diff --git a/src/Build/BackEnd/BuildManager/BuildManager.cs b/src/Build/BackEnd/BuildManager/BuildManager.cs index d2da0c1dbfc..48c1b8909ae 100644 --- a/src/Build/BackEnd/BuildManager/BuildManager.cs +++ b/src/Build/BackEnd/BuildManager/BuildManager.cs @@ -2423,10 +2423,8 @@ private void ReportResultsToSubmission(BuildResult result) lock (_syncLock) { // The build submission has not already been completed. - if (_buildSubmissions.ContainsKey(result.SubmissionId)) + if (_buildSubmissions.TryGetValue(result.SubmissionId, out BuildSubmission submission)) { - BuildSubmission submission = _buildSubmissions[result.SubmissionId]; - /* If the request failed because we caught an exception from the loggers, we can assume we will receive no more logging messages for * this submission, therefore set the logging as complete. InternalLoggerExceptions are unhandled exceptions from the logger. If the logger author does * not handle an exception the eventsource wraps all exceptions (except a logging exception) into an internal logging exception. @@ -2459,9 +2457,8 @@ private void ReportResultsToSubmission(GraphBuildResult result) lock (_syncLock) { // The build submission has not already been completed. - if (_graphBuildSubmissions.ContainsKey(result.SubmissionId)) + if (_graphBuildSubmissions.TryGetValue(result.SubmissionId, out GraphBuildSubmission submission)) { - GraphBuildSubmission submission = _graphBuildSubmissions[result.SubmissionId]; submission.CompleteResults(result); _overallBuildSuccess &= submission.BuildResult.OverallResult == BuildResultCode.Success; diff --git a/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs b/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs index b53e331f9b0..34b563ae053 100644 --- a/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs +++ b/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs @@ -104,10 +104,7 @@ internal void UnregisterSubmissionForLegacyThread(int submissionId) { ErrorUtilities.VerifyThrow(_legacyThreadingEventsById.ContainsKey(submissionId), "Submission {0} should have been previously registered with LegacyThreadingData", submissionId); - if (_legacyThreadingEventsById.ContainsKey(submissionId)) - { - _legacyThreadingEventsById.Remove(submissionId); - } + _legacyThreadingEventsById.Remove(submissionId); } } diff --git a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs index c8301762adc..fec15006b64 100644 --- a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs +++ b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs @@ -230,12 +230,12 @@ public bool ResolveConfigurationRequest(int unresolvedConfigId, int configId) { lock (GlobalLock) { - if (_unresolvedConfigurations?.ContainsKey(unresolvedConfigId) != true) + List requests = null; + if (_unresolvedConfigurations?.TryGetValue(unresolvedConfigId, out requests) != true) { return false; } - List requests = _unresolvedConfigurations[unresolvedConfigId]; _unresolvedConfigurations.Remove(unresolvedConfigId); if (_unresolvedConfigurations.Count == 0) diff --git a/src/Build/BackEnd/Components/Caching/ResultsCache.cs b/src/Build/BackEnd/Components/Caching/ResultsCache.cs index 0cf24b8aa14..ee236fac998 100644 --- a/src/Build/BackEnd/Components/Caching/ResultsCache.cs +++ b/src/Build/BackEnd/Components/Caching/ResultsCache.cs @@ -55,15 +55,15 @@ public void AddResult(BuildResult result) { lock (_resultsByConfiguration) { - if (_resultsByConfiguration.ContainsKey(result.ConfigurationId)) + if (_resultsByConfiguration.TryGetValue(result.ConfigurationId, out BuildResult buildResult)) { - if (Object.ReferenceEquals(_resultsByConfiguration[result.ConfigurationId], result)) + if (Object.ReferenceEquals(buildResult, result)) { // Merging results would be meaningless as we would be merging the object with itself. return; } - _resultsByConfiguration[result.ConfigurationId].MergeResults(result); + buildResult.MergeResults(result); } else { @@ -105,9 +105,8 @@ public BuildResult GetResultForRequest(BuildRequest request) lock (_resultsByConfiguration) { - if (_resultsByConfiguration.ContainsKey(request.ConfigurationId)) + if (_resultsByConfiguration.TryGetValue(request.ConfigurationId, out BuildResult result)) { - BuildResult result = _resultsByConfiguration[request.ConfigurationId]; foreach (string target in request.Targets) { ErrorUtilities.VerifyThrow(result.HasResultsForTarget(target), "No results in cache for target " + target); @@ -159,10 +158,8 @@ public ResultsCacheResponse SatisfyRequest(BuildRequest request, List co lock (_resultsByConfiguration) { - if (_resultsByConfiguration.ContainsKey(request.ConfigurationId)) + if (_resultsByConfiguration.TryGetValue(request.ConfigurationId, out BuildResult allResults)) { - BuildResult allResults = _resultsByConfiguration[request.ConfigurationId]; - // Check for targets explicitly specified. bool explicitTargetsSatisfied = CheckResults(allResults, request.Targets, response.ExplicitTargetsToBuild, skippedResultsDoNotCauseCacheMiss); diff --git a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs index ef746ed27d7..2a917d6eaee 100644 --- a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs +++ b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs @@ -265,9 +265,9 @@ public void UnregisterPacketHandler(NodePacketType packetType) /// The translator containing the data from which the packet should be reconstructed. public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator) { - if (_nodeIdToPacketFactory.ContainsKey(nodeId)) + if (_nodeIdToPacketFactory.TryGetValue(nodeId, out INodePacketFactory nodePacketFactory)) { - _nodeIdToPacketFactory[nodeId].DeserializeAndRoutePacket(nodeId, packetType, translator); + nodePacketFactory.DeserializeAndRoutePacket(nodeId, packetType, translator); } else { @@ -282,9 +282,9 @@ public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITr /// The packet to route. public void RoutePacket(int nodeId, INodePacket packet) { - if (_nodeIdToPacketFactory.ContainsKey(nodeId)) + if (_nodeIdToPacketFactory.TryGetValue(nodeId, out INodePacketFactory nodePacketFactory)) { - _nodeIdToPacketFactory[nodeId].RoutePacket(nodeId, packet); + nodePacketFactory.RoutePacket(nodeId, packet); } else { @@ -304,9 +304,9 @@ public void RoutePacket(int nodeId, INodePacket packet) /// The packet. public void PacketReceived(int node, INodePacket packet) { - if (_nodeIdToPacketHandler.ContainsKey(node)) + if (_nodeIdToPacketHandler.TryGetValue(node, out INodePacketHandler packetHandler)) { - _nodeIdToPacketHandler[node].PacketReceived(node, packet); + packetHandler.PacketReceived(node, packet); } else { diff --git a/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs b/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs index b4fb5ad461c..d7c7cf13ad6 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs @@ -626,12 +626,10 @@ public void LogProjectFinished(BuildEventContext projectBuildEventContext, strin ProcessLoggingEvent(buildEvent); // PERF: Not using VerifyThrow to avoid boxing of projectBuildEventContext.ProjectContextId in the non-error case. - if (!_projectFileMap.ContainsKey(projectBuildEventContext.ProjectContextId)) + if (!_projectFileMap.Remove(projectBuildEventContext.ProjectContextId)) { ErrorUtilities.ThrowInternalError("ContextID {0} for project {1} should be in the ID-to-file mapping!", projectBuildEventContext.ProjectContextId, projectFile); } - - _projectFileMap.Remove(projectBuildEventContext.ProjectContextId); } } diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs index bbe8db85caf..6e0ba6a0d5f 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs @@ -661,10 +661,8 @@ bool runEachTargetSeparately foreach (string targetName in nonNullTargetList) { - if (targetOutputsPerProject[i].ContainsKey(targetName)) + if (targetOutputsPerProject[i].TryGetValue(targetName, out ITaskItem[] outputItemsFromTarget)) { - ITaskItem[] outputItemsFromTarget = targetOutputsPerProject[i][targetName]; - foreach (ITaskItem outputItemFromTarget in outputItemsFromTarget) { // No need to rebase if the calling project is the same as the callee project diff --git a/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs b/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs index 4d0e7f95812..71141924280 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs @@ -210,13 +210,13 @@ internal List GetPropertyOverrideMessages(Dictionary loo string propertyName = property.Name; // If the hash contains the property name, output a messages that displays the previous property value and the new property value - if (lookupHash.ContainsKey(propertyName)) + if (lookupHash.TryGetValue(propertyName, out string propertyValue)) { if (errorMessages == null) { errorMessages = new List(); } - errorMessages.Add(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("PropertyOutputOverridden", propertyName, EscapingUtilities.UnescapeAll(lookupHash[propertyName]), property.EvaluatedValue)); + errorMessages.Add(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("PropertyOutputOverridden", propertyName, EscapingUtilities.UnescapeAll(propertyValue), property.EvaluatedValue)); } // Set the value of the hash to the new property value @@ -945,10 +945,10 @@ private void MustNotBeInTable(ItemDictionary table, Project /// private void MustNotBeInTable(ItemTypeToItemsMetadataUpdateDictionary table, ProjectItemInstance item) { - if (table?.ContainsKey(item.ItemType) == true) + ItemsMetadataUpdateDictionary tableOfItemsOfSameType = null; + if (table?.TryGetValue(item.ItemType, out tableOfItemsOfSameType) == true) { - ItemsMetadataUpdateDictionary tableOfItemsOfSameType = table[item.ItemType]; - if (tableOfItemsOfSameType != null) + if (tableOfItemsOfSameType is not null) { ErrorUtilities.VerifyThrow(!tableOfItemsOfSameType.ContainsKey(item), "Item should not be in table"); } diff --git a/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs index d79147775b7..95c090d5e3e 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs @@ -142,16 +142,16 @@ public async Task BuildTargets(ProjectLoggingContext loggingContext foreach (string targetName in targetNames) { - var targetExists = _projectInstance.Targets.ContainsKey(targetName); + var targetExists = _projectInstance.Targets.TryGetValue(targetName, out ProjectTargetInstance targetInstance); if (!targetExists && entry.Request.BuildRequestDataFlags.HasFlag(BuildRequestDataFlags.SkipNonexistentTargets)) { _projectLoggingContext.LogComment(Framework.MessageImportance.Low, "TargetSkippedWhenSkipNonexistentTargets", targetName); - - continue; } - - targets.Add(new TargetSpecification(targetName, targetExists ? _projectInstance.Targets[targetName].Location : _projectInstance.ProjectFileLocation)); + else + { + targets.Add(new TargetSpecification(targetName, targetExists ? targetInstance.Location : _projectInstance.ProjectFileLocation)); + } } // Push targets onto the stack. This method will reverse their push order so that they @@ -484,13 +484,7 @@ private async Task ProcessTargetStack(ITaskBuilder taskBuilder) } catch { - if (_requestEntry.RequestConfiguration.ActivelyBuildingTargets.ContainsKey( - currentTargetEntry.Name)) - { - _requestEntry.RequestConfiguration.ActivelyBuildingTargets.Remove(currentTargetEntry - .Name); - } - + _requestEntry.RequestConfiguration.ActivelyBuildingTargets.Remove(currentTargetEntry.Name); throw; } } @@ -764,7 +758,7 @@ private void ComputeAfterTargetFailures(string[] targetNames) { foreach (string targetName in targetNames) { - if (_buildResult.ResultsByTarget.ContainsKey(targetName)) + if (_buildResult.ResultsByTarget.TryGetValue(targetName, out TargetResult targetBuildResult)) { // Queue of targets waiting to be processed, seeded with the specific target for which we're computing AfterTargetsHaveFailed. var targetsToCheckForAfterTargets = new Queue(); @@ -785,7 +779,7 @@ private void ComputeAfterTargetFailures(string[] targetNames) if (result?.ResultCode == TargetResultCode.Failure && !result.TargetFailureDoesntCauseBuildFailure) { // Mark the target as having an after target failed, and break the loop to move to the next target. - _buildResult.ResultsByTarget[targetName].AfterTargetsHaveFailed = true; + targetBuildResult.AfterTargetsHaveFailed = true; targetsToCheckForAfterTargets = null; break; } diff --git a/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs b/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs index 590cc2c74a9..1d76dd9405d 100644 --- a/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs +++ b/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs @@ -629,9 +629,7 @@ private void CleanupForCircularDependencyAndThrow(SchedulableRequest requestCaus /// internal void DisconnectRequestWeAreBlockedBy(BlockingRequestKey blockingRequestKey) { - ErrorUtilities.VerifyThrow(_requestsWeAreBlockedBy.ContainsKey(blockingRequestKey), "We are not blocked by the specified request."); - - SchedulableRequest unblockingRequest = _requestsWeAreBlockedBy[blockingRequestKey]; + ErrorUtilities.VerifyThrow(_requestsWeAreBlockedBy.TryGetValue(blockingRequestKey, out SchedulableRequest unblockingRequest), "We are not blocked by the specified request."); ErrorUtilities.VerifyThrow(unblockingRequest._requestsWeAreBlocking.Contains(this), "The request unblocking us doesn't think it is blocking us."); _requestsWeAreBlockedBy.Remove(blockingRequestKey); diff --git a/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs b/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs index 804ac117b8a..34a1d880842 100644 --- a/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs +++ b/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs @@ -360,9 +360,9 @@ public void UpdateFromState(SchedulableRequest request, SchedulableRequestState ErrorUtilities.VerifyThrow(_configurationToRequests.ContainsKey(request.BuildRequest.ConfigurationId), "Configuration {0} never had requests assigned to it.", request.BuildRequest.ConfigurationId); ErrorUtilities.VerifyThrow(_configurationToRequests[request.BuildRequest.ConfigurationId].Count > 0, "Configuration {0} has no requests assigned to it.", request.BuildRequest.ConfigurationId); _configurationToRequests[request.BuildRequest.ConfigurationId].Remove(request); - if (_scheduledRequestsByNode.ContainsKey(request.AssignedNode)) + if (_scheduledRequestsByNode.TryGetValue(request.AssignedNode, out var requests)) { - _scheduledRequestsByNode[request.AssignedNode].Remove(request); + requests.Remove(request); } request.EndTime = EventTime; diff --git a/src/Build/BackEnd/Shared/BuildResult.cs b/src/Build/BackEnd/Shared/BuildResult.cs index ec989c4e92d..67138103af8 100644 --- a/src/Build/BackEnd/Shared/BuildResult.cs +++ b/src/Build/BackEnd/Shared/BuildResult.cs @@ -470,9 +470,9 @@ public void AddResultsForTarget(string target, TargetResult result) _resultsByTarget ??= CreateTargetResultDictionary(1); } - if (_resultsByTarget.ContainsKey(target)) + if (_resultsByTarget.TryGetValue(target, out TargetResult targetResult)) { - ErrorUtilities.VerifyThrow(_resultsByTarget[target].ResultCode == TargetResultCode.Skipped, "Items already exist for target {0}.", target); + ErrorUtilities.VerifyThrow(targetResult.ResultCode == TargetResultCode.Skipped, "Items already exist for target {0}.", target); } _resultsByTarget[target] = result; diff --git a/src/Build/Construction/Solution/SolutionFile.cs b/src/Build/Construction/Solution/SolutionFile.cs index d16447e69c1..7de69fea0c3 100644 --- a/src/Build/Construction/Solution/SolutionFile.cs +++ b/src/Build/Construction/Solution/SolutionFile.cs @@ -617,7 +617,7 @@ internal void ParseSolution() } // Detect collision caused by unique name's normalization - if (projectsByUniqueName.ContainsKey(uniqueName)) + if (projectsByUniqueName.TryGetValue(uniqueName, out ProjectInSolution project)) { // Did normalization occur in the current project? if (uniqueName != proj.ProjectName) @@ -628,16 +628,14 @@ internal void ParseSolution() uniqueName = tempUniqueName; } // Did normalization occur in a previous project? - else if (uniqueName != projectsByUniqueName[uniqueName].ProjectName) + else if (uniqueName != project.ProjectName) { - var projTemp = projectsByUniqueName[uniqueName]; - // Generates a new unique name - string tempUniqueName = $"{uniqueName}_{projTemp.GetProjectGuidWithoutCurlyBrackets()}"; - projTemp.UpdateUniqueProjectName(tempUniqueName); + string tempUniqueName = $"{uniqueName}_{project.GetProjectGuidWithoutCurlyBrackets()}"; + project.UpdateUniqueProjectName(tempUniqueName); projectsByUniqueName.Remove(uniqueName); - projectsByUniqueName.Add(tempUniqueName, projTemp); + projectsByUniqueName.Add(tempUniqueName, project); } } diff --git a/src/Build/Construction/Solution/SolutionProjectGenerator.cs b/src/Build/Construction/Solution/SolutionProjectGenerator.cs index 30b2b3c4316..d291d172bde 100644 --- a/src/Build/Construction/Solution/SolutionProjectGenerator.cs +++ b/src/Build/Construction/Solution/SolutionProjectGenerator.cs @@ -783,7 +783,7 @@ private void EvaluateAndAddProjects(List projectsInOrder, Lis AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, "Publish", null, canBuildDirectly); // Add any other targets specified by the user that were not already added - foreach (string targetName in _targetNames.Where(i => !traversalInstance.Targets.ContainsKey(i))) + foreach (string targetName in _targetNames.Except(traversalInstance.Targets.Keys, StringComparer.OrdinalIgnoreCase)) { AddTraversalTargetForProject(traversalInstance, project, projectConfiguration, targetName, null, canBuildDirectly); } @@ -797,7 +797,7 @@ private void EvaluateAndAddProjects(List projectsInOrder, Lis } // Add any other targets specified by the user that were not already added - foreach (string targetName in _targetNames.Where(i => !traversalInstance.Targets.ContainsKey(i))) + foreach (string targetName in _targetNames.Except(traversalInstance.Targets.Keys, StringComparer.OrdinalIgnoreCase)) { AddTraversalReferencesTarget(traversalInstance, targetName, null); } @@ -1202,7 +1202,7 @@ private ProjectInstance CreateMetaproject(ProjectInstance traversalProject, Proj AddMetaprojectTargetForWebProject(traversalProject, metaprojectInstance, project, "Rebuild"); AddMetaprojectTargetForWebProject(traversalProject, metaprojectInstance, project, "Publish"); - foreach (string targetName in _targetNames.Where(i => !metaprojectInstance.Targets.ContainsKey(i))) + foreach (string targetName in _targetNames.Except(metaprojectInstance.Targets.Keys, StringComparer.OrdinalIgnoreCase)) { AddMetaprojectTargetForWebProject(traversalProject, metaprojectInstance, project, targetName); } @@ -1222,7 +1222,7 @@ private ProjectInstance CreateMetaproject(ProjectInstance traversalProject, Proj AddMetaprojectTargetForManagedProject(traversalProject, metaprojectInstance, project, projectConfiguration, "Rebuild", targetOutputItemName); AddMetaprojectTargetForManagedProject(traversalProject, metaprojectInstance, project, projectConfiguration, "Publish", null); - foreach (string targetName in _targetNames.Where(i => !metaprojectInstance.Targets.ContainsKey(i))) + foreach (string targetName in _targetNames.Except(metaprojectInstance.Targets.Keys, StringComparer.OrdinalIgnoreCase)) { AddMetaprojectTargetForManagedProject(traversalProject, metaprojectInstance, project, projectConfiguration, targetName, null); } @@ -1234,7 +1234,7 @@ private ProjectInstance CreateMetaproject(ProjectInstance traversalProject, Proj AddMetaprojectTargetForUnknownProjectType(traversalProject, metaprojectInstance, project, "Rebuild", unknownProjectTypeErrorMessage); AddMetaprojectTargetForUnknownProjectType(traversalProject, metaprojectInstance, project, "Publish", unknownProjectTypeErrorMessage); - foreach (string targetName in _targetNames.Where(i => !metaprojectInstance.Targets.ContainsKey(i))) + foreach (string targetName in _targetNames.Except(metaprojectInstance.Targets.Keys, StringComparer.OrdinalIgnoreCase)) { AddMetaprojectTargetForUnknownProjectType(traversalProject, metaprojectInstance, project, targetName, unknownProjectTypeErrorMessage); } diff --git a/src/Build/Definition/Project.cs b/src/Build/Definition/Project.cs index 285c4cc592a..f158ca5a2bb 100644 --- a/src/Build/Definition/Project.cs +++ b/src/Build/Definition/Project.cs @@ -2564,10 +2564,10 @@ private GlobResult BuildGlobResultFromIncludeItem(ProjectItemElement itemElement IEnumerable removeFragmentStrings = Enumerable.Empty(); IMSBuildGlob removeGlob = null; - if (removeElementCache.ContainsKey(itemElement.ItemType)) + if (removeElementCache.TryGetValue(itemElement.ItemType, out CumulativeRemoveElementData removeItemElement)) { - removeFragmentStrings = removeElementCache[itemElement.ItemType].FragmentStrings; - removeGlob = new CompositeGlob(removeElementCache[itemElement.ItemType].Globs); + removeFragmentStrings = removeItemElement.FragmentStrings; + removeGlob = new CompositeGlob(removeItemElement.Globs); } var includeGlobWithGaps = CreateIncludeGlobWithGaps(includeGlob, excludeGlob, removeGlob); @@ -2577,27 +2577,17 @@ private GlobResult BuildGlobResultFromIncludeItem(ProjectItemElement itemElement private static IMSBuildGlob CreateIncludeGlobWithGaps(IMSBuildGlob includeGlob, IMSBuildGlob excludeGlob, IMSBuildGlob removeGlob) { - if (excludeGlob != null && removeGlob != null) + if (excludeGlob == null) { - return new MSBuildGlobWithGaps( - includeGlob, - new CompositeGlob( - excludeGlob, - removeGlob - )); + return removeGlob == null ? includeGlob : + new MSBuildGlobWithGaps(includeGlob, removeGlob); } - - if (excludeGlob != null || removeGlob != null) + else { - var gapGlob = excludeGlob ?? removeGlob; - - return new MSBuildGlobWithGaps( - includeGlob, - gapGlob - ); + return new MSBuildGlobWithGaps(includeGlob, + removeGlob == null ? excludeGlob : + new CompositeGlob(excludeGlob, removeGlob)); } - - return includeGlob; } private void CacheInformationFromRemoveItem(ProjectItemElement itemElement, Dictionary removeElementCache) diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 88c7f74bca7..451a26ef506 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -1615,12 +1615,11 @@ private bool RemoveToolsetInternal(string toolsVersion) { Debug.Assert(_locker.IsWriteLockHeld); - if (!_toolsets.ContainsKey(toolsVersion)) + if (!_toolsets.Remove(toolsVersion)) { return false; } - _toolsets.Remove(toolsVersion); _toolsetsVersion++; return true; } diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index 9b3b8028ed7..f9126e6c61f 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -849,14 +849,10 @@ private void PerformDepthFirstPass(ProjectRootElement currentProjectOrImport) _itemDefinitionGroupElements.Add(itemDefinitionGroup); break; case ProjectTargetElement target: - if (_projectSupportsReturnsAttribute.ContainsKey(currentProjectOrImport)) - { - _projectSupportsReturnsAttribute[currentProjectOrImport] |= (target.Returns != null); - } - else - { - _projectSupportsReturnsAttribute[currentProjectOrImport] = (target.Returns != null); - } + // Defaults to false + _projectSupportsReturnsAttribute.TryGetValue(currentProjectOrImport, out NGen projectSupportsReturnsAttribute); + + _projectSupportsReturnsAttribute[currentProjectOrImport] = projectSupportsReturnsAttribute || (target.Returns != null); _targetElements.Add(target); break; case ProjectImportElement import: diff --git a/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs b/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs index 9934759efbf..b072a36f854 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs @@ -162,10 +162,8 @@ private string RouteCall(string itemType, string name, Func { - ErrorUtilities.VerifyThrow(projectsByPath.ContainsKey(referencedProjectPath), "nodes should include solution projects"); - - return projectsByPath[referencedProjectPath]; + ErrorUtilities.VerifyThrow(projectsByPath.TryGetValue(referencedProjectPath, out List projectToReturn), "nodes should include solution projects"); + return projectToReturn; }).ToArray(); - var referencingNodes = projectsByPath[referencingProjectPath]; - foreach (var referencingNode in referencingNodes) { foreach (var referencedNode in referencedNodes) @@ -310,12 +307,12 @@ IReadOnlyCollection GetBuildableProjects(SolutionFile solutio SolutionConfigurationInSolution SelectSolutionConfiguration(SolutionFile solutionFile, ImmutableDictionary globalProperties) { - var solutionConfiguration = globalProperties.ContainsKey("Configuration") - ? globalProperties["Configuration"] + var solutionConfiguration = globalProperties.TryGetValue("Configuration", out string configuration) + ? configuration : solutionFile.GetDefaultConfigurationName(); - var solutionPlatform = globalProperties.ContainsKey("Platform") - ? globalProperties["Platform"] + var solutionPlatform = globalProperties.TryGetValue("Platform", out string platform) + ? platform : solutionFile.GetDefaultPlatformName(); return new SolutionConfigurationInSolution(solutionConfiguration, solutionPlatform); @@ -329,9 +326,9 @@ SolutionConfigurationInSolution SelectSolutionConfiguration(SolutionFile solutio var solutionConfigFullName = solutionConfig.FullName; - if (projectConfigs.ContainsKey(solutionConfigFullName)) + if (projectConfigs.TryGetValue(solutionConfigFullName, out ProjectConfigurationInSolution projectConfiguration)) { - return projectConfigs[solutionConfigFullName]; + return projectConfiguration; } var partiallyMarchedConfig = projectConfigs.FirstOrDefault(pc => pc.Value.ConfigurationName.Equals(solutionConfig.ConfigurationName, StringComparison.OrdinalIgnoreCase)).Value; @@ -417,14 +414,14 @@ void AddGraphBuildGlobalVariable(PropertyDictionary glo foreach (var entryPointNode in entryPointNodes) { - if (!nodeStates.ContainsKey(entryPointNode)) + if (!nodeStates.TryGetValue(entryPointNode, out NodeVisitationState state)) { VisitNode(entryPointNode, nodeStates); } else { ErrorUtilities.VerifyThrow( - nodeStates[entryPointNode] == NodeVisitationState.Processed, + state == NodeVisitationState.Processed, "entrypoints should get processed after a call to detect cycles"); } } @@ -616,8 +613,8 @@ internal class GraphEdges { get { - ErrorUtilities.VerifyThrow(ReferenceItems.ContainsKey(key), "All requested keys should exist"); - return ReferenceItems[key]; + ErrorUtilities.VerifyThrow(ReferenceItems.TryGetValue(key, out ProjectItemInstance referenceItem), "All requested keys should exist"); + return referenceItem; } // First edge wins, in accordance with vanilla msbuild behaviour when multiple msbuild tasks call into the same logical project @@ -626,9 +623,7 @@ internal class GraphEdges public void RemoveEdge((ProjectGraphNode node, ProjectGraphNode reference) key) { - ErrorUtilities.VerifyThrow(ReferenceItems.ContainsKey(key), "All requested keys should exist"); - - ReferenceItems.TryRemove(key, out _); + ErrorUtilities.VerifyThrow(ReferenceItems.TryRemove(key, out _), "All requested keys should exist"); } internal bool HasEdge((ProjectGraphNode node, ProjectGraphNode reference) key) => ReferenceItems.ContainsKey(key); diff --git a/src/Build/Instance/HostServices.cs b/src/Build/Instance/HostServices.cs index 98c03f1fe7a..a27e5787cfb 100644 --- a/src/Build/Instance/HostServices.cs +++ b/src/Build/Instance/HostServices.cs @@ -181,15 +181,8 @@ public void UnregisterProject(string projectFullPath) { if (projectFullPath != null) { - if (_hostObjectMap?.ContainsKey(projectFullPath) == true) - { - _hostObjectMap.Remove(projectFullPath); - } - - if (_projectAffinities?.ContainsKey(projectFullPath) == true) - { - _projectAffinities.Remove(projectFullPath); - } + _hostObjectMap?.Remove(projectFullPath); + _projectAffinities?.Remove(projectFullPath); } } @@ -323,14 +316,15 @@ void ITranslatable.Translate(ITranslator translator) var hostObjectMapPairKeyTaskName = translator.Reader.ReadString(); var hostObjectMapPairValueMonikerName = translator.Reader.ReadString(); var targetTaskKey = new HostObjects.TargetTaskKey(hostObjectMapPairKeyTargetName, hostObjectMapPairKeyTaskName); - if (!hostObjectMap.ContainsKey(pairKey)) + if (!hostObjectMap.TryGetValue(pairKey, out HostObjects hostObject)) { - hostObjectMap[pairKey] = new HostObjects(); + hostObject = new HostObjects(); + hostObjectMap[pairKey] = hostObject; } - if (!hostObjectMap[pairKey]._hostObjects.ContainsKey(targetTaskKey)) + if (!hostObject._hostObjects.ContainsKey(targetTaskKey)) { - hostObjectMap[pairKey]._hostObjects.Add(targetTaskKey, new MonikerNameOrITaskHost(hostObjectMapPairValueMonikerName)); + hostObject._hostObjects.Add(targetTaskKey, new MonikerNameOrITaskHost(hostObjectMapPairValueMonikerName)); } } _hostObjectMap = hostObjectMap; diff --git a/src/Build/Instance/ProjectInstance.cs b/src/Build/Instance/ProjectInstance.cs index bd160b2f66c..97b497e5659 100644 --- a/src/Build/Instance/ProjectInstance.cs +++ b/src/Build/Instance/ProjectInstance.cs @@ -2378,7 +2378,7 @@ internal void RetrieveFromCache(ITranslator translator) parentProjectSupportsReturnsAttribute ); - _actualTargets[target.Name] = target; + _actualTargets[targetName] = target; return target; } diff --git a/src/Build/Instance/TaskFactories/TaskHostTask.cs b/src/Build/Instance/TaskFactories/TaskHostTask.cs index 4956e1383cd..5c7da148de3 100644 --- a/src/Build/Instance/TaskFactories/TaskHostTask.cs +++ b/src/Build/Instance/TaskFactories/TaskHostTask.cs @@ -197,10 +197,8 @@ public void SetPropertyValue(TaskPropertyInfo property, object value) /// public object GetPropertyValue(TaskPropertyInfo property) { - if (_setParameters.ContainsKey(property.Name)) + if (_setParameters.TryGetValue(property.Name, out object value)) { - object value = _setParameters[property.Name]; - // If we returned an exception, then we want to throw it when we // do the get. if (value is Exception) @@ -208,7 +206,7 @@ public object GetPropertyValue(TaskPropertyInfo property) throw (Exception)value; } - return _setParameters[property.Name]; + return value; } else { diff --git a/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs b/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs index 2a74ec78a0d..bae76905916 100644 --- a/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs +++ b/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs @@ -429,14 +429,14 @@ private void ShowErrorWarningSummary(IEnumerable listToProcess) // Check to see if there is a bucket for the warning // If there is no bucket create a new one which contains a list of all the errors which // happened for a given buildEventContext / target - if (!groupByProjectEntryPoint.ContainsKey(key)) + if (!groupByProjectEntryPoint.TryGetValue(key, out var errorWarningEventListByTarget)) { // happened for a given buildEventContext / target - var errorWarningEventListByTarget = new List(); + errorWarningEventListByTarget = new List(); groupByProjectEntryPoint.Add(key, errorWarningEventListByTarget); } // Add the error event to the correct bucket - groupByProjectEntryPoint[key].Add(errorWarningEventArgs); + errorWarningEventListByTarget.Add(errorWarningEventArgs); } BuildEventContext previousEntryPoint = null; @@ -505,11 +505,11 @@ public override void ProjectStartedHandler(object sender, ProjectStartedEventArg } // If there were deferred messages then we should show them now, this will cause the project started event to be shown properly - if (_deferredMessages.ContainsKey(e.BuildEventContext)) + if (_deferredMessages.TryGetValue(e.BuildEventContext, out var deferredMessages)) { if (!showOnlyErrors && !showOnlyWarnings) { - foreach (BuildMessageEventArgs message in _deferredMessages[e.BuildEventContext]) + foreach (BuildMessageEventArgs message in deferredMessages) { // This will display the project started event before the messages is shown this.MessageHandler(sender, message); @@ -1098,12 +1098,7 @@ public override void MessageHandler(object sender, BuildMessageEventArgs e) && IsVerbosityAtLeast(LoggerVerbosity.Normal) ) { - List messageList; - if (_deferredMessages.ContainsKey(e.BuildEventContext)) - { - messageList = _deferredMessages[e.BuildEventContext]; - } - else + if (!_deferredMessages.TryGetValue(e.BuildEventContext, out List messageList)) { messageList = new List(); _deferredMessages.Add(e.BuildEventContext, messageList); @@ -1689,11 +1684,11 @@ internal void AddEventFinished(string projectTargetNames, BuildEventContext buil ErrorUtilities.VerifyThrow(_startedEvent != null, "Cannot have finished counter without started counter. "); - if (_startedEvent.ContainsKey(buildEventContext)) + if (_startedEvent.TryGetValue(buildEventContext, out object time)) { // Calculate the amount of time spent in the event based on the time stamp of when // the started event was created and when the finished event was created - elapsedTime += (TimeSpan.FromTicks(eventTimeStamp.Ticks - (long)_startedEvent[buildEventContext])); + elapsedTime += (TimeSpan.FromTicks(eventTimeStamp.Ticks - (long)time)); _startedEvent.Remove(buildEventContext); } } diff --git a/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs b/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs index 9e25d8e62e7..8b9c74e5085 100644 --- a/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs +++ b/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs @@ -47,23 +47,18 @@ internal void AddProjectStartedEvent(ProjectStartedEventArgs e, bool requireTime int projectTargetKeyLocal = 1; int projectIncrementKeyLocal; // If we haven't seen this project before (by full path) then - // allocate a new key for it and save it away - if (!_projectKey.ContainsKey(e.ProjectFile)) + // allocate a new key for it and save it away. Otherwise, retrieve it. + if (!_projectKey.TryGetValue(e.ProjectFile, out projectIncrementKeyLocal)) { _projectIncrementKey++; _projectKey[e.ProjectFile] = _projectIncrementKey; projectIncrementKeyLocal = _projectIncrementKey; } - else - { - // We've seen this project before, so retrieve it - projectIncrementKeyLocal = _projectKey[e.ProjectFile]; - } // If we haven't seen any entrypoint for the current project (by full path) then // allocate a new entry point key - if (!_projectTargetKey.ContainsKey(e.ProjectFile)) + if (!_projectTargetKey.TryGetValue(e.ProjectFile, out int tempProjectTargetKeyLocal)) { _projectTargetKey[e.ProjectFile] = projectTargetKeyLocal; } @@ -71,7 +66,7 @@ internal void AddProjectStartedEvent(ProjectStartedEventArgs e, bool requireTime { // We've seen this project before, but not this entrypoint, so increment // the entrypoint key that we have. - projectTargetKeyLocal = _projectTargetKey[e.ProjectFile] + 1; + projectTargetKeyLocal = tempProjectTargetKeyLocal + 1; _projectTargetKey[e.ProjectFile] = projectTargetKeyLocal; } @@ -173,15 +168,7 @@ internal string[] ProjectCallStackFromProject(BuildEventContext e) /// internal ProjectStartedEventMinimumFields GetProjectStartedEvent(BuildEventContext e) { - ProjectStartedEventMinimumFields buildEvent; - if (_projectStartedEvents.ContainsKey(e)) - { - buildEvent = _projectStartedEvents[e]; - } - else - { - buildEvent = null; - } + _projectStartedEvents.TryGetValue(e, out ProjectStartedEventMinimumFields buildEvent); return buildEvent; } @@ -190,15 +177,7 @@ internal ProjectStartedEventMinimumFields GetProjectStartedEvent(BuildEventConte /// internal TargetStartedEventMinimumFields GetTargetStartedEvent(BuildEventContext e) { - TargetStartedEventMinimumFields buildEvent; - if (_targetStartedEvents.ContainsKey(e)) - { - buildEvent = _targetStartedEvents[e]; - } - else - { - buildEvent = null; - } + _targetStartedEvents.TryGetValue(e, out TargetStartedEventMinimumFields buildEvent); return buildEvent; } diff --git a/src/Shared/CommunicationsUtilities.cs b/src/Shared/CommunicationsUtilities.cs index 26859071fc0..e5333429e68 100644 --- a/src/Shared/CommunicationsUtilities.cs +++ b/src/Shared/CommunicationsUtilities.cs @@ -478,11 +478,11 @@ internal static HandshakeOptions GetHandshakeOptions(bool taskHost, bool is64Bit } else { - ErrorUtilities.VerifyThrow(taskHostParameters.ContainsKey(XMakeAttributes.runtime), "Should always have an explicit runtime when we call this method."); - ErrorUtilities.VerifyThrow(taskHostParameters.ContainsKey(XMakeAttributes.architecture), "Should always have an explicit architecture when we call this method."); + ErrorUtilities.VerifyThrow(taskHostParameters.TryGetValue(XMakeAttributes.runtime, out string runtimeVersion), "Should always have an explicit runtime when we call this method."); + ErrorUtilities.VerifyThrow(taskHostParameters.TryGetValue(XMakeAttributes.architecture, out string architecture), "Should always have an explicit architecture when we call this method."); - clrVersion = taskHostParameters[XMakeAttributes.runtime].Equals(XMakeAttributes.MSBuildRuntimeValues.clr4, StringComparison.OrdinalIgnoreCase) ? 4 : 2; - is64Bit = taskHostParameters[XMakeAttributes.architecture].Equals(XMakeAttributes.MSBuildArchitectureValues.x64); + clrVersion = runtimeVersion.Equals(XMakeAttributes.MSBuildRuntimeValues.clr4, StringComparison.OrdinalIgnoreCase) ? 4 : 2; + is64Bit = architecture.Equals(XMakeAttributes.MSBuildArchitectureValues.x64); } } diff --git a/src/Shared/FrameworkLocationHelper.cs b/src/Shared/FrameworkLocationHelper.cs index 8544c12acd2..006e0587bf1 100644 --- a/src/Shared/FrameworkLocationHelper.cs +++ b/src/Shared/FrameworkLocationHelper.cs @@ -1068,14 +1068,14 @@ private static string FindRegistryValueUnderKey private static VisualStudioSpec GetVisualStudioSpec(Version version) { - ErrorUtilities.VerifyThrowArgument(s_visualStudioSpecDict.ContainsKey(version), "FrameworkLocationHelper.UnsupportedVisualStudioVersion", version); - return s_visualStudioSpecDict[version]; + ErrorUtilities.VerifyThrowArgument(s_visualStudioSpecDict.TryGetValue(version, out VisualStudioSpec spec), "FrameworkLocationHelper.UnsupportedVisualStudioVersion", version); + return spec; } private static DotNetFrameworkSpec GetDotNetFrameworkSpec(Version version) { - ErrorUtilities.VerifyThrowArgument(s_dotNetFrameworkSpecDict.ContainsKey(version), "FrameworkLocationHelper.UnsupportedFrameworkVersion", version); - return s_dotNetFrameworkSpecDict[version]; + ErrorUtilities.VerifyThrowArgument(s_dotNetFrameworkSpecDict.TryGetValue(version, out DotNetFrameworkSpec spec), "FrameworkLocationHelper.UnsupportedFrameworkVersion", version); + return spec; } /// diff --git a/src/Shared/NodePacketFactory.cs b/src/Shared/NodePacketFactory.cs index 25d4851fc82..17b3e52c8f7 100644 --- a/src/Shared/NodePacketFactory.cs +++ b/src/Shared/NodePacketFactory.cs @@ -48,12 +48,11 @@ public void UnregisterPacketHandler(NodePacketType packetType) public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator) { // PERF: Not using VerifyThrow to avoid boxing of packetType in the non-error case - if (!_packetFactories.ContainsKey(packetType)) + if (!_packetFactories.TryGetValue(packetType, out PacketFactoryRecord record)) { ErrorUtilities.ThrowInternalError("No packet handler for type {0}", packetType); } - PacketFactoryRecord record = _packetFactories[packetType]; record.DeserializeAndRoutePacket(nodeId, translator); } diff --git a/src/Shared/VersionUtilities.cs b/src/Shared/VersionUtilities.cs index ab4a2a2ba5c..fe113266894 100644 --- a/src/Shared/VersionUtilities.cs +++ b/src/Shared/VersionUtilities.cs @@ -39,9 +39,8 @@ internal static Version ConvertToVersion(string version) if (candidateVersion != null && (targetPlatformVersion == null || (candidateVersion <= targetPlatformVersion))) { - if (versionValues.ContainsKey(candidateVersion)) + if (versionValues.TryGetValue(candidateVersion, out List versionList)) { - List versionList = versionValues[candidateVersion]; if (!versionList.Contains(version)) { versionList.Add(version); @@ -128,4 +127,4 @@ int IComparer.Compare(Version x, Version y) return y.CompareTo(x); } } -} \ No newline at end of file +} diff --git a/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs b/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs index b0da1661f29..147a65313eb 100644 --- a/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs +++ b/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs @@ -280,9 +280,8 @@ bool specificVersion } else { - if (fusionNameToResolvedPath.ContainsKey(strongName)) + if (fusionNameToResolvedPath.TryGetValue(strongName, out string fusionName)) { - fusionNameToResolvedPath.TryGetValue(strongName, out string fusionName); return fusionName; } } diff --git a/src/Tasks/AssemblyDependency/Reference.cs b/src/Tasks/AssemblyDependency/Reference.cs index c9761c6d469..e5b3b361455 100644 --- a/src/Tasks/AssemblyDependency/Reference.cs +++ b/src/Tasks/AssemblyDependency/Reference.cs @@ -148,8 +148,7 @@ internal Reference(IsWinMDFile isWinMDFile, FileExists fileExists, GetAssemblyRu internal void AddSourceItem(ITaskItem sourceItem) { string itemSpec = sourceItem.ItemSpec; - bool sourceItemAlreadyInList = _sourceItems.ContainsKey(itemSpec); - if (!sourceItemAlreadyInList) + if (!_sourceItems.ContainsKey(itemSpec)) { _sourceItems[itemSpec] = sourceItem; PropagateSourceItems(sourceItem); diff --git a/src/Tasks/AssemblyDependency/ReferenceTable.cs b/src/Tasks/AssemblyDependency/ReferenceTable.cs index dcc38343d3c..5967f4c1cdf 100644 --- a/src/Tasks/AssemblyDependency/ReferenceTable.cs +++ b/src/Tasks/AssemblyDependency/ReferenceTable.cs @@ -327,14 +327,7 @@ internal ReferenceTable if (sdkName.Length > 0) { - if (!_resolvedSDKReferences.ContainsKey(sdkName)) - { - _resolvedSDKReferences.Add(sdkName, resolvedSDK); - } - else - { - _resolvedSDKReferences[sdkName] = resolvedSDK; - } + _resolvedSDKReferences[sdkName] = resolvedSDK; } } } @@ -406,9 +399,8 @@ internal ReferenceTable internal void AddReference(AssemblyNameExtension assemblyName, Reference reference) { ErrorUtilities.VerifyThrow(assemblyName.Name != null, "Got an empty assembly name."); - if (References.ContainsKey(assemblyName)) + if (References.TryGetValue(assemblyName, out Reference referenceGoingToBeReplaced)) { - Reference referenceGoingToBeReplaced = References[assemblyName]; foreach (AssemblyRemapping pair in referenceGoingToBeReplaced.RemappedAssemblyNames()) { reference.AddRemapping(pair.From, pair.To); @@ -3197,15 +3189,12 @@ internal bool MarkReferencesForExclusion(Dictionary exclusionLis if (!reference.CheckForSpecificVersionMetadataOnParentsReference(false)) { // Check to see if the reference is not in a profile or subset - if (exclusionList != null) + if (exclusionList?.ContainsKey(assemblyFullName) == true) { - if (exclusionList.ContainsKey(assemblyFullName)) - { - anyMarkedReference = true; - reference.ExclusionListLoggingProperties.ExclusionReasonLogDelegate = LogProfileExclusionUnresolve; - reference.ExclusionListLoggingProperties.IsInExclusionList = true; - ListOfExcludedAssemblies.Add(assemblyFullName); - } + anyMarkedReference = true; + reference.ExclusionListLoggingProperties.ExclusionReasonLogDelegate = LogProfileExclusionUnresolve; + reference.ExclusionListLoggingProperties.IsInExclusionList = true; + ListOfExcludedAssemblies.Add(assemblyFullName); } // Check to see if the reference is in the current target framework but has a higher version than what exists in the target framework diff --git a/src/Tasks/GenerateBootstrapper.cs b/src/Tasks/GenerateBootstrapper.cs index 98ffca90a5e..ff94ae73668 100644 --- a/src/Tasks/GenerateBootstrapper.cs +++ b/src/Tasks/GenerateBootstrapper.cs @@ -118,10 +118,9 @@ public override bool Execute() foreach (Product product in products) { - if (items.ContainsKey(product.ProductCode)) + if (items.Remove(product.ProductCode)) { settings.ProductBuilders.Add(product.ProductBuilder); - items.Remove(product.ProductCode); } } diff --git a/src/Tasks/InstalledSDKResolver.cs b/src/Tasks/InstalledSDKResolver.cs index 427cc8c86eb..ac0ff362d0b 100644 --- a/src/Tasks/InstalledSDKResolver.cs +++ b/src/Tasks/InstalledSDKResolver.cs @@ -52,10 +52,8 @@ public override bool Resolve if (assemblyName != null) { // We have found a resolved SDK item that matches the one on the reference items. - if (_resolvedSDKs.ContainsKey(sdkName)) + if (_resolvedSDKs.TryGetValue(sdkName, out ITaskItem resolvedSDK)) { - ITaskItem resolvedSDK = _resolvedSDKs[sdkName]; - string sdkDirectory = resolvedSDK.ItemSpec; string configuration = resolvedSDK.GetMetadata("TargetedSDKConfiguration"); string architecture = resolvedSDK.GetMetadata("TargetedSDKArchitecture"); diff --git a/src/Tasks/MSBuild.cs b/src/Tasks/MSBuild.cs index de2da27930b..0d5fe24e603 100644 --- a/src/Tasks/MSBuild.cs +++ b/src/Tasks/MSBuild.cs @@ -611,10 +611,8 @@ string toolsVersion foreach (string targetName in nonNullTargetList) { - if (targetOutputsPerProject[i].ContainsKey(targetName)) + if (targetOutputsPerProject[i].TryGetValue(targetName, out ITaskItem[] outputItemsFromTarget)) { - ITaskItem[] outputItemsFromTarget = targetOutputsPerProject[i][targetName]; - foreach (ITaskItem outputItemFromTarget in outputItemsFromTarget) { // No need to rebase if the calling project is the same as the callee project diff --git a/src/Tasks/ManifestUtil/ApplicationManifest.cs b/src/Tasks/ManifestUtil/ApplicationManifest.cs index d5a7628a245..4db84f02967 100644 --- a/src/Tasks/ManifestUtil/ApplicationManifest.cs +++ b/src/Tasks/ManifestUtil/ApplicationManifest.cs @@ -421,25 +421,25 @@ private void ValidateCom() if (!String.IsNullOrEmpty(comInfo.ClsId)) { string key = comInfo.ClsId.ToLowerInvariant(); - if (!clsidList.ContainsKey(key)) + if (!clsidList.TryGetValue(key, out ComInfo info)) { clsidList.Add(key, comInfo); } else { - OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "clsid", comInfo.ComponentFileName, comInfo.ClsId, comInfo.ManifestFileName, clsidList[key].ManifestFileName); + OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "clsid", comInfo.ComponentFileName, comInfo.ClsId, comInfo.ManifestFileName, info.ManifestFileName); } } if (!String.IsNullOrEmpty(comInfo.TlbId)) { string key = comInfo.TlbId.ToLowerInvariant(); - if (!tlbidList.ContainsKey(key)) + if (!tlbidList.TryGetValue(key, out ComInfo info)) { tlbidList.Add(key, comInfo); } else { - OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "tlbid", comInfo.ComponentFileName, comInfo.TlbId, comInfo.ManifestFileName, tlbidList[key].ManifestFileName); + OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "tlbid", comInfo.ComponentFileName, comInfo.TlbId, comInfo.ManifestFileName, info.ManifestFileName); } } } @@ -455,13 +455,13 @@ private void ValidateCom() foreach (ComClass comClass in file.ComClasses) { string key = comClass.ClsId.ToLowerInvariant(); - if (!clsidList.ContainsKey(key)) + if (!clsidList.TryGetValue(key, out ComInfo info)) { clsidList.Add(key, new ComInfo(outputFileName, file.TargetPath, comClass.ClsId, null)); } else { - OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "clsid", file.ToString(), comClass.ClsId, outputFileName, clsidList[key].ManifestFileName); + OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "clsid", file.ToString(), comClass.ClsId, outputFileName, info.ManifestFileName); } } } @@ -470,13 +470,13 @@ private void ValidateCom() foreach (TypeLib typeLib in file.TypeLibs) { string key = typeLib.TlbId.ToLowerInvariant(); - if (!tlbidList.ContainsKey(key)) + if (!tlbidList.TryGetValue(key, out ComInfo info)) { tlbidList.Add(key, new ComInfo(outputFileName, file.TargetPath, null, typeLib.TlbId)); } else { - OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "tlbid", file.ToString(), typeLib.TlbId, outputFileName, tlbidList[key].ManifestFileName); + OutputMessages.AddErrorMessage("GenerateManifest.DuplicateComDefinition", "tlbid", file.ToString(), typeLib.TlbId, outputFileName, info.ManifestFileName); } } } diff --git a/src/Tasks/ResolveSDKReference.cs b/src/Tasks/ResolveSDKReference.cs index 51ddc6acde9..74d9ab45c2c 100644 --- a/src/Tasks/ResolveSDKReference.cs +++ b/src/Tasks/ResolveSDKReference.cs @@ -901,23 +901,23 @@ public MultipleVersionSupport SupportsMultipleVersions /// public void Resolve(Dictionary sdks, string targetConfiguration, string targetArchitecture, HashSet sdkNamesOnReferenceItems, bool treatErrorsAsWarnings, bool prefer32Bit, string identifierTargetPlatform, Version versionTargetPlatform, string projectName, bool enableMaxPlatformVersionEmptyWarning) { - if (sdks.ContainsKey(SDKName)) + if (sdks.TryGetValue(SDKName, out ITaskItem sdk)) { _prefer32BitFromProject = prefer32Bit; // There must be a trailing slash or else the ExpandSDKReferenceAssemblies will not work. - ResolvedPath = FileUtilities.EnsureTrailingSlash(sdks[SDKName].ItemSpec); + ResolvedPath = FileUtilities.EnsureTrailingSlash(sdk.ItemSpec); - System.Version.TryParse(sdks[SDKName].GetMetadata(SDKPlatformVersion), out Version targetPlatformVersionFromItem); + System.Version.TryParse(sdk.GetMetadata(SDKPlatformVersion), out Version targetPlatformVersionFromItem); GetSDKManifestAttributes(); CreateResolvedReferenceItem(targetConfiguration, targetArchitecture, sdkNamesOnReferenceItems, identifierTargetPlatform, versionTargetPlatform, targetPlatformVersionFromItem, projectName, enableMaxPlatformVersionEmptyWarning); // Need to pass these along so we can unroll the platform via GetMatchingPlatformSDK when we get reference files - ResolvedItem.SetMetadata(GetInstalledSDKLocations.DirectoryRootsMetadataName, sdks[SDKName].GetMetadata(GetInstalledSDKLocations.DirectoryRootsMetadataName)); - ResolvedItem.SetMetadata(GetInstalledSDKLocations.ExtensionDirectoryRootsMetadataName, sdks[SDKName].GetMetadata(GetInstalledSDKLocations.ExtensionDirectoryRootsMetadataName)); - ResolvedItem.SetMetadata(GetInstalledSDKLocations.RegistryRootMetadataName, sdks[SDKName].GetMetadata(GetInstalledSDKLocations.RegistryRootMetadataName)); + ResolvedItem.SetMetadata(GetInstalledSDKLocations.DirectoryRootsMetadataName, sdk.GetMetadata(GetInstalledSDKLocations.DirectoryRootsMetadataName)); + ResolvedItem.SetMetadata(GetInstalledSDKLocations.ExtensionDirectoryRootsMetadataName, sdk.GetMetadata(GetInstalledSDKLocations.ExtensionDirectoryRootsMetadataName)); + ResolvedItem.SetMetadata(GetInstalledSDKLocations.RegistryRootMetadataName, sdk.GetMetadata(GetInstalledSDKLocations.RegistryRootMetadataName)); if (!treatErrorsAsWarnings && ResolutionErrors.Count > 0) { @@ -1377,7 +1377,7 @@ private void CreateResolvedReferenceItem(string targetConfiguration, string targ continue; } - bool containsKey = architectureLocations.ContainsKey(architectureComponent); + bool containsKey = architectureLocations.TryGetValue(architectureComponent, out string architectureLocation); // If we have not seen this architecture before (and it has a compatible configuration with what we are targeting) then add it. // Also, replace the entry if we have already added an entry for a non configuration specific entry and we now have a configuration specific entry that matches what we are targeting. @@ -1387,7 +1387,7 @@ private void CreateResolvedReferenceItem(string targetConfiguration, string targ if (containsKey) { - AddStatusMessage("ResolveSDKReference.ReplaceAppxLocation", architectureComponent, architectureLocations[architectureComponent], appxLocation.Value); + AddStatusMessage("ResolveSDKReference.ReplaceAppxLocation", architectureComponent, architectureLocation, appxLocation.Value); } architectureLocations[architectureComponent] = appxLocation.Value; @@ -1517,10 +1517,8 @@ private void CreateResolvedReferenceItem(string targetConfiguration, string targ /// private string FindFrameworkIdentity(string frameworkIdentityKey) { - string frameworkIdentityValue = null; - if (FrameworkIdentitiesFromManifest.ContainsKey(frameworkIdentityKey)) + if (FrameworkIdentitiesFromManifest.TryGetValue(frameworkIdentityKey, out string frameworkIdentityValue)) { - frameworkIdentityValue = FrameworkIdentitiesFromManifest[frameworkIdentityKey]; AddStatusMessage("ResolveSDKReference.FoundFrameworkIdentity", frameworkIdentityValue); } else diff --git a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs index 3cfd592d32e..069d4272c99 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs @@ -467,11 +467,11 @@ internal static bool TryLoadTaskBody(TaskLoggingHelper log, string taskName, str bool foundValidCodeLanguage = false; // Attempt to map the user specified value as an alias to our vernacular for code languages - foreach (string validLanguage in ValidCodeLanguages.Keys) + foreach (KeyValuePair> validLanguage in ValidCodeLanguages) { - if (ValidCodeLanguages[validLanguage].Contains(languageAttribute.Value)) + if (validLanguage.Value.Contains(languageAttribute.Value)) { - taskInfo.CodeLanguage = validLanguage; + taskInfo.CodeLanguage = validLanguage.Key; foundValidCodeLanguage = true; break; } diff --git a/src/Tasks/XamlTaskFactory/RelationsParser.cs b/src/Tasks/XamlTaskFactory/RelationsParser.cs index aaf6072e5a0..4ce861ca530 100644 --- a/src/Tasks/XamlTaskFactory/RelationsParser.cs +++ b/src/Tasks/XamlTaskFactory/RelationsParser.cs @@ -416,10 +416,7 @@ private static bool ParseSwitch(XmlNode node, Dictionary switches)) { - var switches = new List { Switch }; + switches = new List { Switch }; switchRelationsToAdd.ExternalRequires.Add(tool, switches); } else { - switchRelationsToAdd.ExternalRequires[tool].Add(Switch); + switches.Add(Switch); } } } diff --git a/src/Tasks/XamlTaskFactory/TaskGenerator.cs b/src/Tasks/XamlTaskFactory/TaskGenerator.cs index b0aeb1c7198..76547bf0e52 100644 --- a/src/Tasks/XamlTaskFactory/TaskGenerator.cs +++ b/src/Tasks/XamlTaskFactory/TaskGenerator.cs @@ -966,9 +966,8 @@ private bool ContainsCurrentPlatform(string SwitchValue) if (Platform == null) return true; - if (_relationsParser.SwitchRelationsList.ContainsKey(SwitchValue)) + if (_relationsParser.SwitchRelationsList.TryGetValue(SwitchValue, out SwitchRelations rel)) { - SwitchRelations rel = _relationsParser.SwitchRelationsList[SwitchValue]; if (rel.ExcludedPlatforms.Count > 0) { foreach (string excludedPlatform in rel.ExcludedPlatforms) @@ -996,9 +995,8 @@ private bool ContainsCurrentPlatform(string SwitchValue) /// private void GenerateOverrides(Property property, CodeMemberProperty propertyName) { - if (_relationsParser.SwitchRelationsList.ContainsKey(property.SwitchName)) + if (_relationsParser.SwitchRelationsList.TryGetValue(property.SwitchName, out SwitchRelations rel)) { - SwitchRelations rel = _relationsParser.SwitchRelationsList[property.SwitchName]; if (rel.Overrides.Count > 0) { foreach (string overrided in rel.Overrides) diff --git a/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs b/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs index a6483ae584e..b0f61b5746d 100644 --- a/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs +++ b/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs @@ -102,12 +102,7 @@ private string CommandLine /// public bool IsPropertySet(string propertyName) { - if (!String.IsNullOrEmpty(propertyName)) - { - return ActiveToolSwitches.ContainsKey(propertyName); - } - - return false; + return !String.IsNullOrEmpty(propertyName) && ActiveToolSwitches.ContainsKey(propertyName); } /// diff --git a/src/Utilities/MuxLogger.cs b/src/Utilities/MuxLogger.cs index fd31a3cf970..819fff3bf65 100644 --- a/src/Utilities/MuxLogger.cs +++ b/src/Utilities/MuxLogger.cs @@ -302,10 +302,7 @@ private void ProjectFinished(object sender, ProjectFinishedEventArgs e) _submissionProjectsInProgress.Remove(e.BuildEventContext.SubmissionId); lock (_submissionRecords) { - if (_submissionRecords.ContainsKey(e.BuildEventContext.SubmissionId)) - { - _submissionRecords.Remove(e.BuildEventContext.SubmissionId); - } + _submissionRecords.Remove(e.BuildEventContext.SubmissionId); } } else diff --git a/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs b/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs index 86b3892f2a2..1784b4d751a 100644 --- a/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs +++ b/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs @@ -605,10 +605,7 @@ private void ConstructDependencyTable() { // The tracking logs are not available, they may have been deleted at some point. // Be safe and remove any references from the cache. - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } return; } @@ -832,11 +829,7 @@ private void ConstructDependencyTable() // sure that we essentially force a rebuild of this particular root. if (encounteredInvalidTLogContents || exceptionCaught) { - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } - + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); DependencyTable = new Dictionary>(StringComparer.OrdinalIgnoreCase); } else @@ -874,10 +867,7 @@ public void SaveTlog(DependencyFilter includeInTLog) { // The tracking logs in the cache will be invalidated by this compaction // remove the cached entries - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } string firstTlog = _tlogFiles[0].ItemSpec; diff --git a/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs b/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs index f69120d591e..2dd952fa1ec 100644 --- a/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs +++ b/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs @@ -116,10 +116,7 @@ private void ConstructOutputTable() { // The tracking logs are not available, they may have been deleted at some point. // Be safe and remove any references from the cache. - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } return; } @@ -246,11 +243,7 @@ private void ConstructOutputTable() // sure that we essentially force a rebuild of this particular root. if (encounteredInvalidTLogContents) { - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } - + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); DependencyTable = new Dictionary>(StringComparer.OrdinalIgnoreCase); } else @@ -320,9 +313,9 @@ public string[] RemoveRootsWithSharedOutputs(ITaskItem[] sources) /// The output path to be removed public bool RemoveOutputForSourceRoot(string sourceRoot, string outputPathToRemove) { - if (DependencyTable.ContainsKey(sourceRoot)) + if (DependencyTable.TryGetValue(sourceRoot, out var outputPaths)) { - bool removed = DependencyTable[sourceRoot].Remove(outputPathToRemove); + bool removed = outputPaths.Remove(outputPathToRemove); // If we just removed the last entry for this root, remove the root. if (DependencyTable[sourceRoot].Count == 0) { @@ -584,10 +577,7 @@ public void SaveTlog(DependencyFilter includeInTLog) { // The tracking logs in the cache will be invalidated by this compaction // remove the cached entries to be sure - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } string firstTlog = _tlogFiles[0].ItemSpec; diff --git a/src/Utilities/TrackedDependencies/DependencyTableCache.cs b/src/Utilities/TrackedDependencies/DependencyTableCache.cs index 0767897c772..c87fcaf16fd 100644 --- a/src/Utilities/TrackedDependencies/DependencyTableCache.cs +++ b/src/Utilities/TrackedDependencies/DependencyTableCache.cs @@ -60,9 +60,8 @@ private static bool DependencyTableIsUpToDate(DependencyTableCacheEntry dependen /// The cached table entry internal static DependencyTableCacheEntry GetCachedEntry(string tLogRootingMarker) { - if (DependencyTable.ContainsKey(tLogRootingMarker)) + if (DependencyTable.TryGetValue(tLogRootingMarker, out DependencyTableCacheEntry cacheEntry)) { - DependencyTableCacheEntry cacheEntry = DependencyTable[tLogRootingMarker]; if (DependencyTableIsUpToDate(cacheEntry)) { return cacheEntry; diff --git a/src/Utilities/TrackedDependencies/FlatTrackingData.cs b/src/Utilities/TrackedDependencies/FlatTrackingData.cs index f69c68b7a08..49d2531a2b4 100644 --- a/src/Utilities/TrackedDependencies/FlatTrackingData.cs +++ b/src/Utilities/TrackedDependencies/FlatTrackingData.cs @@ -359,10 +359,7 @@ private void ConstructFileTable() { // The tracking logs are not available, they may have been deleted at some point. // Be safe and remove any references from the cache. - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } return; } @@ -480,11 +477,7 @@ private void ConstructFileTable() // sure that we essentially force a rebuild of this particular root. if (encounteredInvalidTLogContents) { - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } - + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); DependencyTable = new Dictionary(StringComparer.OrdinalIgnoreCase); } else @@ -619,10 +612,7 @@ public void SaveTlog(DependencyFilter includeInTLog) { // The tracking logs in the cache will be invalidated by this write // remove the cached entries to be sure - if (DependencyTableCache.DependencyTable.ContainsKey(tLogRootingMarker)) - { - DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); - } + DependencyTableCache.DependencyTable.Remove(tLogRootingMarker); } string firstTlog = TlogFiles[0].ItemSpec;