diff --git a/.editorconfig b/.editorconfig index 5311eb964aa..fa30dae9c78 100644 --- a/.editorconfig +++ b/.editorconfig @@ -163,7 +163,7 @@ dotnet_code_quality.ca2208.api_surface = public dotnet_diagnostic.RS0037.severity = none # License header -file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license.\n +file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license. # C++ Files [*.{cpp,h,in}] @@ -200,5 +200,192 @@ end_of_line = lf end_of_line = crlf [src/**/*.{cs,vb}] +# Code style checks +dotnet_analyzer_diagnostic.category-Style.severity = warning + +# Cast is redundant +dotnet_diagnostic.IDE0004.severity = suggestion + # IDE0005: Remove unnecessary usings/imports dotnet_diagnostic.IDE0005.severity = warning + +# Use explicit type instead of 'var' +dotnet_diagnostic.IDE0008.severity = suggestion + +# Populate switch +dotnet_diagnostic.IDE0010.severity = suggestion + +# Null check can be simplified +dotnet_diagnostic.IDE0016.severity = suggestion + +# Object initialization can be simplified +dotnet_diagnostic.IDE0017.severity = suggestion + +# Variable declaration can be inlined +dotnet_diagnostic.IDE0018.severity = suggestion + +# Use pattern matching +dotnet_diagnostic.IDE0019.severity = suggestion +dotnet_diagnostic.IDE0020.severity = suggestion + +# Use expression body for constructor +dotnet_diagnostic.IDE0021.severity = suggestion + +# Use expression body for method +dotnet_diagnostic.IDE0022.severity = suggestion + +# Use expression body for conversion operator +dotnet_diagnostic.IDE0023.severity = suggestion + +# Use block body for operator +dotnet_diagnostic.IDE0024.severity = suggestion + +# Use expression body for property +dotnet_diagnostic.IDE0025.severity = suggestion + +# Use expression body for indexer +dotnet_diagnostic.IDE0026.severity = suggestion + +# Use expression body for accessor +dotnet_diagnostic.IDE0027.severity = suggestion + +# Collection initialization can be simplified +dotnet_diagnostic.IDE0028.severity = suggestion + +# Null check can be simplified +dotnet_diagnostic.IDE0031.severity = suggestion + +# Use auto property +dotnet_diagnostic.IDE0032.severity = suggestion + +# 'default' expression can be simplified +dotnet_diagnostic.IDE0034.severity = suggestion + +# Member name can be simplified +dotnet_diagnostic.IDE0037.severity = suggestion + +# Use local function +dotnet_diagnostic.IDE0039.severity = suggestion + +# Null check can be simplified +dotnet_diagnostic.IDE0041.severity = suggestion + +# Variable declaration can be deconstructed +dotnet_diagnostic.IDE0042.severity = suggestion + +# Made field readonly +dotnet_diagnostic.IDE0044.severity = suggestion + +# 'if' statement can be simplified +dotnet_diagnostic.IDE0045.severity = suggestion +dotnet_diagnostic.IDE0046.severity = suggestion + +# Parentheses can be removed +dotnet_diagnostic.IDE0047.severity = suggestion + +# Parentheses should be added for clarity +dotnet_diagnostic.IDE0048.severity = suggestion + +# Member name can be simplified +dotnet_diagnostic.IDE0049.severity = suggestion + +# Use compound assignment +dotnet_diagnostic.IDE0054.severity = suggestion + +# Indexing can be simplified +dotnet_diagnostic.IDE0056.severity = suggestion + +# Slice can be simplified +dotnet_diagnostic.IDE0057.severity = suggestion + +# Expression value is never used +dotnet_diagnostic.IDE0058.severity = suggestion + +# Unnecessary assignment of a value +dotnet_diagnostic.IDE0059.severity = suggestion + +# Remove unused parameter +dotnet_diagnostic.IDE0060.severity = suggestion + +# Use expression body for a local function +dotnet_diagnostic.IDE0061.severity = suggestion + +# Local function can be made static +dotnet_diagnostic.IDE0062.severity = suggestion + +# Using directives must be placed outside of a namespace declaration +dotnet_diagnostic.IDE0065.severity = suggestion + +# Use 'switch' expression +dotnet_diagnostic.IDE0066.severity = suggestion + +# 'GetHashCode' implementation can be simplified +dotnet_diagnostic.IDE0070.severity = suggestion + +# Interpolation can be simplified +dotnet_diagnostic.IDE0071.severity = suggestion + +# Populate switch +dotnet_diagnostic.IDE0072.severity = suggestion + +# Use compound assignment +dotnet_diagnostic.IDE0074.severity = suggestion + +# Conditional expression can be simplified +dotnet_diagnostic.IDE0075.severity = suggestion + +# Use pattern matching +dotnet_diagnostic.IDE0078.severity = suggestion +dotnet_diagnostic.IDE0083.severity = suggestion + +# 'typeof' can be converted to 'nameof' +dotnet_diagnostic.IDE0082.severity = suggestion + +# 'new' expression can be simplified +dotnet_diagnostic.IDE0090.severity = suggestion + +# Simplify LINQ expression +dotnet_diagnostic.IDE0120.severity = suggestion + +# namespace does not match folder structure +dotnet_diagnostic.IDE0130.severity = suggestion + +# Null check can be clarified +dotnet_diagnostic.IDE0150.severity = suggestion + +# Convert to block scoped namespaces +dotnet_diagnostic.IDE0160.severity = suggestion + +# Simplify property pattern +dotnet_diagnostic.IDE0170.severity = suggestion + +# Use tuple to swap values +dotnet_diagnostic.IDE0180.severity = suggestion + +# Use tuple to swap values +dotnet_diagnostic.IDE0180.severity = suggestion + +# Lambda expression can be removed +dotnet_diagnostic.IDE0200.severity = suggestion + +# Convert to top-level statements +dotnet_diagnostic.IDE0210.severity = suggestion + +# 'foreach' statement implicitly converts +dotnet_diagnostic.IDE0220.severity = suggestion + +# Use UTF-8 string literal +dotnet_diagnostic.IDE0230.severity = suggestion + +# Nullable directives +dotnet_diagnostic.IDE0240.severity = suggestion +dotnet_diagnostic.IDE0241.severity = suggestion + +# Struct can be made 'readonly' +dotnet_diagnostic.IDE0250.severity = suggestion + +# Null check can be simplified +dotnet_diagnostic.IDE0270.severity = suggestion + +# naming rule violation +dotnet_diagnostic.IDE1006.severity = suggestion \ No newline at end of file diff --git a/eng/Common.globalconfig b/eng/Common.globalconfig index d0b65becdd1..dd47c3b3336 100644 --- a/eng/Common.globalconfig +++ b/eng/Common.globalconfig @@ -782,10 +782,10 @@ dotnet_diagnostic.SA1107.severity = suggestion dotnet_diagnostic.SA1108.severity = none # Opening parenthesis or bracket should be on declaration line -dotnet_diagnostic.SA1110.severity = suggestion +dotnet_diagnostic.SA1110.severity = warning # Closing parenthesis should be on line of last parameter -dotnet_diagnostic.SA1111.severity = suggestion +dotnet_diagnostic.SA1111.severity = warning dotnet_diagnostic.SA1112.severity = none @@ -1093,7 +1093,8 @@ dotnet_diagnostic.SA1627.severity = suggestion dotnet_diagnostic.SA1629.severity = suggestion # File should have header -dotnet_diagnostic.SA1633.severity = suggestion +# Superseded by IDE0073 +dotnet_diagnostic.SA1633.severity = none # Constructor summary documentation should begin with standard text dotnet_diagnostic.SA1642.severity = suggestion diff --git a/eng/build.ps1 b/eng/build.ps1 index 2762b71fb9f..eaf7cc577d8 100644 --- a/eng/build.ps1 +++ b/eng/build.ps1 @@ -169,7 +169,7 @@ function Check-RequiredVersionBumps() { if (($LASTEXITCODE -ne 0) -and (-not $versionLineChanged)) { throw "##vso[task.logissue type=error] Detected changes in Framework\EngineServices.cs without a version bump. " + "If you are making API changes, please bump the version. " + - "If the changes in the file are cosmetic, please add/change a comment on the Version prop to silence the error." + "If the changes in the file are cosmetic, please change an inline comment on the `"int Version =`" line in EngineServices.cs to silence the error." } } } diff --git a/src/Build.OM.UnitTests/AssemblyInfo.cs b/src/Build.OM.UnitTests/AssemblyInfo.cs index 7f6f30fcef9..3b5d7bbb185 100644 --- a/src/Build.OM.UnitTests/AssemblyInfo.cs +++ b/src/Build.OM.UnitTests/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Build.OM.UnitTests/AssemblyResources.cs b/src/Build.OM.UnitTests/AssemblyResources.cs index baa3ffd33ba..311870a9e2b 100644 --- a/src/Build.OM.UnitTests/AssemblyResources.cs +++ b/src/Build.OM.UnitTests/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build.OM.UnitTests/Construction/ConstructionEditing_Tests.cs b/src/Build.OM.UnitTests/Construction/ConstructionEditing_Tests.cs index bc6e78a22fd..8d3690d5d5c 100644 --- a/src/Build.OM.UnitTests/Construction/ConstructionEditing_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ConstructionEditing_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -110,8 +110,7 @@ public void InvalidAddFromDifferentProject_AppendChild() ProjectRootElement project2 = ProjectRootElement.Create(); ProjectTargetElement target = project1.CreateTargetElement("t"); project2.AppendChild(target); - } - ); + }); } /// /// Add node created from different project with PrependChild @@ -125,8 +124,7 @@ public void InvalidAddFromDifferentProject_PrependChild() ProjectRootElement project2 = ProjectRootElement.Create(); ProjectTargetElement target = project1.CreateTargetElement("t"); project2.PrependChild(target); - } - ); + }); } /// /// Add node created from different project with InsertBeforeChild @@ -141,8 +139,7 @@ public void InvalidAddFromDifferentProject_InsertBefore() ProjectTargetElement target1 = project1.CreateTargetElement("t"); ProjectTargetElement target2 = project2.AddTarget("t2"); project2.InsertBeforeChild(target2, target1); - } - ); + }); } /// /// Add node created from different project with InsertAfterChild @@ -157,8 +154,7 @@ public void InvalidAddFromDifferentProject_InsertAfter() ProjectTargetElement target1 = project1.CreateTargetElement("t"); ProjectTargetElement target2 = project2.AddTarget("t2"); project2.InsertAfterChild(target2, target1); - } - ); + }); } /// /// Become direct child of self with AppendChild @@ -173,8 +169,7 @@ public void InvalidBecomeChildOfSelf_AppendChild() ProjectChooseElement choose = project.CreateChooseElement(); choose.AppendChild(choose); - } - ); + }); } /// /// Become grandchild of self with AppendChild @@ -190,8 +185,7 @@ public void InvalidBecomeGrandChildOfSelf_AppendChild() project.AppendChild(choose); choose.AppendChild(when); when.AppendChild(choose); - } - ); + }); } /// /// Become grandchild of self with PrependChild @@ -207,8 +201,7 @@ public void InvalidBecomeGrandChildOfSelf_PrependChild() project.AppendChild(choose); choose.AppendChild(when); when.PrependChild(choose); - } - ); + }); } /// /// Become grandchild of self with InsertBeforeChild @@ -226,8 +219,7 @@ public void InvalidBecomeGrandChildOfSelf_InsertBefore() choose1.AppendChild(when); when.PrependChild(choose2); when.InsertBeforeChild(choose1, choose2); - } - ); + }); } /// /// Become grandchild of self with InsertAfterChild @@ -245,8 +237,7 @@ public void InvalidBecomeGrandChildOfSelf_InsertAfter() choose1.AppendChild(when); when.PrependChild(choose2); when.InsertAfterChild(choose1, choose2); - } - ); + }); } /// /// Attempt to reparent with AppendChild @@ -260,8 +251,7 @@ public void InvalidAlreadyParented_AppendChild() ProjectTargetElement target = project.AddTarget("t"); project.AppendChild(target); - } - ); + }); } /// /// Attempt to reparent with PrependChild @@ -275,8 +265,7 @@ public void InvalidAlreadyParented_PrependChild() ProjectTargetElement target = project.AddTarget("t"); project.PrependChild(target); - } - ); + }); } /// /// Attempt to reparent with InsertBeforeChild @@ -291,8 +280,7 @@ public void InvalidAlreadyParented_InsertBefore() ProjectTargetElement target2 = project.AddTarget("t2"); project.InsertBeforeChild(target1, target2); - } - ); + }); } /// /// Attempt to reparent with InsertAfterChild @@ -307,8 +295,7 @@ public void InvalidAlreadyParented_InsertAfter() ProjectTargetElement target2 = project.AddTarget("t2"); project.InsertAfterChild(target1, target2); - } - ); + }); } /// /// Attempt to add to unparented parent with AppendChild @@ -323,8 +310,7 @@ public void InvalidParentNotParented_AppendChild() ProjectTaskElement task = project.CreateTaskElement("tt"); target.AppendChild(task); - } - ); + }); } /// /// Attempt to add to unparented parent with PrependChild @@ -339,8 +325,7 @@ public void InvalidParentNotParented_PrependChild() ProjectTaskElement task = project.CreateTaskElement("tt"); target.PrependChild(task); - } - ); + }); } /// /// Attempt to add to unparented parent with InsertBeforeChild @@ -356,8 +341,7 @@ public void InvalidParentNotParented_InsertBefore() ProjectTaskElement task2 = project.CreateTaskElement("tt"); target.InsertBeforeChild(task2, task1); - } - ); + }); } /// /// Attempt to add to unparented parent with InsertAfterChild @@ -373,8 +357,7 @@ public void InvalidParentNotParented_InsertAfter() ProjectTaskElement task2 = project.CreateTaskElement("tt"); target.InsertAfterChild(task2, task1); - } - ); + }); } /// /// Setting attributes on a target should be reflected in the XML @@ -652,8 +635,7 @@ public void InvalidAttemptToAddProjectToTarget() ProjectTargetElement target = project.CreateTargetElement("t"); target.AppendChild(project); - } - ); + }); } /// /// Attempt to insert item in target @@ -669,8 +651,7 @@ public void InvalidAttemptToAddItemToTarget() project.AppendChild(target); target.AppendChild(item); - } - ); + }); } /// /// Attempt to insert item without include in itemgroup in project @@ -686,8 +667,7 @@ public void InvalidAttemptToAddEmptyItem() project.AppendChild(itemGroup); itemGroup.AppendChild(item); - } - ); + }); } /// /// Add item without include in itemgroup in target @@ -1014,7 +994,7 @@ public static IEnumerable InsertMetadataAttributeAfterSiblingsTestData } } - [Theory(Skip= "https://github.com/dotnet/msbuild/issues/1253")] + [Theory(Skip = "https://github.com/dotnet/msbuild/issues/1253")] [MemberData(nameof(InsertMetadataAttributeAfterSiblingsTestData))] public void InsertMetadataAttributeAfterSiblings(AddMetadata addMetadata, int position, string expectedItem) { @@ -1078,7 +1058,7 @@ public static IEnumerable InsertMetadataAttributeBeforeSiblingsTestDat } } - [Theory(Skip= "https://github.com/dotnet/msbuild/issues/1253")] + [Theory(Skip = "https://github.com/dotnet/msbuild/issues/1253")] [MemberData(nameof(InsertMetadataAttributeBeforeSiblingsTestData))] public void InsertMetadataAttributeBeforeSiblings(AddMetadata addMetadata, int position, string expectedItem) { @@ -1216,8 +1196,7 @@ public void InvalidRemoveUnparentedChild() ProjectRootElement project = ProjectRootElement.Create(); ProjectTargetElement target = project.CreateTargetElement("t"); project.RemoveChild(target); - } - ); + }); } /// /// Attempt to remove a child that is parented by something in another project @@ -1232,8 +1211,7 @@ public void InvalidRemoveChildFromOtherProject() ProjectRootElement project2 = ProjectRootElement.Create(); project2.RemoveChild(target); - } - ); + }); } /// /// Attempt to remove a child that is parented by something else in the same project @@ -1250,8 +1228,7 @@ public void InvalidRemoveChildFromOtherParent() itemGroup1.AppendChild(item); itemGroup2.RemoveChild(item); - } - ); + }); } /// /// Attempt to add an Otherwise before a When @@ -1269,8 +1246,7 @@ public void InvalidOtherwiseBeforeWhen() project.AppendChild(choose); choose.AppendChild(when); choose.InsertBeforeChild(otherwise, when); - } - ); + }); } /// /// Attempt to add an Otherwise after another @@ -1286,8 +1262,7 @@ public void InvalidOtherwiseAfterOtherwise() choose.AppendChild(project.CreateWhenElement("c")); choose.AppendChild(project.CreateOtherwiseElement()); choose.AppendChild(project.CreateOtherwiseElement()); - } - ); + }); } /// /// Attempt to add an Otherwise before another @@ -1303,8 +1278,7 @@ public void InvalidOtherwiseBeforeOtherwise() choose.AppendChild(project.CreateWhenElement("c")); choose.AppendChild(project.CreateOtherwiseElement()); choose.InsertAfterChild(project.CreateOtherwiseElement(), choose.FirstChild); - } - ); + }); } /// /// Attempt to add a When after an Otherwise @@ -1322,8 +1296,7 @@ public void InvalidWhenAfterOtherwise() project.AppendChild(choose); choose.AppendChild(otherwise); choose.InsertAfterChild(when, otherwise); - } - ); + }); } /// /// Add When before Otherwise @@ -2287,8 +2260,7 @@ public void InvalidAddPropertyReservedName() { ProjectRootElement project = ProjectRootElement.Create(); project.AddProperty("MSBuildToolsPATH", "v"); - } - ); + }); } /// /// Attempt to add a property with an illegal name @@ -2300,8 +2272,7 @@ public void InvalidAddPropertyIllegalName() { ProjectRootElement project = ProjectRootElement.Create(); project.AddProperty("ItemGroup", "v"); - } - ); + }); } /// /// Attempt to add a property with an invalid XML name @@ -2313,8 +2284,7 @@ public void InvalidAddPropertyInvalidXmlName() { ProjectRootElement project = ProjectRootElement.Create(); project.AddProperty("@#$@#", "v"); - } - ); + }); } /// /// Too much nesting should not cause stack overflow. diff --git a/src/Build.OM.UnitTests/Construction/ElementLocationPublic_Tests.cs b/src/Build.OM.UnitTests/Construction/ElementLocationPublic_Tests.cs index c98ce34d856..fabff8c5bcc 100644 --- a/src/Build.OM.UnitTests/Construction/ElementLocationPublic_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ElementLocationPublic_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System; diff --git a/src/Build.OM.UnitTests/Construction/ProjectChooseElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectChooseElement_Tests.cs index 741534ff364..f8bcc00dc81 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectChooseElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectChooseElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -37,8 +37,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read choose with unexpected Condition attribute. @@ -56,8 +55,7 @@ public void ReadInvalidConditionAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read choose with unexpected child @@ -76,8 +74,7 @@ public void ReadInvalidChild() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read choose with a When containing no Condition attribute @@ -101,8 +98,7 @@ public void ReadInvalidWhen() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read choose with only an otherwise @@ -121,8 +117,7 @@ public void ReadInvalidOnlyOtherwise() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read choose with two otherwises @@ -142,8 +137,7 @@ public void ReadInvalidTwoOtherwise() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read choose with otherwise before when @@ -163,8 +157,7 @@ public void ReadInvalidOtherwiseBeforeWhen() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read empty choose @@ -187,8 +180,7 @@ public void ReadInvalidEmptyChoose() ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children); Assert.Null(Helpers.GetFirst(choose.Children)); - } - ); + }); } /// /// Read choose with only a when @@ -260,8 +252,7 @@ public void ExcessivelyNestedChoose() content += @""; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Setting a When's condition should dirty the project diff --git a/src/Build.OM.UnitTests/Construction/ProjectExtensionsElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectExtensionsElement_Tests.cs index 31dd3783930..75630c2f041 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectExtensionsElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectExtensionsElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -53,8 +53,7 @@ public void ReadInvalidCondition() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read project with more than one ProjectExtensions @@ -73,8 +72,7 @@ public void ReadInvalidDuplicate() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Set valid content @@ -102,8 +100,7 @@ public void SetInvalidNull() ProjectExtensionsElement extensions = GetEmptyProjectExtensions(); extensions.Content = null; - } - ); + }); } /// /// Delete by ID diff --git a/src/Build.OM.UnitTests/Construction/ProjectFormatting_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectFormatting_Tests.cs index b04097bd028..48ade2120bc 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectFormatting_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectFormatting_Tests.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Construction; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.UnitTests; using System; @@ -267,7 +270,7 @@ public void ProjectRemoveItemFormatting() var itemToRemove = project.GetItems("Compile").Single(item => item.EvaluatedInclude == "Class2.cs"); project.RemoveItem(itemToRemove); - + StringWriter writer = new StringWriter(); project.Save(writer); @@ -303,7 +306,7 @@ public void ProjectAddItemMetadataFormatting() var itemToEdit = project.GetItems("Compile").Single(item => item.EvaluatedInclude == "Class2.cs"); itemToEdit.SetMetadataValue("ExcludeFromStyleCop", "true"); - + StringWriter writer = new StringWriter(); project.Save(writer); @@ -351,13 +354,13 @@ public void PreprocessorFormatting() VerifyAssertLineByLine(expected, actual); } - void VerifyFormattingPreserved(string projectContents) + private void VerifyFormattingPreserved(string projectContents) { VerifyFormattingPreservedFromString(projectContents); VerifyFormattingPreservedFromFile(projectContents); } - void VerifyFormattingPreservedFromString(string projectContents) + private void VerifyFormattingPreservedFromString(string projectContents) { ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectContents)), ProjectCollection.GlobalProjectCollection, @@ -373,7 +376,7 @@ void VerifyFormattingPreservedFromString(string projectContents) VerifyAssertLineByLine(expected, actual); } - void VerifyFormattingPreservedFromFile(string projectContents) + private void VerifyFormattingPreservedFromFile(string projectContents) { string directory = null; @@ -403,13 +406,13 @@ void VerifyFormattingPreservedFromFile(string projectContents) } } - void VerifyProjectReformatting(string originalContents, string expectedContents) + private void VerifyProjectReformatting(string originalContents, string expectedContents) { VerifyProjectReformattingFromString(originalContents, expectedContents); VerifyProjectReformattingFromFile(originalContents, expectedContents); } - void VerifyProjectReformattingFromString(string originalContents, string expectedContents) + private void VerifyProjectReformattingFromString(string originalContents, string expectedContents) { ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(originalContents)), ProjectCollection.GlobalProjectCollection, @@ -425,7 +428,7 @@ void VerifyProjectReformattingFromString(string originalContents, string expecte VerifyAssertLineByLine(expected, actual); } - void VerifyProjectReformattingFromFile(string originalContents, string expectedContents) + private void VerifyProjectReformattingFromFile(string originalContents, string expectedContents) { string directory = null; @@ -455,7 +458,7 @@ void VerifyProjectReformattingFromFile(string originalContents, string expectedC } } - void VerifyAssertLineByLine(string expected, string actual) + private void VerifyAssertLineByLine(string expected, string actual) { Helpers.VerifyAssertLineByLine(expected, actual, false, _testOutput); } @@ -503,8 +506,8 @@ public void DefaultProjectSaveContainsAllNewFileOptions() Project project = new Project(); project.AddItem("ProjectReference", @"..\CLREXE\CLREXE.vcxproj", - new[] {new KeyValuePair("metadata", "value")}); - + new[] { new KeyValuePair("metadata", "value") }); + StringWriter writer = new EncodingStringWriter(); project.Save(writer); diff --git a/src/Build.OM.UnitTests/Construction/ProjectImportElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectImportElement_Tests.cs index c974eeb2915..790558091f5 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectImportElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectImportElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -48,8 +48,7 @@ public void ReadInvalidMissingProject() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read import with empty project attribute @@ -66,8 +65,7 @@ public void ReadInvalidEmptyProject() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read import with unexpected attribute @@ -84,8 +82,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read basic valid imports @@ -149,8 +146,7 @@ public void SetProjectInvalidEmpty() ProjectImportElement import = (ProjectImportElement)Helpers.GetFirst(project.Children); import.Project = String.Empty; - } - ); + }); } /// /// Setting the project attribute should dirty the project @@ -173,13 +169,11 @@ public void SettingProjectDirties() importProject2.AddProperty("p", "v2"); importProject2.Save(file2); - string content = String.Format - ( + string content = String.Format( @" ", - file1 - ); + file1); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectImportElement import = Helpers.GetFirst(project.Xml.Imports); @@ -213,13 +207,11 @@ public void SettingConditionDirties() importProject.AddProperty("p", "v1"); importProject.Save(file); - string content = String.Format - ( + string content = String.Format( @" ", - file - ); + file); Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectImportElement import = Helpers.GetFirst(project.Xml.Imports); @@ -247,15 +239,13 @@ public void ImportWithRelativePath() string testTempPath = Path.Combine(tempPath, "UnitTestsPublicOm"); string projectfile = Path.Combine(testTempPath, "a.proj"); string targetsFile = Path.Combine(tempPath, "x.targets"); - string projectfileContent = String.Format - ( + string projectfileContent = String.Format( @" ", - testTempPath + "\\..\\x.targets" - ); + testTempPath + "\\..\\x.targets"); string targetsfileContent = @" diff --git a/src/Build.OM.UnitTests/Construction/ProjectImportGroupElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectImportGroupElement_Tests.cs index 3b2b05d094a..d5566731c72 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectImportGroupElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectImportGroupElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -184,8 +184,7 @@ public void ReadInvalidChildMissingProject() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Checks that an InvalidProjectFileException is thrown when an invalid @@ -205,8 +204,7 @@ public void ReadInvalidChildType() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Checks that an InvalidProjectFileException is thrown when an ImportGroup is placed @@ -226,8 +224,7 @@ public void ReadInvalidParentType() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read import group with unexpected attribute @@ -244,8 +241,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read basic valid import group @@ -358,8 +354,7 @@ public void SetProjectInvalidEmpty() ProjectImportElement import = (ProjectImportElement)Helpers.GetFirst(importGroup.Imports); import.Project = String.Empty; - } - ); + }); } /// /// Set the condition value diff --git a/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionElement_Tests.cs index a7caaaff7f4..0228b259612 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionGroupElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionGroupElement_Tests.cs index 5b081f981f3..2112fa2d2c2 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionGroupElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectItemDefinitionGroupElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; @@ -44,8 +44,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read itemdefinitiongroup with no children diff --git a/src/Build.OM.UnitTests/Construction/ProjectItemElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectItemElement_Tests.cs index 5228974a6e7..b6ec9024a6e 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectItemElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectItemElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -110,8 +110,7 @@ public void ReadInvalidNoInclude(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -139,8 +138,7 @@ public void ReadInvalidContainsText(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -168,8 +166,7 @@ public void ReadInvalidEmptyInclude(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -197,8 +194,7 @@ public void ReadInvalidReservedElementName(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -217,8 +213,7 @@ public void ReadInvalidExcludeWithoutInclude() var exception = Assert.Throws( - () => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); } - ); + () => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); }); Assert.Contains("Items that are outside Target elements must have one of the following operations: Include, Update, or Remove.", exception.Message); } @@ -241,8 +236,7 @@ public void ReadInvalidExcludeWithoutIncludeUnderTarget() var exception = Assert.Throws( - () => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); } - ); + () => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); }); Assert.Contains("The attribute \"Exclude\" in element is unrecognized.", exception.Message); } @@ -285,8 +279,7 @@ public void ReadInvalidItemAttributeCasing(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -428,8 +421,7 @@ public void ReadInvalidUpdateWithInclude(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } [Theory] @@ -454,8 +446,7 @@ public void ReadInvalidUpdateWithIncludeAndExclude(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } [Theory] @@ -480,8 +471,7 @@ public void ReadInvalidUpdateWithExclude(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -513,8 +503,7 @@ public void ReadInvalidRemoveWithMetadata(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -542,8 +531,7 @@ public void ReadInvalidExcludeAndRemove(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -571,8 +559,7 @@ public void ReadInvalidIncludeAndRemove(string project) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(project))); - } - ); + }); } /// @@ -732,8 +719,7 @@ public void SetInvalidRemoveWithInclude(string project) ProjectItemElement item = GetItemFromContent(project); item.Remove = "i1"; - } - ); + }); } /// @@ -749,8 +735,7 @@ public void SetInvalidUpdateWithInclude(string project) ProjectItemElement item = GetItemFromContent(project); item.Update = "i1"; - } - ); + }); } /// @@ -811,8 +796,7 @@ public void SetInvalidIncludeWithRemove(string project) ProjectItemElement item = GetItemFromContent(project); item.Include = "i1"; - } - ); + }); } /// @@ -828,8 +812,7 @@ public void SetInvalidExcludeWithRemove(string project) ProjectItemElement item = GetItemFromContent(project); item.Exclude = "i1"; - } - ); + }); } /// @@ -845,8 +828,7 @@ public void SetInvalidUpdateWithRemove(string project) ProjectItemElement item = GetItemFromContent(project); item.Update = "i1"; - } - ); + }); } /// @@ -908,8 +890,7 @@ public void SetInvalidIncludeWithUpdate(string project) ProjectItemElement item = GetItemFromContent(project); item.Include = "i1"; - } - ); + }); } /// @@ -925,8 +906,7 @@ public void SetInvalidExcludeWithUpdate(string project) ProjectItemElement item = GetItemFromContent(project); item.Exclude = "i1"; - } - ); + }); } /// diff --git a/src/Build.OM.UnitTests/Construction/ProjectItemGroupElement_tests.cs b/src/Build.OM.UnitTests/Construction/ProjectItemGroupElement_tests.cs index 05fa6347ad6..8c71efffce3 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectItemGroupElement_tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectItemGroupElement_tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/Construction/ProjectMetadataElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectMetadataElement_Tests.cs index fc29f4d87da..cd8d9167026 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectMetadataElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectMetadataElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -60,8 +60,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read metadatum with invalid name characters (but legal xml) @@ -82,8 +81,7 @@ public void ReadInvalidName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } [Theory] @@ -106,8 +104,7 @@ public void ReadInvalidNameAsAttribute(string content) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// @@ -129,8 +126,7 @@ public void ReadInvalidBuiltInName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } [Theory] @@ -153,8 +149,7 @@ public void ReadInvalidBuiltInNameAsAttribute(string content) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// @@ -176,8 +171,7 @@ public void ReadInvalidBuiltInElementName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// @@ -203,8 +197,7 @@ public void ReadInvalidBuiltInElementNameAsAttribute(string content) Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// @@ -257,8 +250,7 @@ public void SetNameIllegal() ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Name = "ImportGroup"; - } - ); + }); } [Fact] @@ -270,8 +262,7 @@ public void SetNameIllegalAsAttribute() Assert.Throws(() => { metadatum.Name = "Include"; - } - ); + }); } @@ -284,8 +275,7 @@ public void SetExpressedAsAttributeIllegalName() Assert.Throws(() => { metadatum.ExpressedAsAttribute = true; - } - ); + }); } [Theory] @@ -371,8 +361,7 @@ public void SetInvalidNullValue() ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Value = null; - } - ); + }); } /// /// Read a metadatum containing an expression like @(..) but whose parent is an ItemDefinitionGroup @@ -393,8 +382,7 @@ public void ReadInvalidItemExpressionInMetadata() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read a metadatum containing an expression like @(..) but whose parent is NOT an ItemDefinitionGroup @@ -1259,7 +1247,7 @@ private static ProjectMetadataElement GetMetadataXml() return metadata; } - void VerifyAssertLineByLine(string expected, string actual) + private void VerifyAssertLineByLine(string expected, string actual) { Helpers.VerifyAssertLineByLine(expected, actual, false, _testOutput); } diff --git a/src/Build.OM.UnitTests/Construction/ProjectOnErrorElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectOnErrorElement_Tests.cs index 1edfae8a76d..216a583cbe6 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectOnErrorElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectOnErrorElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -83,8 +83,7 @@ public void ReadMissingExecuteTargets() ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children); Assert.Equal(String.Empty, onError.ExecuteTargetsAttribute); - } - ); + }); } /// /// Read onerror with empty executetargets attribute @@ -110,8 +109,7 @@ public void ReadEmptyExecuteTargets() ProjectOnErrorElement onError = (ProjectOnErrorElement)Helpers.GetFirst(target.Children); Assert.Equal(String.Empty, onError.ExecuteTargetsAttribute); - } - ); + }); } /// /// Read onerror with invalid attribute @@ -130,8 +128,7 @@ public void ReadInvalidUnexpectedAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read onerror with invalid child element @@ -152,8 +149,7 @@ public void ReadInvalidUnexpectedChild() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read onerror before task @@ -173,8 +169,7 @@ public void ReadInvalidBeforeTask() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read onerror before task @@ -194,8 +189,7 @@ public void ReadInvalidBeforePropertyGroup() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read onerror before task @@ -215,8 +209,7 @@ public void ReadInvalidBeforeItemGroup() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Set ExecuteTargets @@ -242,8 +235,7 @@ public void SetInvalidExecuteTargetsNull() ProjectOnErrorElement onError = GetOnError(); onError.ExecuteTargetsAttribute = null; - } - ); + }); } /// /// Set ExecuteTargets to empty string @@ -256,8 +248,7 @@ public void SetInvalidExecuteTargetsEmpty() ProjectOnErrorElement onError = GetOnError(); onError.ExecuteTargetsAttribute = String.Empty; - } - ); + }); } /// /// Set on error condition diff --git a/src/Build.OM.UnitTests/Construction/ProjectOutputElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectOutputElement_Tests.cs index 2a3bfb4a6c8..f64361abb46 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectOutputElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectOutputElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -68,8 +68,7 @@ public void ReadInvalidOutputWithoutPropertyOrItem() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an output property with reserved property name @@ -91,8 +90,7 @@ public void ReadInvalidReservedOutputPropertyName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an output property with missing taskparameter @@ -114,8 +112,7 @@ public void ReadInvalidOutputWithoutTaskName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an output property with missing taskparameter @@ -137,8 +134,7 @@ public void ReadInvalidOutputWithEmptyTaskName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an output property with child element @@ -162,8 +158,7 @@ public void ReadInvalidOutputWithChildElement() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an output property with propertyname but an empty itemname attribute @@ -185,8 +180,7 @@ public void ReadInvalidPropertyValueItemBlank() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an output property with an itemname but an empty propertyname attribute @@ -208,8 +202,7 @@ public void ReadInvalidItemValuePropertyBlank() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Modify the condition @@ -250,8 +243,7 @@ public void SetOutputPropertyItemType() ProjectOutputElement output = GetOutputProperty(); output.ItemType = "i1b"; - } - ); + }); } /// /// Set the item name value @@ -278,8 +270,7 @@ public void SetOutputItemPropertyName() ProjectOutputElement output = GetOutputItem(); output.PropertyName = "p1b"; - } - ); + }); } /// /// Helper to get a ProjectOutputElement for an output item diff --git a/src/Build.OM.UnitTests/Construction/ProjectPropertyElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectPropertyElement_Tests.cs index 8942470692d..ed38f1828e0 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectPropertyElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectPropertyElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -70,8 +70,7 @@ public void ReadInvalidName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read property with invalid reserved name @@ -90,8 +89,7 @@ public void ReadInvalidReservedName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read property with invalid built in name @@ -110,8 +108,7 @@ public void ReadInvalidBuiltInName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read property with invalid attribute @@ -130,8 +127,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read property with child element @@ -152,8 +148,7 @@ public void ReadInvalidChildElement() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Set property value @@ -223,8 +218,7 @@ public void SetNameIllegal() ProjectPropertyElement property = GetPropertyXml(); property.Name = "ImportGroup"; - } - ); + }); } /// /// Set property value to empty @@ -251,8 +245,7 @@ public void SetInvalidNullValue() ProjectPropertyElement property = GetPropertyXml(); property.Value = null; - } - ); + }); } /// /// Set condition diff --git a/src/Build.OM.UnitTests/Construction/ProjectPropertyGroupElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectPropertyGroupElement_Tests.cs index ec569875fbb..38f84d1b655 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectPropertyGroupElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectPropertyGroupElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/Construction/ProjectRootElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectRootElement_Tests.cs index da183efaaf8..f1311c25d5c 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectRootElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectRootElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -267,8 +267,7 @@ public void InvalidXml() Assert.Throws(() => { ProjectRootElement.Create(XmlReader.Create(new StringReader("XXX"))); - } - ); + }); } /// @@ -297,8 +296,7 @@ public void InvalidRootTag() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Valid Xml, invalid syntax below the root @@ -315,8 +313,7 @@ public void InvalidChildBelowRoot() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Root indicates upgrade needed @@ -331,8 +328,7 @@ public void NeedsUpgrade() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Valid Xml, invalid namespace below the root @@ -349,8 +345,7 @@ public void InvalidNamespaceBelowRoot() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Tests that the namespace error reports are correct @@ -403,8 +398,7 @@ public void ValidXmlInvalidSyntaxInChildElement() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Valid Xml, invalid syntax, should not get added to the Xml cache and @@ -445,8 +439,7 @@ public void ValidXmlInvalidSyntaxOpenFromDiskTwice() { File.Delete(path); } - } - ); + }); } /// /// Verify that opening project using XmlTextReader does not add it to the Xml cache @@ -561,8 +554,7 @@ public void InvalidSaveWithoutFullPath() ProjectRootElement project = ProjectRootElement.Create(reader); project.Save(); - } - ); + }); } /// /// Save content with transforms. @@ -697,8 +689,7 @@ public void SaveUnnamedProject() { ProjectRootElement project = ProjectRootElement.Create(); project.Save(); - } - ); + }); } /// /// Verifies that the ProjectRootElement.Encoding property getter returns values @@ -935,8 +926,7 @@ public void SolutionCanNotBeOpened() File.Delete(tempFileSentinel); Assert.False(File.Exists(solutionFile)); } - } - ); + }); } /// @@ -979,8 +969,7 @@ public void ProjectCanNotBeOpened() File.Delete(projectFile); Assert.False(File.Exists(projectFile)); } - } - ); + }); } #endif @@ -1011,8 +1000,7 @@ public void SolutionCorrupt() { File.Delete(solutionFile); } - } - ); + }); } /// /// Open lots of projects concurrently to try to trigger problems diff --git a/src/Build.OM.UnitTests/Construction/ProjectTargetElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectTargetElement_Tests.cs index 585c10071f7..891e1bd625d 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectTargetElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectTargetElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -32,8 +32,7 @@ public void AddTargetInvalidName() { ProjectRootElement project = ProjectRootElement.Create(); project.CreateTargetElement("@#$invalid@#$"); - } - ); + }); } /// /// Read targets in an empty project @@ -107,8 +106,7 @@ public void SetInvalidNullInputs() { ProjectTargetElement target = GetTargetXml(); target.Inputs = null; - } - ); + }); } /// /// Set null outputs on the target element @@ -120,8 +118,7 @@ public void SetInvalidNullOutputs() { ProjectTargetElement target = GetTargetXml(); target.Outputs = null; - } - ); + }); } /// /// Set null dependsOnTargets on the target element @@ -133,8 +130,7 @@ public void SetInvalidNullDependsOnTargets() { ProjectTargetElement target = GetTargetXml(); target.DependsOnTargets = null; - } - ); + }); } /// /// Set null dependsOnTargets on the target element @@ -146,8 +142,7 @@ public void SetInvalidNullKeepDuplicateOutputs() { ProjectTargetElement target = GetTargetXml(); target.KeepDuplicateOutputs = null; - } - ); + }); } /// /// Set null condition on the target element @@ -176,8 +171,7 @@ public void ReadInvalidMissingName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read a target with an invalid attribute @@ -194,8 +188,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read an target with two task children diff --git a/src/Build.OM.UnitTests/Construction/ProjectTaskElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectTaskElement_Tests.cs index d469a8da1f8..bffc428efb8 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectTaskElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectTaskElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -97,8 +97,7 @@ public void ReadInvalidChild() "; GetTaskFromContent(content); - } - ); + }); } /// /// Read task with empty parameter. @@ -176,8 +175,7 @@ public void SetInvalidNullParameterValue() ProjectTaskElement task = GetBasicTask(); task.SetParameter("p1", null); - } - ); + }); } /// /// Set a parameter with the reserved name 'continueonerror' @@ -190,8 +188,7 @@ public void SetInvalidParameterNameContinueOnError() ProjectTaskElement task = GetBasicTask(); task.SetParameter("ContinueOnError", "v"); - } - ); + }); } /// /// Set a parameter with the reserved name 'condition' @@ -204,8 +201,7 @@ public void SetInvalidParameterNameCondition() ProjectTaskElement task = GetBasicTask(); task.SetParameter("Condition", "c"); - } - ); + }); } /// /// Set a parameter using a null name @@ -218,8 +214,7 @@ public void SetInvalidNullParameterName() ProjectTaskElement task = GetBasicTask(); task.SetParameter(null, "v1"); - } - ); + }); } /// /// Add a parameter to the task diff --git a/src/Build.OM.UnitTests/Construction/ProjectUsingTaskElement_Tests.cs b/src/Build.OM.UnitTests/Construction/ProjectUsingTaskElement_Tests.cs index e9305ec49ae..e905ecdf342 100644 --- a/src/Build.OM.UnitTests/Construction/ProjectUsingTaskElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/ProjectUsingTaskElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -45,8 +45,7 @@ public void ReadInvalidMissingTaskName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with empty task name attribute @@ -63,8 +62,7 @@ public void ReadInvalidEmptyTaskName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with unexpected attribute @@ -81,8 +79,7 @@ public void ReadInvalidAttribute() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with neither AssemblyFile nor AssemblyName attributes @@ -99,8 +96,7 @@ public void ReadInvalidMissingAssemblyFileAssemblyName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with only empty AssemblyFile attribute @@ -117,8 +113,7 @@ public void ReadInvalidEmptyAssemblyFile() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with empty AssemblyFile attribute but AssemblyName present @@ -135,8 +130,7 @@ public void ReadInvalidEmptyAssemblyFileAndAssemblyNameNotEmpty() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with only empty AssemblyName attribute but AssemblyFile present @@ -153,8 +147,7 @@ public void ReadInvalidEmptyAssemblyNameAndAssemblyFileNotEmpty() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with both AssemblyName and AssemblyFile attributes @@ -171,8 +164,7 @@ public void ReadInvalidBothAssemblyFileAssemblyName() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with both AssemblyName and AssemblyFile attributes but both are empty @@ -189,8 +181,7 @@ public void ReadInvalidBothEmptyAssemblyFileEmptyAssemblyNameBoth() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Read usingtask with assembly file @@ -290,8 +281,7 @@ public void SetUsingTaskAssemblyFileOnUsingTaskAssemblyName() ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyName(); usingTask.AssemblyFile = "afb"; - } - ); + }); } /// /// Set assembly name on a usingtask that already has assembly file @@ -304,8 +294,7 @@ public void SetUsingTaskAssemblyNameOnUsingTaskAssemblyFile() ProjectUsingTaskElement usingTask = GetUsingTaskAssemblyFile(); usingTask.AssemblyName = "anb"; - } - ); + }); } /// /// Set task name @@ -370,8 +359,7 @@ public void DuplicateParameterGroup() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); - } - ); + }); } /// /// Make sure there is an exception when there are multiple task groups in the using task tag. @@ -391,8 +379,7 @@ public void DuplicateTaskGroup() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); - } - ); + }); } /// /// Make sure there is an exception when there is an unknown child @@ -411,8 +398,7 @@ public void UnknownChild() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); - } - ); + }); } /// /// Make sure there is an no exception when there are children in the using task @@ -460,8 +446,7 @@ public void ExceptionWhenNoTaskFactoryAndHavePG() ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Helpers.GetFirst(project.Children); Assert.True(false); - } - ); + }); } /// /// Make sure there is an exception when a parameter group is added but no task factory attribute is on the using task @@ -482,8 +467,7 @@ public void ExceptionWhenNoTaskFactoryAndHaveTask() ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Helpers.GetFirst(project.Children); Assert.True(false); - } - ); + }); } /// /// Helper to get a ProjectUsingTaskElement with a task factory, required runtime and required platform diff --git a/src/Build.OM.UnitTests/Construction/SolutionFile_Tests.cs b/src/Build.OM.UnitTests/Construction/SolutionFile_Tests.cs index e739dcafc4f..fb060ae1026 100644 --- a/src/Build.OM.UnitTests/Construction/SolutionFile_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/SolutionFile_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -53,8 +53,7 @@ public void ParseSolution_VC() ParseSolutionHelper(solutionFileContents); Assert.True(false, "Should not get here"); - } - ); + }); } /// /// Test that a project with the C++ project guid and an arbitrary extension is seen as valid -- @@ -219,8 +218,7 @@ public void BadVersionStamp() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Expected version numbers less than 7 to cause an invalid project file exception. @@ -237,8 +235,7 @@ public void VersionTooLow() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Test to parse a very basic .sln file to validate that description property in a solution file @@ -788,8 +785,7 @@ public void ParseInvalidSolutionConfigurations1() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Test some invalid cases for solution configuration parsing @@ -815,8 +811,7 @@ public void ParseInvalidSolutionConfigurations2() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Test some invalid cases for solution configuration parsing @@ -842,8 +837,7 @@ public void ParseInvalidSolutionConfigurations3() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Make sure the project configurations in solution configurations get parsed correctly diff --git a/src/Build.OM.UnitTests/Construction/UsingTaskBodyElement_Tests.cs b/src/Build.OM.UnitTests/Construction/UsingTaskBodyElement_Tests.cs index 3396ae04416..b941411298c 100644 --- a/src/Build.OM.UnitTests/Construction/UsingTaskBodyElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/UsingTaskBodyElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -48,8 +48,7 @@ public void ReadInvalidAttribute() ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); - } - ); + }); } /// /// Create a task body outside of a using task @@ -68,8 +67,7 @@ public void CreateBodyOutsideUsingTask() "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Set body value @@ -110,8 +108,7 @@ public void SetInvalidNullValue() ProjectUsingTaskBodyElement body = GetBodyXml(); body.TaskBody = null; Assert.True(false); - } - ); + }); } /// /// Verify setting the value of evaluate to null will wipe out the element and then the property will return true by default. diff --git a/src/Build.OM.UnitTests/Construction/UsingTaskParameterElement_Tests.cs b/src/Build.OM.UnitTests/Construction/UsingTaskParameterElement_Tests.cs index 35b673f7e05..a6dd098573f 100644 --- a/src/Build.OM.UnitTests/Construction/UsingTaskParameterElement_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/UsingTaskParameterElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -92,8 +92,7 @@ public void ReadInvalidAttribute() ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); - } - ); + }); } /// /// Set type value diff --git a/src/Build.OM.UnitTests/Construction/UsingTaskParameterGroup_Tests.cs b/src/Build.OM.UnitTests/Construction/UsingTaskParameterGroup_Tests.cs index 16d94683c80..82b99505a26 100644 --- a/src/Build.OM.UnitTests/Construction/UsingTaskParameterGroup_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/UsingTaskParameterGroup_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -109,8 +109,7 @@ public void ReadDuplicateChildParameters() { GetParameterGroupXml(s_contentDuplicateParameters); Assert.True(false); - } - ); + }); } /// /// Read parameterGroup with a attribute @@ -130,8 +129,7 @@ public void ReadInvalidAttribute() ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); Assert.True(false); - } - ); + }); } /// /// Helper to get a UsingTaskParameterGroupElement from xml diff --git a/src/Build.OM.UnitTests/Construction/WhiteSpacePreservation_Tests.cs b/src/Build.OM.UnitTests/Construction/WhiteSpacePreservation_Tests.cs index 8bbf86c4278..5985ad2754e 100644 --- a/src/Build.OM.UnitTests/Construction/WhiteSpacePreservation_Tests.cs +++ b/src/Build.OM.UnitTests/Construction/WhiteSpacePreservation_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.OM.UnitTests/Definition/DefinitionEditing_Tests.cs b/src/Build.OM.UnitTests/Definition/DefinitionEditing_Tests.cs index 586b3cb9ecd..5b5f799bf78 100644 --- a/src/Build.OM.UnitTests/Definition/DefinitionEditing_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/DefinitionEditing_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -232,8 +232,7 @@ public void AddItem_InvalidEmptyInclude() Project project = new Project(); project.AddItem("i", String.Empty); - } - ); + }); } /// /// Add an item with null metadata parameter. @@ -528,8 +527,8 @@ public void AddItem_MatchesComplicatedWildcard() ProjectItemElement item2 = project.AddItem( "i", - NativeMethodsShared.IsWindows ? @"c:\subdir1\a\b\subdir2\c\i1.xyx" : "/subdir1/a/b/subdir2/c/i1.xyx") - [0].Xml; + NativeMethodsShared.IsWindows ? @"c:\subdir1\a\b\subdir2\c\i1.xyx" : "/subdir1/a/b/subdir2/c/i1.xyx")[ + 0].Xml; string expected = ObjectModelHelpers.CleanupFileContents( NativeMethodsShared.IsWindows ? @@ -1156,7 +1155,7 @@ public void RenameItem_StillMatchesWildcard() [MemberData(nameof(ItemElementsWithGlobsThatRequireSplitting))] public void RenameThrowsWhenItemElementSplittingIsDisabled(string projectContents, int itemIndex, SetupProject setupProject) { - AssertDisabledItemSplitting(projectContents, itemIndex, setupProject, (p, i) => {i.Rename("foo"); }); + AssertDisabledItemSplitting(projectContents, itemIndex, setupProject, (p, i) => { i.Rename("foo"); }); } /// @@ -1457,7 +1456,7 @@ public void RemoveItemThrowsWhenItemElementSplittingIsDisabled(string projectCon [MemberData(nameof(ItemElementsWithGlobsThatRequireSplitting))] public void RemoveItemsThrowsWhenItemElementSplittingIsDisabled(string projectContents, int itemIndex, SetupProject setupProject) { - AssertDisabledItemSplitting(projectContents, itemIndex, setupProject, (p, i) => { p.RemoveItems(new [] {i}); }); + AssertDisabledItemSplitting(projectContents, itemIndex, setupProject, (p, i) => { p.RemoveItems(new[] { i }); }); } /// @@ -1589,8 +1588,7 @@ public void SetPropertyAfterRemoved() var property = project.SetProperty("p", "v1"); property.Xml.Parent.RemoveAllChildren(); property.UnevaluatedValue = "v2"; - } - ); + }); } /// /// Setting an evaluated property after its XML's parent has been removed should @@ -1605,8 +1603,7 @@ public void SetPropertyAfterRemoved2() var property = project.SetProperty("p", "v1"); property.Xml.Parent.Parent.RemoveAllChildren(); property.UnevaluatedValue = "v2"; - } - ); + }); } /// /// Setting an evaluated metadatum after its XML has been removed should @@ -1621,8 +1618,7 @@ public void SetMetadatumAfterRemoved() var metadatum = project.AddItem("i", "i1")[0].SetMetadataValue("p", "v1"); metadatum.Xml.Parent.RemoveAllChildren(); metadatum.UnevaluatedValue = "v2"; - } - ); + }); } /// /// Changing an item's type after its XML has been removed should @@ -1637,8 +1633,7 @@ public void SetItemTypeAfterRemoved() var item = project.AddItem("i", "i1")[0]; item.Xml.Parent.RemoveAllChildren(); item.ItemType = "j"; - } - ); + }); } /// /// Changing an item's type after its XML has been removed should @@ -1653,8 +1648,7 @@ public void RemoveMetadataAfterItemRemoved() var item = project.AddItem("i", "i1")[0]; item.Xml.Parent.RemoveAllChildren(); item.RemoveMetadata("m"); - } - ); + }); } [Theory] @@ -1678,8 +1672,7 @@ public void RemoveMetadataThrowsWhenItemElementSplittingIsDisabled(string projec new[] // files that should be captured by the glob { "a.foo" - } - )] + })] // explode on item coming from glob that expands to multiple items [InlineData( @" @@ -1694,8 +1687,7 @@ public void RemoveMetadataThrowsWhenItemElementSplittingIsDisabled(string projec { "a.foo", "b.foo" - } - )] + })] public void RemoveMetadataThrowsWhenItemElementSplittingIsDisabledAndItemComesFromGlob(string projectContents, int itemIndex, string[] files) { using (var env = TestEnvironment.Create()) @@ -1730,8 +1722,7 @@ public void SetMetadatumAfterRemoved2() var metadatum = project.AddItem("i", "i1")[0].SetMetadataValue("p", "v1"); metadatum.Xml.Parent.Parent.RemoveAllChildren(); metadatum.UnevaluatedValue = "v2"; - } - ); + }); } /// /// Setting an evaluated metadatum after its XML's parent's parent has been removed should @@ -1746,8 +1737,7 @@ public void SetMetadatumAfterRemoved3() var metadatum = project.AddItem("i", "i1")[0].SetMetadataValue("p", "v1"); metadatum.Xml.Parent.Parent.Parent.RemoveAllChildren(); metadatum.UnevaluatedValue = "v2"; - } - ); + }); } [Theory] @@ -2161,8 +2151,7 @@ public void AddItemFast_InvalidEmptyInclude() Project project = new Project(); project.AddItemFast("i", String.Empty); - } - ); + }); } /// /// Add an item with null metadata parameter. diff --git a/src/Build.OM.UnitTests/Definition/EditingElementsReferencedByOrReferences_Tests.cs b/src/Build.OM.UnitTests/Definition/EditingElementsReferencedByOrReferences_Tests.cs index ec11160ae1c..0b63edcfbef 100644 --- a/src/Build.OM.UnitTests/Definition/EditingElementsReferencedByOrReferences_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/EditingElementsReferencedByOrReferences_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs b/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs index ca3f74502fe..1005cc140f2 100644 --- a/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProjectCollection_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -132,7 +132,10 @@ public void AddProjectOnSave_SpecifiedProjectCollection() } finally { - if (path != null) File.Delete(path); + if (path != null) + { + File.Delete(path); + } } } @@ -769,8 +772,7 @@ public void UnloadProjectXmlWhileInImportUse() Console.WriteLine(ex.Message); throw; } - } - ); + }); } /// @@ -838,8 +840,15 @@ public void SaveToNewNameAndUnload() } finally { - if (file1 != null) File.Delete(file1); - if (file2 != null) File.Delete(file2); + if (file1 != null) + { + File.Delete(file1); + } + + if (file2 != null) + { + File.Delete(file2); + } } } @@ -874,8 +883,15 @@ public void LoadUnloadReloadSaveToNewName() } finally { - if (file1 != null) File.Delete(file1); - if (file2 != null) File.Delete(file2); + if (file1 != null) + { + File.Delete(file1); + } + + if (file2 != null) + { + File.Delete(file2); + } } } @@ -910,8 +926,15 @@ public void LoadUnloadAllReloadSaveToNewName() } finally { - if (file1 != null) File.Delete(file1); - if (file2 != null) File.Delete(file2); + if (file1 != null) + { + File.Delete(file1); + } + + if (file2 != null) + { + File.Delete(file2); + } } } diff --git a/src/Build.OM.UnitTests/Definition/ProjectItemDefinition_Tests.cs b/src/Build.OM.UnitTests/Definition/ProjectItemDefinition_Tests.cs index b6196db8d6a..caeacc2c859 100644 --- a/src/Build.OM.UnitTests/Definition/ProjectItemDefinition_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProjectItemDefinition_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -139,8 +139,7 @@ public void UpdateMetadataImported() { File.Delete(file); } - } - ); + }); } /// /// Attempt to add new metadata on imported item definition should succeed, @@ -166,8 +165,7 @@ public void SetMetadataImported() ProjectItemDefinition definition = project.ItemDefinitions["i"]; definition.SetMetadataValue("n", "n0"); - string expected = String.Format - ( + string expected = String.Format( ObjectModelHelpers.CleanupFileContents( @" @@ -177,8 +175,7 @@ public void SetMetadataImported() "), - file - ); + file); Helpers.VerifyAssertProjectContent(expected, project.Xml); } @@ -477,8 +474,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_BuiltInProhibitedOnItemDefinitionM "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -500,8 +496,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_UnquotedBuiltInProhibitedOnItemDef "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -523,8 +518,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_BuiltInProhibitedOnItemDefinitionC "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -546,8 +540,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_BuiltInProhibitedOnItemDefinitionG "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -569,8 +562,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_QualifiedBuiltInProhibitedOnItemDe "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -592,8 +584,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_QualifiedBuiltInProhibitedOnItemDe "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -615,8 +606,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_QualifiedBuiltInProhibitedOnItemDe "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Built-in metadata is prohibited in item definition conditions. @@ -638,8 +628,7 @@ public void ExpandBuiltInMetadataAtPointOfUse_UnquotedQualifiedBuiltInProhibited "); Project project = new Project(XmlReader.Create(new StringReader(content))); - } - ); + }); } /// /// Custom metadata is allowed in item definition conditions. diff --git a/src/Build.OM.UnitTests/Definition/ProjectItem_Tests.cs b/src/Build.OM.UnitTests/Definition/ProjectItem_Tests.cs index 0d44fcf3f06..293cdb4ff05 100644 --- a/src/Build.OM.UnitTests/Definition/ProjectItem_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProjectItem_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -231,8 +231,7 @@ public void SetInvalidXmlNameMetadata() ProjectItem item = GetOneItemFromFragment(@""); item.SetMetadataValue("##invalid##", "x"); - } - ); + }); } /// /// Attempting to set built-in metadata should fail @@ -245,8 +244,7 @@ public void SetInvalidBuiltInMetadata() ProjectItem item = GetOneItemFromFragment(@""); item.SetMetadataValue("FullPath", "x"); - } - ); + }); } /// /// Attempting to set reserved metadata should fail @@ -259,8 +257,7 @@ public void SetInvalidReservedMetadata() ProjectItem item = GetOneItemFromFragment(@""); item.SetMetadataValue("Choose", "x"); - } - ); + }); } /// /// Metadata enumerator should only return custom metadata @@ -837,7 +834,7 @@ private static void ProjectGetterResultsInDriveEnumerationWarning(string unevalu Project project = new Project(projectCollection); // Add item - _= project.AddItem("i", unevaluatedInclude); + _ = project.AddItem("i", unevaluatedInclude); // Verify collectionLogger.WarningCount.ShouldBe(1); @@ -927,7 +924,7 @@ public void LogWindowsWarningUponProjectInstanceCreationFromDriveEnumeratingCont public void LogWarningUponProjectInstanceCreationFromDriveEnumeratingContent(string content, string placeHolder, string excludePlaceHolder = null) { content = string.Format(content, placeHolder, excludePlaceHolder); - CleanContentsAndCreateProjectInstanceFromFileWithDriveEnumeratingWildcard(content, false); + CleanContentsAndCreateProjectInstanceFromFileWithDriveEnumeratingWildcard(content, false); } private static void CleanContentsAndCreateProjectInstanceFromFileWithDriveEnumeratingWildcard(string content, bool throwException) @@ -1014,8 +1011,8 @@ private static void TestIncludeExclude(string projectContents, string[] inputFil { @"project\a", }, - false // whether the include survives the exclude (true) or not (false) - )] + false) // whether the include survives the exclude (true) or not (false) + ] // exclude matches include; file is below the project file [InlineData(ItemWithIncludeAndExclude, @"a", @@ -1028,8 +1025,7 @@ private static void TestIncludeExclude(string projectContents, string[] inputFil { @"project\dir\a", }, - false - )] + false)] // exclude matches include; file is above the project file [InlineData(ItemWithIncludeAndExclude, @"a", @@ -1042,8 +1038,7 @@ private static void TestIncludeExclude(string projectContents, string[] inputFil { @"a", }, - false - )] + false)] // exclude does not match include; file is next to project file; exclude points above the project file [InlineData(ItemWithIncludeAndExclude, "a", @@ -1056,8 +1051,7 @@ private static void TestIncludeExclude(string projectContents, string[] inputFil { "a", }, - true - )] + true)] // exclude does not match include; file is below the project file; exclude points next to the project file [InlineData(ItemWithIncludeAndExclude, "a", @@ -1070,8 +1064,7 @@ private static void TestIncludeExclude(string projectContents, string[] inputFil { @"project\dir\a", }, - true - )] + true)] // exclude does not match include; file is above the project file; exclude points next to the project file [InlineData(ItemWithIncludeAndExclude, "a", @@ -1084,8 +1077,7 @@ private static void TestIncludeExclude(string projectContents, string[] inputFil { "a", }, - true - )] + true)] public void IncludeAndExcludeWorkWithRelativeAndAbsolutePaths( string projectContents, string includeItem, @@ -1133,26 +1125,24 @@ public void IncludeAndExcludeWorkWithRelativeAndAbsolutePaths( [InlineData( "../a.cs;b.cs", // include string "**/*.cs", // exclude string - new[] {"a.cs", "ProjectDir/b.cs"}, // files to create relative to the test root dir + new[] { "a.cs", "ProjectDir/b.cs" }, // files to create relative to the test root dir "ProjectDir", // relative path from test root to project - new[] { "../a.cs" } // expected items - )] + new[] { "../a.cs" }) // expected items + ] // exclude globbing cone below project level; [InlineData( "a.cs;a/b.cs", "a/**/*.cs", new[] { "a.cs", "a/b.cs" }, "", - new[] { "a.cs" } - )] + new[] { "a.cs" })] // exclude globbing above project level; [InlineData( "a.cs;../b.cs;../../c.cs", "../**/*.cs", new[] { "a/ProjectDir/a.cs", "a/b.cs", "c.cs" }, "a/ProjectDir", - new[] { "../../c.cs" } - )] + new[] { "../../c.cs" })] public void ExcludeWithMissmatchingGlobCones(string includeString, string excludeString, string[] files, string relativePathFromRootToProject, string[] expectedInclude) { var projectContents = string.Format(ItemWithIncludeAndExclude, includeString, excludeString); @@ -1171,8 +1161,8 @@ public void ExcludeWithMissmatchingGlobCones(string includeString, string exclud "a.cs", // exclude string new[] { "ProjectDir/a.cs", "b.cs" }, // files to create relative to the test root dir "ProjectDir", // relative path from test root to project - new[] { "../b.cs" } // expected items - )] + new[] { "../b.cs" }) // expected items + ] public void ExcludingRelativeItemToCurrentDirectoryShouldWorkWithAboveTheConeIncludes(string includeString, string excludeString, string[] files, string relativePathFromRootToProject, string[] expectedInclude) { var projectContents = string.Format(ItemWithIncludeAndExclude, includeString, excludeString); @@ -1642,8 +1632,7 @@ public void BuiltInMetadataInItemCondition() "; GetOneItem(content); - } - ); + }); } /// /// Two items should each get their own values for built-in metadata @@ -1924,8 +1913,7 @@ public void RemoveItemDefinitionMetadataNotMasked() ProjectItem item = Helpers.GetFirst(project.GetItems("i")); item.RemoveMetadata("m"); // Should throw - } - ); + }); } /// /// Remove a nonexistent metadatum @@ -1958,8 +1946,7 @@ public void RemoveBuiltInMetadata() // This should throw item.RemoveMetadata("FullPath"); - } - ); + }); } /// /// Simple rename @@ -2048,8 +2035,7 @@ public void ChangeItemTypeInvalid() project.ReevaluateIfNecessary(); item.ItemType = "|"; - } - ); + }); } /// /// Attempt to rename imported item should fail @@ -2080,8 +2066,7 @@ public void RenameImported() { File.Delete(file); } - } - ); + }); } /// /// Attempt to set metadata on imported item should fail @@ -2112,8 +2097,7 @@ public void SetMetadataImported() { File.Delete(file); } - } - ); + }); } /// /// Attempt to remove metadata on imported item should fail @@ -2145,8 +2129,7 @@ public void RemoveMetadataImported() { File.Delete(file); } - } - ); + }); } [Fact] @@ -2325,8 +2308,7 @@ public void Remove() { IList items = ObjectModelHelpers.GetItemsFromFragment( "" + - "" - ); + ""); Assert.Single(items); Assert.Equal("a", items[0].EvaluatedInclude); @@ -2338,8 +2320,7 @@ public void RemoveAllMatchingItems() IList items = ObjectModelHelpers.GetItemsFromFragment( "" + "" + - "" - ); + ""); Assert.Equal(2, items.Count); Assert.Equal(@"a;a", string.Join(";", items.Select(i => i.EvaluatedInclude))); @@ -2350,8 +2331,7 @@ public void RemoveGlob() { IList items = ObjectModelHelpers.GetItemsFromFragment( @"" + - @"" - ); + @""); Assert.Equal(2, items.Count); Assert.Equal(@"a.txt;b.cs", string.Join(";", items.Select(i => i.EvaluatedInclude))); @@ -2363,8 +2343,7 @@ public void RemoveItemReference() IList items = ObjectModelHelpers.GetItemsFromFragment( @"" + @"" + - @"" - ); + @""); Assert.Equal(2, items.Count); Assert.Equal(@"a;c", string.Join(";", items.Select(i => i.EvaluatedInclude))); @@ -2393,8 +2372,7 @@ public void RemoveShouldRespectCondition() var projectContents = ObjectModelHelpers.FormatProjectContentsWithItemGroupFragment( @"" + @"" + - @"" - ); + @""); var project = ObjectModelHelpers.CreateInMemoryProject(projectContents); @@ -2411,8 +2389,7 @@ public void RemoveWithConditionShouldNotApplyOnItemsIgnoringCondition() @"" + @"" + @"" + - @"" - ); + @""); var project = ObjectModelHelpers.CreateInMemoryProject(projectContents); @@ -2482,7 +2459,7 @@ public void RemoveWithItemReferenceOnFilePathMatchingMetadata() - + @@ -3683,8 +3660,7 @@ public void UpdateAndRemoveShouldNotUseGlobMatchingOnEscapedGlobsFromReferencedI project, inputFiles: Array.Empty(), expectedInclude: new[] { "1.cs", "2.js" }, - expectedMetadataPerItem: null - ); + expectedMetadataPerItem: null); } [Theory] diff --git a/src/Build.OM.UnitTests/Definition/ProjectMetadata_Tests.cs b/src/Build.OM.UnitTests/Definition/ProjectMetadata_Tests.cs index 42e18a5c742..2078a37b8db 100644 --- a/src/Build.OM.UnitTests/Definition/ProjectMetadata_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProjectMetadata_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -461,8 +461,7 @@ public void SetMetadataImported() Assert.True(metadata.IsImported); metadata.UnevaluatedValue = "m1"; - } - ); + }); } /// /// Escaping in metadata values diff --git a/src/Build.OM.UnitTests/Definition/ProjectProperty_Tests.cs b/src/Build.OM.UnitTests/Definition/ProjectProperty_Tests.cs index 7dc0fae6b3f..b53259968f4 100644 --- a/src/Build.OM.UnitTests/Definition/ProjectProperty_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProjectProperty_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -139,8 +139,7 @@ public void InvalidSetValueBuiltInProperty() ProjectProperty property = project.GetProperty("MSBuildProjectDirectory"); property.UnevaluatedValue = "v"; - } - ); + }); } /// /// Set the value of a property originating in the environment. @@ -279,8 +278,7 @@ public void SetPropertyImported() { File.Delete(file); } - } - ); + }); } /// /// Get the property named "p" in the project provided diff --git a/src/Build.OM.UnitTests/Definition/Project_Tests.cs b/src/Build.OM.UnitTests/Definition/Project_Tests.cs index a3457bbcd44..d8ed8d18514 100644 --- a/src/Build.OM.UnitTests/Definition/Project_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/Project_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -244,8 +244,7 @@ public void ReadFromEmptyReader1() { XmlReader reader = XmlReader.Create(new StringReader(String.Empty)); ProjectRootElement.Create(reader); - } - ); + }); } /// /// Reading from an XMLReader that has no content should throw the correct @@ -258,8 +257,7 @@ public void ReadFromEmptyReader2() { XmlReader reader = XmlReader.Create(new StringReader(String.Empty)); Project project = new Project(reader); - } - ); + }); } /// /// Reading from an XMLReader that has no content should throw the correct @@ -278,8 +276,7 @@ public void ReadFromEmptyReader3() } Project project = (new ProjectCollection()).LoadProject(reader); - } - ); + }); } /// @@ -294,8 +291,7 @@ public void ReadFromClosedReader() XmlReader reader = XmlReader.Create(new StringReader(String.Empty)); reader.Dispose(); Project project = new Project(reader); - } - ); + }); } /// @@ -328,8 +324,7 @@ public void ImportDoesNotExistDefaultSettings() xml.AddImport("__nonexistent__"); Project project = new Project(xml); - } - ); + }); } /// /// Import gives invalid uri exception @@ -343,8 +338,7 @@ public void ImportInvalidUriFormat() xml.AddImport(@"//MSBuildExtensionsPath32)\4.0\Microsoft.VisualStudioVersion.v11.Common.props"); Project project = new Project(xml); - } - ); + }); } /// /// Necessary but not sufficient for MSBuild evaluation to be thread safe. @@ -393,8 +387,7 @@ public void TryImportsIncludingDuplicatesExpectException() Project project = new Project(xml, null, null, new ProjectCollection(), ProjectLoadSettings.IgnoreMissingImports); IList imports = project.ImportsIncludingDuplicates; imports.ShouldBeEmpty(); - } - ); + }); } /// /// Import self ignored @@ -919,8 +912,7 @@ public void ChangeGlobalPropertyAfterReevaluation2() project.SetGlobalProperty("p", "v1"); project.ReevaluateIfNecessary(); project.SetProperty("p", "v2"); - } - ); + }); } /// /// Setting environment property should create a real property @@ -949,8 +941,7 @@ public void SetReservedPropertyThroughProject() { Project project = new Project(); project.SetProperty("msbuildprojectdirectory", "v1"); - } - ); + }); } /// /// Changing global properties with some preexisting. @@ -2131,8 +2122,7 @@ public void UsingTaskExpansion1() ProjectRootElement xml = ProjectRootElement.Create(); xml.AddUsingTask("x", "@(x->'%(x)')", null); Project project = new Project(xml); - } - ); + }); } /// /// UsingTask expansion should throw InvalidProjectFileException @@ -2146,8 +2136,7 @@ public void UsingTaskExpansion2() ProjectRootElement xml = ProjectRootElement.Create(); xml.AddUsingTask("@(x->'%(x)')", "y", null); Project project = new Project(xml); - } - ); + }); } /// /// UsingTask expansion should throw InvalidProjectFileException @@ -2161,8 +2150,7 @@ public void UsingTaskExpansion3() ProjectRootElement xml = ProjectRootElement.Create(); xml.AddUsingTask("x", null, "@(x->'%(x)')"); Project project = new Project(xml); - } - ); + }); } /// /// Saving project should make it "clean" for saving @@ -2348,8 +2336,7 @@ public void RemoveItemsOneNull() { Project project = new Project(); project.RemoveItems(new List() { null }); - } - ); + }); } /// /// Remove several items where removing the first one @@ -2368,8 +2355,7 @@ public void RemoveItemWrongProject() Project project2 = new Project(root2); project1.RemoveItems(project2.Items); - } - ); + }); } /// /// Remove an item that is no longer attached. For convenience, @@ -2406,8 +2392,7 @@ public void ReservedPropertyProjectConstructor() globalProperties.Add("msbuildprojectdirectory", "x"); Project project = new Project(globalProperties, null, new ProjectCollection()); - } - ); + }); } /// /// Reserved property in project collection global properties should log an error then rethrow @@ -2431,8 +2416,7 @@ public void ReservedPropertyProjectCollectionConstructor() { logger.AssertLogContains("MSB4177"); } - } - ); + }); } /// /// Invalid property (reserved name) in project collection global properties should log an error then rethrow @@ -2456,8 +2440,7 @@ public void ReservedPropertyProjectCollectionConstructor2() { logger.AssertLogContains("MSB4177"); } - } - ); + }); } /// /// Create tree like this @@ -2527,8 +2510,7 @@ public void ReservedPropertyProjectCollectionConstructor3() { logger.AssertLogContains("MSB4177"); } - } - ); + }); } /// /// Create a structure of various imports and verify that project.GetLogicalProject() @@ -2642,8 +2624,7 @@ public void ImportPropertyEvaluatingToEmpty() "); Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents))); - } - ); + }); } [Fact] @@ -2691,8 +2672,7 @@ public void ImportPropertyEvaluatingToInvalidPath() "); Project project = new Project(XmlReader.Create(new StringReader(projectOriginalContents))); - } - ); + }); } [Fact] @@ -3677,28 +3657,28 @@ public void GetAllGlobsShouldFindAllExcludesAndRemoves() } [Theory] -// [InlineData( -// @" -// -// -// ", -// new[] {"ba"}, -// new[] {"a", "ca", "da", "ea", "fa"} -// )] -// [InlineData( -// @" -// -// ", -// new[] {"ba", "ea", "fa"}, -// new[] {"a", "ca", "da"} -// )] -// [InlineData( -// @" -// -// ", -// new[] {"ba", "ca", "da", "ea", "fa"}, -// new[] {"a"} -// )] + // [InlineData( + // @" + // + // + // ", + // new[] {"ba"}, + // new[] {"a", "ca", "da", "ea", "fa"} + // )] + // [InlineData( + // @" + // + // ", + // new[] {"ba", "ea", "fa"}, + // new[] {"a", "ca", "da"} + // )] + // [InlineData( + // @" + // + // ", + // new[] {"ba", "ca", "da", "ea", "fa"}, + // new[] {"a"} + // )] [InlineData( @" @@ -3708,13 +3688,11 @@ public void GetAllGlobsShouldFindAllExcludesAndRemoves() ", new[] { "aa", "bb", "cc" }, - new[] { "b", "c" } - )] + new[] { "b", "c" })] [InlineData( @"", new[] { "ab", "de" }, - new[] { "bc", "b|c", "b", "c" } - )] + new[] { "bc", "b|c", "b", "c" })] public void GetAllGlobsShouldProduceGlobThatMatches(string itemContents, string[] stringsThatShouldMatch, string[] stringsThatShouldNotMatch) { var projectTemplate = diff --git a/src/Build.OM.UnitTests/Definition/ProtectImports_Tests.cs b/src/Build.OM.UnitTests/Definition/ProtectImports_Tests.cs index 880504db761..9da3706a604 100644 --- a/src/Build.OM.UnitTests/Definition/ProtectImports_Tests.cs +++ b/src/Build.OM.UnitTests/Definition/ProtectImports_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -136,8 +136,7 @@ public void PropertySetViaProperty() // This should throw property.UnevaluatedValue = NewValue; - } - ); + }); } /// /// Tests against edits into imported properties through the project. @@ -168,8 +167,7 @@ public void PropertyRemove() // This should throw project.RemoveProperty(property); - } - ); + }); } #endregion @@ -188,8 +186,7 @@ public void ItemImportedChangeType() // This should throw item.ItemType = "NewItemType"; - } - ); + }); } /// /// Tests imported item renaming. @@ -204,8 +201,7 @@ public void ItemImportedRename() // This should throw item.Rename("NewItemName"); - } - ); + }); } /// /// Tests imported item SetUnevaluatedValue. @@ -220,8 +216,7 @@ public void ItemImportedSetUnevaluatedValue() // This should throw item.UnevaluatedInclude = "NewItemName"; - } - ); + }); } /// /// Tests imported item removal. @@ -236,8 +231,7 @@ public void ItemImportedRemove() // This should throw project.RemoveItem(item); - } - ); + }); } /// /// Tests project item type change. @@ -312,8 +306,7 @@ public void MetadataImportSetViaProject() // This should throw item.SetMetadataValue(ImportedMetadataName, "NewImportedMetadataValue"); - } - ); + }); } /// /// Tests setting new metadata in import. @@ -328,8 +321,7 @@ public void MetadataImportAdd() // This should throw item.SetMetadataValue("NewMetadata", "NewImportedMetadataValue"); - } - ); + }); } /// /// Tests setting new metadata in import. @@ -344,8 +336,7 @@ public void MetadataImportSetViaMetadata() // This should throw metadata.UnevaluatedValue = NewValue; - } - ); + }); } /// /// Tests removing metadata in import. @@ -360,8 +351,7 @@ public void MetadataImportRemove() // This should throw item.RemoveMetadata(ImportedMetadataName); - } - ); + }); } /// /// Tests setting existing metadata in import. @@ -439,8 +429,7 @@ public void DefinitionMetadataImportSetViaMetadata() // This should throw metadata.UnevaluatedValue = NewValue; - } - ); + }); } /// /// Tests removing metadata in imported item definition. @@ -455,8 +444,7 @@ public void DefinitionMetadataImportRemove() // This should throw item.RemoveMetadata(NonOverridableMetadataName); - } - ); + }); } /// /// Tests setting existing metadata in import. diff --git a/src/Build.OM.UnitTests/Instance/ProjectInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectInstance_Tests.cs index 9b9ea6ff098..7fd5bf6425f 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -157,8 +157,7 @@ public void AddItemInvalidNullItemType() { ProjectInstance p = GetEmptyProjectInstance(); p.AddItem(null, "i1"); - } - ); + }); } /// /// Add item empty item type @@ -170,8 +169,7 @@ public void AddItemInvalidEmptyItemType() { ProjectInstance p = GetEmptyProjectInstance(); p.AddItem(String.Empty, "i1"); - } - ); + }); } /// /// Add item null include @@ -183,8 +181,7 @@ public void AddItemInvalidNullInclude() { ProjectInstance p = GetEmptyProjectInstance(); p.AddItem("i", null); - } - ); + }); } /// /// Add item null metadata @@ -349,8 +346,7 @@ public void BuildNullTargetInArray() { ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create()); instance.Build(new string[] { null }, null); - } - ); + }); } /// /// Null logger in array should give ArgumentNullException @@ -362,8 +358,7 @@ public void BuildNullLoggerInArray() { ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create()); instance.Build("t", new ILogger[] { null }); - } - ); + }); } /// /// Null remote logger in array should give ArgumentNullException @@ -375,8 +370,7 @@ public void BuildNullRemoteLoggerInArray() { ProjectInstance instance = new ProjectInstance(ProjectRootElement.Create()); instance.Build("t", null, new ForwardingLoggerRecord[] { null }); - } - ); + }); } /// /// Null target name should imply the default target diff --git a/src/Build.OM.UnitTests/Instance/ProjectItemInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectItemInstance_Tests.cs index c3316bb2267..3e8f8a63a0e 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectItemInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectItemInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -128,8 +128,7 @@ public void SetInvalidEmptyInclude() { ProjectItemInstance item = GetItemInstance(); item.EvaluatedInclude = String.Empty; - } - ); + }); } /// /// Set include to invalid null value @@ -141,8 +140,7 @@ public void SetInvalidNullInclude() { ProjectItemInstance item = GetItemInstance(); item.EvaluatedInclude = null; - } - ); + }); } /// /// Create an item with a metadatum that has a null value @@ -204,8 +202,7 @@ public void SetInvalidNullMetadataName() { ProjectItemInstance item = GetItemInstance(); item.SetMetadata(null, "m1"); - } - ); + }); } /// /// Set metadata with invalid empty name @@ -217,8 +214,7 @@ public void SetInvalidEmptyMetadataName() { ProjectItemInstance item = GetItemInstance(); item.SetMetadata(String.Empty, "m1"); - } - ); + }); } /// /// Cast to ITaskItem @@ -647,8 +643,7 @@ public void BuiltInMetadataInItemCondition() "; GetOneItem(content); - } - ); + }); } /// /// Two items should each get their own values for built-in metadata diff --git a/src/Build.OM.UnitTests/Instance/ProjectMetadataInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectMetadataInstance_Tests.cs index f716a9469c1..4032f6014f2 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectMetadataInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectMetadataInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; diff --git a/src/Build.OM.UnitTests/Instance/ProjectOnErrorInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectOnErrorInstance_Tests.cs index 6804c09e7d0..65d57fca9f6 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectOnErrorInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectOnErrorInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/Instance/ProjectPropertyInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectPropertyInstance_Tests.cs index 1f925217111..45726eac668 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectPropertyInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectPropertyInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Evaluation; @@ -70,8 +70,7 @@ public void SetInvalidNullValue() { ProjectPropertyInstance property = GetPropertyInstance(); property.EvaluatedValue = null; - } - ); + }); } /// /// Immutable getter diff --git a/src/Build.OM.UnitTests/Instance/ProjectTargetInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectTargetInstance_Tests.cs index c6866746365..a9345ebf6cd 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectTargetInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectTargetInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/src/Build.OM.UnitTests/Instance/ProjectTaskInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectTaskInstance_Tests.cs index 2a7a9f6c73b..52a7f5a2fe1 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectTaskInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectTaskInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/Instance/ProjectTaskOutputItemInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectTaskOutputItemInstance_Tests.cs index 5afc11bd1b7..53101e5ff09 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectTaskOutputItemInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectTaskOutputItemInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/Instance/ProjectTaskOutputPropertyInstance_Tests.cs b/src/Build.OM.UnitTests/Instance/ProjectTaskOutputPropertyInstance_Tests.cs index a1f8045d634..ef41a9564f9 100644 --- a/src/Build.OM.UnitTests/Instance/ProjectTaskOutputPropertyInstance_Tests.cs +++ b/src/Build.OM.UnitTests/Instance/ProjectTaskOutputPropertyInstance_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; diff --git a/src/Build.OM.UnitTests/LazyFormattedEventArgs_Tests.cs b/src/Build.OM.UnitTests/LazyFormattedEventArgs_Tests.cs index 2940e3df2cf..870c497e175 100644 --- a/src/Build.OM.UnitTests/LazyFormattedEventArgs_Tests.cs +++ b/src/Build.OM.UnitTests/LazyFormattedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using Xunit; diff --git a/src/Build.OM.UnitTests/NugetRestoreTests.cs b/src/Build.OM.UnitTests/NugetRestoreTests.cs index daf8cbea8d0..e7458cf0a26 100644 --- a/src/Build.OM.UnitTests/NugetRestoreTests.cs +++ b/src/Build.OM.UnitTests/NugetRestoreTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if !DEBUG using Microsoft.Build.UnitTests; diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/TestCollectionGroup.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/TestCollectionGroup.cs index 83ce92e4d30..e8662ee46ec 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/TestCollectionGroup.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/TestCollectionGroup.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -230,7 +231,7 @@ public TestCollectionGroup(int remoteCount, int stdFilesCount) this.Disk = this.ImmutableDisk.GetSubFolder("Mutable"); List stdFiles = new List(); - for (int i=0; i< stdFilesCount; i++) + for (int i = 0; i < stdFilesCount; i++) { stdFiles.Add(this.ImmutableDisk.WriteProjectFile($"Proj{i}.proj", TestCollectionGroup.SampleProjectFile)); } @@ -253,7 +254,9 @@ private void Clear(ProjectCollectionLinker linker) foreach (var p in linker.Collection.LoadedProjects) { if (!toKeep.Contains(p)) + { toUnload.Add(p); + } } foreach (var p in toUnload) diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.construction.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.construction.cs index 100d0b6ae77..ef34a5876b9 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.construction.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.construction.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -73,7 +74,7 @@ public ElementLinkPair AddNewNamedChaildWithVerify(ObjectType where, str public ElementLinkPair AddNewLabeledChaildWithVerify(ObjectType where, string label, Func adder) where CT : ProjectElement => AddNewChaildWithVerify(where, label, - (t, l)=> + (t, l) => { var ct = adder(t, l); Assert.NotNull(ct); @@ -141,7 +142,7 @@ public ICollection> QueryChildrenWithValidation(Func> QueryChildrenWithValidation(Func getter, Func matcher) + public ICollection> QueryChildrenWithValidation(Func getter, Func matcher) where CT : ProjectElement { var viewResult = new List(); @@ -206,7 +207,7 @@ public ElementLinkPair QuerySingleChildrenWithValidation(Func { - ProjectPair Project { get; } + private ProjectPair Project { get; } public ProjectXmlPair(ProjectPair pair) : base(null, pair.View.Xml, pair.Real.Xml) { this.Project = pair; this.PRE = this; } public ProjectXmlPair(ProjectRootElement viewXml, ProjectRootElement realXml) : base(null, viewXml, realXml) { this.PRE = this; } @@ -246,7 +247,10 @@ public static void VerifySameLocationWithException(Func expecte public static void VerifySameLocation(ElementLocation expected, ElementLocation actual, ValidationContext context = null) { - if (object.ReferenceEquals(expected, actual)) return; + if (object.ReferenceEquals(expected, actual)) + { + return; + } if (context?.ValidateLocation != null) { @@ -267,10 +271,14 @@ public static bool IsLinkedObject(object obj) return LinkedObjectsFactory.GetLink(obj) != null; } - private static bool dbgIgnoreLinked = false; + private static bool dbgIgnoreLinked = false; public static void VerifyNotLinked(object obj) { - if (dbgIgnoreLinked) return; + if (dbgIgnoreLinked) + { + return; + } + Assert.True(obj == null || !IsLinkedObject(obj)); } @@ -278,8 +286,15 @@ public static void VerifyNotLinked(object obj) public static T GetRealObject(T view) where T : class { - if (view == null) return null; - if (!IsLinkedObject(view)) return view; + if (view == null) + { + return null; + } + + if (!IsLinkedObject(view)) + { + return view; + } var link = LinkedObjectsFactory.GetLink(view) as ILinkMock; Assert.NotNull(link); @@ -293,7 +308,11 @@ public static T GetRealObject(T view) public static void VerifyLinked(object obj) { - if (dbgIgnoreLinked) return; + if (dbgIgnoreLinked) + { + return; + } + Assert.True(obj == null || IsLinkedObject(obj)); } @@ -301,21 +320,33 @@ public static void VerifyLinked(object obj) public static void VerifyNotNull(object obj, bool linked) { Assert.NotNull(obj); - if (dbgIgnoreLinked) return; + if (dbgIgnoreLinked) + { + return; + } + Assert.Equal(linked, IsLinkedObject(obj)); } public static void VerifyNotLinkedNotNull(object obj) { Assert.NotNull(obj); - if (dbgIgnoreLinked) return; + if (dbgIgnoreLinked) + { + return; + } + Assert.True(!IsLinkedObject(obj)); } public static void VerifyLinkedNotNull(object obj) { Assert.NotNull(obj); - if (dbgIgnoreLinked) return; + if (dbgIgnoreLinked) + { + return; + } + Assert.True(IsLinkedObject(obj)); } @@ -344,7 +375,10 @@ public static void ValidateEqualWithException(Func viewGetter, Func rea private static void VerifyProjectElementViewInternal(ProjectElement viewXml, ProjectElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } VerifyLinkedNotNull(viewXml); VerifyNotLinkedNotNull(realXml); @@ -353,7 +387,7 @@ private static void VerifyProjectElementViewInternal(ProjectElement viewXml, Pro VerifySameLocation(realXml.LabelLocation, viewXml.LabelLocation, context); - VerifySameLocationWithException(()=>realXml.ConditionLocation, ()=>viewXml.ConditionLocation, context); + VerifySameLocationWithException(() => realXml.ConditionLocation, () => viewXml.ConditionLocation, context); VerifyNotLinked(realXml.ContainingProject); VerifyLinked(viewXml.ContainingProject); @@ -379,7 +413,11 @@ private static void VerifyProjectElementViewInternal(ProjectElement viewXml, Pro private static void VerifyProjectElementContainerView(ProjectElementContainer viewXml, ProjectElementContainer realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElementViewInternal(viewXml, realXml, context); Assert.Equal(realXml.Count, viewXml.Count); @@ -393,7 +431,7 @@ private static void VerifyProjectElementContainerView(ProjectElementContainer vi var realChild = realXml.FirstChild; var viewChild = viewXml.FirstChild; - while (realChild != null ) + while (realChild != null) { Assert.NotNull(viewChild); Assert.Same(realChild.Parent, realXml); @@ -458,7 +496,10 @@ public static void VerifyProjectCollectionLinks(IEnumerable projects, i public static void VerifyProjectElement(ProjectElement viewXml, ProjectElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } if (viewXml is ProjectElementContainer viewContainer) { @@ -474,7 +515,11 @@ public static void VerifyProjectElement(ProjectElement viewXml, ProjectElement r public static void Verify(ProjectRootElement viewXml, ProjectRootElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.FullPath, viewXml.FullPath); @@ -517,7 +562,11 @@ public static void Verify(ProjectRootElement viewXml, ProjectRootElement realXml public static void Verify(ProjectChooseElement viewXml, ProjectChooseElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); @@ -527,7 +576,11 @@ public static void Verify(ProjectChooseElement viewXml, ProjectChooseElement rea public static void Verify(ProjectWhenElement viewXml, ProjectWhenElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); @@ -538,7 +591,11 @@ public static void Verify(ProjectWhenElement viewXml, ProjectWhenElement realXml public static void Verify(ProjectOtherwiseElement viewXml, ProjectOtherwiseElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); @@ -549,7 +606,11 @@ public static void Verify(ProjectOtherwiseElement viewXml, ProjectOtherwiseEleme public static void Verify(ProjectExtensionsElement viewXml, ProjectExtensionsElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.Content, viewXml.Content); @@ -557,7 +618,11 @@ public static void Verify(ProjectExtensionsElement viewXml, ProjectExtensionsEle public static void Verify(ProjectMetadataElement viewXml, ProjectMetadataElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.Name, viewXml.Name); @@ -567,7 +632,11 @@ public static void Verify(ProjectMetadataElement viewXml, ProjectMetadataElement public static void Verify(ProjectTaskElement viewXml, ProjectTaskElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.Name, viewXml.Name); @@ -627,7 +696,11 @@ public static void Verify(ProjectTaskElement viewXml, ProjectTaskElement realXml public static void Verify(ProjectOutputElement viewXml, ProjectOutputElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.TaskParameter, viewXml.TaskParameter); @@ -641,7 +714,10 @@ public static void Verify(ProjectOutputElement viewXml, ProjectOutputElement rea public static void Verify(ProjectUsingTaskBodyElement viewXml, ProjectUsingTaskBodyElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } VerifyProjectElement(viewXml, realXml, context); @@ -652,7 +728,10 @@ public static void Verify(ProjectUsingTaskBodyElement viewXml, ProjectUsingTaskB public static void Verify(ProjectUsingTaskParameterElement viewXml, ProjectUsingTaskParameterElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } VerifyProjectElement(viewXml, realXml, context); @@ -667,7 +746,10 @@ public static void Verify(ProjectUsingTaskParameterElement viewXml, ProjectUsing public static void Verify(UsingTaskParameterGroupElement viewXml, UsingTaskParameterGroupElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } VerifyProjectElement(viewXml, realXml, context); @@ -676,7 +758,11 @@ public static void Verify(UsingTaskParameterGroupElement viewXml, UsingTaskParam public static void Verify(ProjectUsingTaskElement viewXml, ProjectUsingTaskElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); @@ -704,7 +790,11 @@ public static void Verify(ProjectUsingTaskElement viewXml, ProjectUsingTaskEleme public static void Verify(ProjectTargetElement viewXml, ProjectTargetElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); @@ -733,7 +823,11 @@ public static void Verify(ProjectTargetElement viewXml, ProjectTargetElement rea public static void Verify(ProjectImportElement viewXml, ProjectImportElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); @@ -752,7 +846,11 @@ public static void Verify(ProjectImportElement viewXml, ProjectImportElement rea public static void Verify(ProjectImportGroupElement viewXml, ProjectImportGroupElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); ViewValidation.Verify(viewXml.Imports, realXml.Imports, ViewValidation.Verify, context); @@ -760,7 +858,11 @@ public static void Verify(ProjectImportGroupElement viewXml, ProjectImportGroupE public static void Verify(ProjectItemDefinitionElement viewXml, ProjectItemDefinitionElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.ItemType, viewXml.ItemType); @@ -769,7 +871,11 @@ public static void Verify(ProjectItemDefinitionElement viewXml, ProjectItemDefin public static void Verify(ProjectItemDefinitionGroupElement viewXml, ProjectItemDefinitionGroupElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); ViewValidation.Verify(viewXml.ItemDefinitions, realXml.ItemDefinitions, ViewValidation.Verify, context); @@ -777,7 +883,11 @@ public static void Verify(ProjectItemDefinitionGroupElement viewXml, ProjectItem public static void Verify(ProjectItemElement viewXml, ProjectItemElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.ItemType, viewXml.ItemType); @@ -790,20 +900,24 @@ public static void Verify(ProjectItemElement viewXml, ProjectItemElement realXml Assert.Equal(realXml.KeepDuplicates, viewXml.KeepDuplicates); Assert.Equal(realXml.HasMetadata, viewXml.HasMetadata); - Verify(viewXml.Metadata, realXml.Metadata, ViewValidation.Verify, context); + Verify(viewXml.Metadata, realXml.Metadata, ViewValidation.Verify, context); - VerifySameLocation(realXml.IncludeLocation, viewXml.IncludeLocation, context); - VerifySameLocation(realXml.ExcludeLocation, viewXml.ExcludeLocation, context); - VerifySameLocation(realXml.RemoveLocation, viewXml.RemoveLocation, context); - VerifySameLocation(realXml.UpdateLocation, viewXml.UpdateLocation, context); - VerifySameLocation(realXml.KeepMetadataLocation, viewXml.KeepMetadataLocation, context); - VerifySameLocation(realXml.RemoveMetadataLocation, viewXml.RemoveMetadataLocation, context); - VerifySameLocation(realXml.KeepDuplicatesLocation, viewXml.KeepDuplicatesLocation, context); + VerifySameLocation(realXml.IncludeLocation, viewXml.IncludeLocation, context); + VerifySameLocation(realXml.ExcludeLocation, viewXml.ExcludeLocation, context); + VerifySameLocation(realXml.RemoveLocation, viewXml.RemoveLocation, context); + VerifySameLocation(realXml.UpdateLocation, viewXml.UpdateLocation, context); + VerifySameLocation(realXml.KeepMetadataLocation, viewXml.KeepMetadataLocation, context); + VerifySameLocation(realXml.RemoveMetadataLocation, viewXml.RemoveMetadataLocation, context); + VerifySameLocation(realXml.KeepDuplicatesLocation, viewXml.KeepDuplicatesLocation, context); } public static void Verify(ProjectItemGroupElement viewXml, ProjectItemGroupElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Verify(viewXml.Items, realXml.Items, Verify, context); @@ -811,7 +925,11 @@ public static void Verify(ProjectItemGroupElement viewXml, ProjectItemGroupEleme public static void Verify(ProjectPropertyElement viewXml, ProjectPropertyElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.Name, viewXml.Name); @@ -820,7 +938,11 @@ public static void Verify(ProjectPropertyElement viewXml, ProjectPropertyElement public static void Verify(ProjectPropertyGroupElement viewXml, ProjectPropertyGroupElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Verify(viewXml.Properties, realXml.Properties, Verify, context); Verify(viewXml.PropertiesReversed, realXml.PropertiesReversed, Verify, context); @@ -828,7 +950,11 @@ public static void Verify(ProjectPropertyGroupElement viewXml, ProjectPropertyGr public static void Verify(ProjectSdkElement viewXml, ProjectSdkElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.Name, viewXml.Name); Assert.Equal(realXml.Version, viewXml.Version); @@ -837,7 +963,11 @@ public static void Verify(ProjectSdkElement viewXml, ProjectSdkElement realXml, public static void Verify(ProjectOnErrorElement viewXml, ProjectOnErrorElement realXml, ValidationContext context = null) { - if (viewXml == null && realXml == null) return; + if (viewXml == null && realXml == null) + { + return; + } + VerifyProjectElement(viewXml, realXml, context); Assert.Equal(realXml.ExecuteTargetsAttribute, viewXml.ExecuteTargetsAttribute); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.cs index 4e1161c32ab..0545ad97ba8 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -121,48 +122,165 @@ private static bool VerifyCheckType(object view, object real, ValidationConte // "Slow" Verify, probing all known link types public static void VerifyFindType(object view, object real, ValidationContext context = null) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + VerifyLinkedNotNull(view); VerifyNotLinkedNotNull(real); // construction - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } // evaluation - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; - if (VerifyCheckType(view, real, context, Verify)) return; + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } + + if (VerifyCheckType(view, real, context, Verify)) + { + return; + } throw new NotImplementedException($"Unknown type:{view.GetType().Name}"); } public static void VerifyMetadata(IEnumerable> expected, Func getMetadata, Func hasMetadata = null) { - if (expected == null) return; + if (expected == null) + { + return; + } foreach (var md in expected) { @@ -177,7 +295,11 @@ public static void VerifyMetadata(IEnumerable> expe public static void Verify(IEnumerable viewCollection, IEnumerable realCollection, Action validator, ValidationContext context = null) { - if (viewCollection == null && realCollection == null) return; + if (viewCollection == null && realCollection == null) + { + return; + } + Assert.NotNull(viewCollection); Assert.NotNull(realCollection); @@ -192,7 +314,11 @@ public static void Verify(IEnumerable viewCollection, IEnumerable realC public static void Verify(IDictionary viewCollection, IDictionary realCollection, Action validator, ValidationContext context = null) { - if (viewCollection == null && realCollection == null) return; + if (viewCollection == null && realCollection == null) + { + return; + } + Assert.NotNull(viewCollection); Assert.NotNull(realCollection); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.evaluation.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.evaluation.cs index ea46c70faa3..09505be2280 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.evaluation.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/Helpers/ViewValidation.evaluation.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -68,7 +69,11 @@ public ProjectItem GetSingleItemWithVerify(ObjectType which, string evaluatedInc var viewItems = this.View.GetItemsByEvaluatedInclude(evaluatedInclude); ViewValidation.Verify(viewItems, realItems, ViewValidation.Verify, new ValidationContext(this)); - if (viewItems == null || viewItems.Count == 0) return null; + if (viewItems == null || viewItems.Count == 0) + { + return null; + } + Assert.Equal(1, viewItems.Count); return which == ObjectType.View ? viewItems.First() : realItems.First(); } @@ -93,7 +98,11 @@ internal static partial class ViewValidation { public static void Verify(ProjectProperty view, ProjectProperty real, ValidationContext context) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + VerifyLinkedNotNull(view); VerifyNotLinkedNotNull(real); @@ -121,7 +130,11 @@ public static void Verify(ProjectProperty view, ProjectProperty real, Validation // public static void Verify(ProjectMetadata view, ProjectMetadata real) => Verify(view, real, null); public static void Verify(ProjectMetadata view, ProjectMetadata real, ValidationContext context) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + VerifyLinkedNotNull(view); VerifyNotLinkedNotNull(real); @@ -150,7 +163,11 @@ public static void Verify(ProjectMetadata view, ProjectMetadata real, Validation // public static void Verify(ProjectItemDefinition view, ProjectItemDefinition real) => Verify(view, real, null); public static void Verify(ProjectItemDefinition view, ProjectItemDefinition real, ValidationContext context) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + VerifyLinkedNotNull(view); VerifyNotLinkedNotNull(real); @@ -188,7 +205,11 @@ public static void Verify(ProjectItemDefinition view, ProjectItemDefinition real // public static void Verify(ProjectItem view, ProjectItem real) => Verify(view, real, null); public static void Verify(ProjectItem view, ProjectItem real, ValidationContext context = null) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + VerifyLinkedNotNull(view); VerifyNotLinkedNotNull(real); @@ -234,7 +255,11 @@ public static void Verify(ProjectItem view, ProjectItem real, ValidationContext private static void Verify(SdkReference view, SdkReference real, ValidationContext context = null) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + Assert.NotNull(view); Assert.NotNull(real); @@ -245,7 +270,11 @@ private static void Verify(SdkReference view, SdkReference real, ValidationConte private static void Verify(SdkResult view, SdkResult real, ValidationContext context = null) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + Assert.NotNull(view); Assert.NotNull(real); Assert.Equal(real.Success, view.Success); @@ -263,12 +292,16 @@ private static void Verify(ResolvedImport view, ResolvedImport real, ValidationC private static void Verify(List viewProps, List realProps, ValidationContext context = null) { - if (viewProps == null && realProps == null) return; + if (viewProps == null && realProps == null) + { + return; + } + Assert.NotNull(viewProps); Assert.NotNull(realProps); Assert.Equal(realProps.Count, viewProps.Count); - for (int i = 0; i< realProps.Count; i++) + for (int i = 0; i < realProps.Count; i++) { Assert.Equal(realProps[i], viewProps[i]); } @@ -276,14 +309,22 @@ private static void Verify(List viewProps, List realProps, Valid public static void Verify(Project view, Project real, ValidationContext context = null) { - if (view == null && real == null) return; + if (view == null && real == null) + { + return; + } + var pair = new ProjectPair(view, real); Verify(pair, context); } public static void Verify(ProjectPair pair, ValidationContext context = null) { - if (pair == null) return; + if (pair == null) + { + return; + } + var real = pair.Real; var view = pair.View; context ??= new ValidationContext(); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionModify_Tests.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionModify_Tests.cs index 2489f2b4687..5edad4f2699 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionModify_Tests.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionModify_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -159,7 +160,7 @@ public void ProjectTargetElementModify() newTarget1.Add2NewLabeledChildrenWithVerify(NewPropertyGroup, (t, l) => t.AddPropertyGroup(), out var newPropertyGroup1, out var newPropertyGroup2); // Add property groups - newTarget1.Append2NewChildrenWithVerify("errTarget", (p, et) => p.CreateOnErrorElement(et), (oe, et)=>oe.ExecuteTargetsAttribute == et, out var newOnErr1, out var newOnErr2); + newTarget1.Append2NewChildrenWithVerify("errTarget", (p, et) => p.CreateOnErrorElement(et), (oe, et) => oe.ExecuteTargetsAttribute == et, out var newOnErr1, out var newOnErr2); // string setters @@ -193,7 +194,7 @@ public void ProjectTargetElementModify() // removes newTarget1.View.RemoveChild(newTask2.View); - Assert.ThrowsAny( () => newTarget1.Real.RemoveChild(newTask2.Real) ); + Assert.ThrowsAny(() => newTarget1.Real.RemoveChild(newTask2.Real)); Assert.Equal(1, newTarget1.View.Tasks.Count); newTarget1.Real.RemoveChild(newTask1.Real); Assert.ThrowsAny(() => newTarget1.View.RemoveChild(newTask1.View)); @@ -264,9 +265,9 @@ public void ProjectTaskElementModify() newTask.VerifySetter(paramValue.Ver(i), (t) => t.GetParameter(paramName.Ver(i)), (t, v) => t.SetParameter(paramName.Ver(i), v)); } - newTask.Verify(); + newTask.Verify(); Assert.Equal(5, newTask.View.Parameters.Count); - for (int i = 1; i<= 5; i++) + for (int i = 1; i <= 5; i++) { Assert.Equal(paramValue.Ver(i), newTask.View.Parameters[paramName.Ver(i)]); } @@ -320,7 +321,7 @@ public void ProjectOutputElementModify() const string NewOutputItem = "NewOutputItem"; const string ItemType = "CPPSource"; - var newOutputItem = newTask.AddNewChaildWithVerify(ObjectType.View, NewOutputItem, (t, n) => t.AddOutputItem(n, ItemType), (oi, n) => oi.TaskParameter == n); + var newOutputItem = newTask.AddNewChaildWithVerify(ObjectType.View, NewOutputItem, (t, n) => t.AddOutputItem(n, ItemType), (oi, n) => oi.TaskParameter == n); Assert.True(newOutputItem.View.IsOutputItem); Assert.False(newOutputItem.View.IsOutputProperty); @@ -387,7 +388,7 @@ public void ProjectChooseElementModify() Assert.Null(choose.View.OtherwiseElement); - var otherWise = choose.AppendNewChaildWithVerify(ObjectType.View, "when", (p, l) => p.CreateOtherwiseElement(), (p,l) => true); + var otherWise = choose.AppendNewChaildWithVerify(ObjectType.View, "when", (p, l) => p.CreateOtherwiseElement(), (p, l) => true); Assert.Same(otherWise.View, choose.View.OtherwiseElement); Assert.Same(otherWise.Real, choose.Real.OtherwiseElement); @@ -410,7 +411,7 @@ public void ProjectWhenElementModify() var xmlPair = new ProjectXmlPair(pair); var choose = xmlPair.AppendNewChaildWithVerify(ObjectType.View, "choose", (p, s) => p.CreateChooseElement(), (p, s) => true); - var when = choose.AppendNewChaildWithVerify(ObjectType.View, "when", (p, s) => p.CreateWhenElement("true"), (p, s) => true); + var when = choose.AppendNewChaildWithVerify(ObjectType.View, "when", (p, s) => p.CreateWhenElement("true"), (p, s) => true); when.VerifySetter("Condition", (we) => we.Condition, (we, v) => we.Condition = v); Assert.Empty(when.View.ChooseElements); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionReadOnly_Tests.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionReadOnly_Tests.cs index 5c53201c0d8..7a2cb811fe0 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionReadOnly_Tests.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedConstructionReadOnly_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -71,7 +71,7 @@ public void ProjectRootElemetReadOnly() ViewValidation.Verify(preView, preReal); } - + [Fact] public void ProjectChooseElementReadOnly() { diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationModify_Tests.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationModify_Tests.cs index d0f1b2125c9..dd887f0ca16 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationModify_Tests.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationModify_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -215,7 +216,7 @@ public void ProjectItemModify() var fooRealFast = pair.GetSingleItemWithVerify(ObjectType.Real, "fooFast.cpp"); Assert.NotNull(fooRealFast); ViewValidation.Verify(fooViewFast, fooRealFast, validationContext); - var toRemoveReal = new List() { fooRealFast, barRealFast}; + var toRemoveReal = new List() { fooRealFast, barRealFast }; Assert.Throws(() => { diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationReadOnly_Tests.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationReadOnly_Tests.cs index 5197936d9e4..37578322323 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationReadOnly_Tests.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedEvaluationReadOnly_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedProjectCollection_Tests.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedProjectCollection_Tests.cs index 89447997df1..c0dc256c99f 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedProjectCollection_Tests.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedProjectCollection_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting @@ -29,7 +30,7 @@ public void EnumerationBasic() var pcRemote = this.StdGroup.Remote[0]; var proj1Path = this.StdGroup.StdProjectFiles[0]; - var proj2Path = this.StdGroup.StdProjectFiles[1]; + var proj2Path = this.StdGroup.StdProjectFiles[1]; var proj1 = pcLocal.LoadProject(proj1Path); var proj2 = pcRemote.LoadProject(proj2Path); @@ -106,7 +107,7 @@ public void EnumerationMultiple() Assert.Equal(2, prj2Coll.Count); Assert.False(prj2Coll.Contains(proj2remote0)); Assert.False(prj2Coll.Contains(proj2remote1)); - foreach(var p in prj2Coll) + foreach (var p in prj2Coll) { ViewValidation.VerifyLinkedNotNull(p); } diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedSpecialCasesScenarios.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedSpecialCasesScenarios.cs index 62dba852a43..d9d8a7fc9e4 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedSpecialCasesScenarios.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/LinkedSpecialCasesScenarios.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #nullable disable namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/CollectionsHelpers.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/CollectionsHelpers.cs index ea551d51ac1..1e525aae9fe 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/CollectionsHelpers.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/CollectionsHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -9,11 +9,14 @@ namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting using System.Collections.Generic; using Microsoft.Build.Construction; - static class CollectionHelpers + internal static class CollectionHelpers { - public static IList ConvertCollection(this IEnumerable source, Func converter) + public static IList ConvertCollection(this IEnumerable source, Func converter) { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... List result = new List(); foreach (var b in source) @@ -27,7 +30,10 @@ public static IList ConvertCollection(this IEnumerable source, Func ImportCollection(this ProjectCollectionLinker importer, IEnumerable source) where T : ProjectElement { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... List result = new List(); foreach (var sRemoter in source) @@ -43,7 +49,10 @@ public static IList ImportCollection(this ProjectCollectionLinker i where T : class where RMock : MockLinkRemoter, new() { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... List result = new List(); foreach (var sRemoter in source) @@ -58,7 +67,10 @@ public static IList ImportCollection(this ProjectCollectionLinker i public static IList ExportCollection(this ProjectCollectionLinker exporter, IEnumerable source) where T : ProjectElement { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... List result = new List(); foreach (var s in source) @@ -73,7 +85,10 @@ public static IList ExportCollection(this ProjectCollectionLink where T : class where RMock : MockLinkRemoter, new() { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... List result = new List(); foreach (var s in source) @@ -89,7 +104,10 @@ public static IDictionary ImportDictionary(th where TValue : class where RMock : MockLinkRemoter, new() { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... Dictionary result = new Dictionary(); foreach (var sRemoter in source) @@ -105,7 +123,10 @@ public static IDictionary ExportDictionary(thi where TValue : class where RMock : MockLinkRemoter, new() { - if (source == null) return null; + if (source == null) + { + return null; + } // Just copy ... Dictionary result = new Dictionary(); foreach (var s in source) diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/InheritanceImplementationHelpers.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/InheritanceImplementationHelpers.cs index 2dff6a546e7..075a0af11ec 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/InheritanceImplementationHelpers.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/InheritanceImplementationHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -167,7 +167,7 @@ public static ProjectElementContainer DeepClone(this IProjectElementContainerLin { var factoryRemote = xml.Linker.Export(factory); var parentRemote = (MockProjectElementContainerLinkRemoter)xml.Linker.ExportElement(parent); - var result = xml.ContainerProxy.DeepClone(factoryRemote, parentRemote); + var result = xml.ContainerProxy.DeepClone(factoryRemote, parentRemote); return (ProjectElementContainer)result.Import(xml.Linker); } diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectChooseElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectChooseElementLink.cs index cd95fc66b3a..4d2a3fa0dde 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectChooseElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectChooseElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementContainerLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementContainerLink.cs index e4754f60d2c..4649ce117d8 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementContainerLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementContainerLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementLink.cs index 40ee91d732b..ef223917f02 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectExtensionsElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectExtensionsElementLink.cs index f4dadff9519..54e3281620d 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectExtensionsElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectExtensionsElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportElementLink.cs index 590b4f9dfe0..c5fa1a839c3 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportGroupElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportGroupElementLink.cs index 98fe38f3e28..91183160a77 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportGroupElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectImportGroupElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionElementLink.cs index 2ebcdf29e14..1fa22919a85 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionGroupElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionGroupElementLink.cs index 324de0cd4ad..4db3a3887c6 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionGroupElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemDefinitionGroupElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemElementLink.cs index 387636a661a..b3e6082cfa6 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemGroupElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemGroupElementLink.cs index 40c67b66ae4..2a2cd60b8fd 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemGroupElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectItemGroupElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectMetadataElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectMetadataElementLink.cs index d4201a0e566..c1c4104e896 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectMetadataElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectMetadataElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOnErrorElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOnErrorElementLink.cs index 670037f8ab9..2e2f270b6bd 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOnErrorElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOnErrorElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOtherwiseElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOtherwiseElementLink.cs index cf9ed5cfc73..f505ff63bfc 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOtherwiseElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOtherwiseElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOutputElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOutputElementLink.cs index e92c8bada54..6614aefb505 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOutputElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectOutputElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyElementLink.cs index 171e9537b91..2ec4b700504 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyGroupElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyGroupElementLink.cs index aa4aa21be26..12145a4d3cf 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyGroupElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectPropertyGroupElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectRootElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectRootElementLink.cs index 6b9da4a89be..a42fa6bf257 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectRootElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectRootElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -15,7 +15,7 @@ namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting internal class MockProjectRootElementLinkRemoter : MockProjectElementContainerLinkRemoter { - ProjectRootElement ProjectXml => (ProjectRootElement)Source; + private ProjectRootElement ProjectXml => (ProjectRootElement)Source; public override ProjectElement CreateLinkedObject(IImportHolder holder) { @@ -53,7 +53,7 @@ public MockProjectItemElementLinkRemoter CreateItemElement(string itemType) } public MockProjectItemElementLinkRemoter CreateItemElement(string itemType, string include) { - return (MockProjectItemElementLinkRemoter) this.Export(this.ProjectXml.CreateItemElement(itemType, include)); + return (MockProjectItemElementLinkRemoter)this.Export(this.ProjectXml.CreateItemElement(itemType, include)); } public MockProjectItemDefinitionElementLinkRemoter CreateItemDefinitionElement(string itemType) { diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectSdkElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectSdkElementLink.cs index e388f98a799..04c02eae76c 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectSdkElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectSdkElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTargetElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTargetElementLink.cs index 5f167256223..e4c86708942 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTargetElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTargetElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTaskElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTaskElementLink.cs index 0270ebd93f1..e269c88d187 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTaskElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectTaskElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -59,7 +59,7 @@ public MockProjectTaskElementLink(MockProjectTaskElementLinkRemoter proxy, IImpo public override IEnumerable> ParameterLocations => this.Proxy.ParameterLocations; public override string GetParameter(string name) { return this.Proxy.GetParameter(name); } // hmm did not know can use => on functions, can clean the milion other cases some tiem ... - public override void SetParameter(string name, string unevaluatedValue) => this.Proxy.SetParameter(name, unevaluatedValue); + public override void SetParameter(string name, string unevaluatedValue) => this.Proxy.SetParameter(name, unevaluatedValue); public override void RemoveParameter(string name) => Proxy.RemoveParameter(name); public override void RemoveAllParameters() => Proxy.RemoveAllParameters(); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskBodyElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskBodyElementLink.cs index 738ae4b419f..096dfd6bbea 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskBodyElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskBodyElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -68,7 +68,7 @@ public MockProjectUsingTaskBodyElementLink(MockProjectUsingTaskBodyElementLinkRe namespace Microsoft.Build.Engine.OM.UnitTests.ObjectModelRemoting.RemoteProjectsProviderMock.ConstructionLinkMocks { - class MockProjectUsingTaskBodyElementLink + internal class MockProjectUsingTaskBodyElementLink { } } diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskElementLink.cs index 6c712d6a783..bbdf492a173 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskParameterElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskParameterElementLink.cs index 4a2ea57fc08..91d70d33982 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskParameterElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectUsingTaskParameterElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -40,7 +40,7 @@ public MockProjectUsingTaskParameterElementLink(MockProjectUsingTaskParameterEle object ILinkMock.Remoter => this.Proxy; MockProjectElementLinkRemoter IProjectElementLinkHelper.ElementProxy => this.Proxy; - public override string Name { get => Proxy.Name; set =>Proxy.Name = value; } + public override string Name { get => Proxy.Name; set => Proxy.Name = value; } #region ProjectElementLink redirectors private IProjectElementLinkHelper EImpl => (IProjectElementLinkHelper)this; public override ProjectElementContainer Parent => EImpl.GetParent(); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectWhenElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectWhenElementLink.cs index eab1585dd0b..921a0a367e8 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectWhenElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockProjectWhenElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockUsingTaskParameterGroupElementLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockUsingTaskParameterGroupElementLink.cs index 7756a107763..3a020455530 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockUsingTaskParameterGroupElementLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/MockUsingTaskParameterGroupElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/ProjectElemetExportHelper.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/ProjectElemetExportHelper.cs index 6fba5806135..daa32209fe2 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/ProjectElemetExportHelper.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/ProjectElemetExportHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -18,7 +18,7 @@ namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting /// internal static class ProjectElemetExportHelper { - delegate MockProjectElementLinkRemoter ExporterFactory(ProjectCollectionLinker exporter, ProjectElement xml); + private delegate MockProjectElementLinkRemoter ExporterFactory(ProjectCollectionLinker exporter, ProjectElement xml); private class ElementInfo { public static ElementInfo New() diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/DirectlyRemotedClasses.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/DirectlyRemotedClasses.cs index d09294c9ada..85dd231427c 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/DirectlyRemotedClasses.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/DirectlyRemotedClasses.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -41,7 +41,7 @@ public RemotedResolvedImport(ResolvedImport resolvedImport, ProjectCollectionLin public bool IsImported { get; } - ResolvedImport Import(ProjectCollectionLinker importer) + private ResolvedImport Import(ProjectCollectionLinker importer) { var importElement = (ProjectImportElement)importer.Import(this.ImportingElement); var projectElement = (ProjectRootElement)importer.Import(this.ImportedProject); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemDefinitionLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemDefinitionLink.cs index ae0dcaa1d05..e2c9738fde6 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemDefinitionLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemDefinitionLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemLink.cs index d9fc77084ea..5012822e461 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectItemLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectLink.cs index 2eaf1a6fa6f..abb23669f25 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -79,7 +79,7 @@ public IList AddItemFast(string itemType, string une public ICollection GetItems(string itemType) => this.OwningCollection.ExportCollection(this.Source.GetItems(itemType)); - public ICollection GetItemsByEvaluatedInclude(string evaluatedInclude) + public ICollection GetItemsByEvaluatedInclude(string evaluatedInclude) => this.OwningCollection.ExportCollection(this.Source.GetItemsByEvaluatedInclude(evaluatedInclude)); public ICollection GetItemsIgnoringCondition(string itemType) @@ -89,7 +89,7 @@ public IEnumerable GetLogicalProject() => this.OwningCollection.ExportCollection(this.Source.GetLogicalProject()); public MockProjectPropertyLinkRemoter GetProperty(string name) => this.OwningCollection.Export(this.Source.GetProperty(name)); - public string GetPropertyValue(string name) => this.Source.GetPropertyValue(name); + public string GetPropertyValue(string name) => this.Source.GetPropertyValue(name); public void MarkDirty() => this.Source.MarkDirty(); public void ReevaluateIfNecessary(EvaluationContext evaluationContext) => this.Source.ReevaluateIfNecessary(evaluationContext); public bool RemoveGlobalProperty(string name) => this.Source.RemoveGlobalProperty(name); @@ -107,9 +107,9 @@ public void SaveLogicalProject(TextWriter writer) this.Source.SaveLogicalProject(writer); } - public bool SetGlobalProperty(string name, string escapedValue) => this.Source.SetGlobalProperty(name, escapedValue); + public bool SetGlobalProperty(string name, string escapedValue) => this.Source.SetGlobalProperty(name, escapedValue); - public MockProjectPropertyLinkRemoter SetProperty(string name, string unevaluatedValue) + public MockProjectPropertyLinkRemoter SetProperty(string name, string unevaluatedValue) => this.OwningCollection.Export(this.Source.SetProperty(name, unevaluatedValue)); public void Unload() { } } @@ -138,7 +138,7 @@ public MockProjectLink(MockProjectLinkRemoter proxy, IImportHolder holder) public override ICollection ItemTypes => this.Proxy.ItemTypes; - public override ICollection Properties => this.Linker.ImportCollection(this.Proxy.Properties); + public override ICollection Properties => this.Linker.ImportCollection(this.Proxy.Properties); public override IDictionary> ConditionedProperties => this.Proxy.ConditionedProperties; @@ -184,7 +184,7 @@ public override bool Build(string[] targets, IEnumerable loggers, IEnum => throw new NotImplementedException(); public override ProjectInstance CreateProjectInstance(ProjectInstanceSettings settings, EvaluationContext evaluationContext) => throw new NotImplementedException(); public override IDictionary Targets => throw new NotImplementedException(); -// -------------------------------------------------- + // -------------------------------------------------- public override string ExpandString(string unexpandedValue) => this.Proxy.ExpandString(unexpandedValue); @@ -212,7 +212,7 @@ public override List GetItemProvenance(ProjectItem item, Evalu { throw new NotImplementedException(); } -// --------------------------------------------------------------------------------------- + // --------------------------------------------------------------------------------------- public override ICollection GetItems(string itemType) => this.Linker.ImportCollection(this.Proxy.GetItems(itemType)); diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectMetadataLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectMetadataLink.cs index 1399fb28746..0b5ae0d6dfd 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectMetadataLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectMetadataLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -23,7 +23,11 @@ public object Parent get { var parent = ProjectMetadataLink.GetParent(this.Source); - if (parent == null) return null; + if (parent == null) + { + return null; + } + var itemParent = parent as ProjectItem; if (itemParent != null) { @@ -58,7 +62,11 @@ public override object Parent get { var parentRemoter = this.Proxy.Parent; - if (parentRemoter == null) return null; + if (parentRemoter == null) + { + return null; + } + var itemParent = parentRemoter as MockProjectItemLinkRemoter; if (itemParent != null) { diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectPropertyLink.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectPropertyLink.cs index cea7656b893..aa838bc26ea 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectPropertyLink.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/EvaluationLinkMocks/MockProjectPropertyLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -22,7 +22,7 @@ public override ProjectProperty CreateLinkedObject(IImportHolder holder) public MockProjectPropertyElementLinkRemoter Xml => (MockProjectPropertyElementLinkRemoter)this.ExportElement(this.Source.Xml); public string Name => this.Source.Name; public string EvaluatedIncludeEscaped => ProjectPropertyLink.GetEvaluatedValueEscaped(this.Source); - public string UnevaluatedValue { get => this.Source.UnevaluatedValue; set=> this.Source.UnevaluatedValue = value; } + public string UnevaluatedValue { get => this.Source.UnevaluatedValue; set => this.Source.UnevaluatedValue = value; } public bool IsEnvironmentProperty => this.Source.IsEnvironmentProperty; public bool IsGlobalProperty => this.Source.IsGlobalProperty; public bool IsReservedProperty => this.Source.IsReservedProperty; diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ExporterMock.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ExporterMock.cs index 1b7e3b67aee..a76b6b88a0a 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ExporterMock.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ExporterMock.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -154,12 +154,12 @@ internal class ProjectCollectionLinker : ExternalProjectsProvider private ProjectCollectionLinker(ConnectedProjectCollections group) { this.LinkedCollections = group; - this.CollectionId = (UInt32) Interlocked.Increment(ref _collecitonId); + this.CollectionId = (UInt32)Interlocked.Increment(ref _collecitonId); this.Collection = new ProjectCollection(); this.LinkFactory = LinkedObjectsFactory.Get(this.Collection); } - public Project LoadProject(string path) => this.Collection.LoadProject(path); + public Project LoadProject(string path) => this.Collection.LoadProject(path); public Project LoadProjectIgnoreMissingImports(string path) => LoadProjectWithSettings(path, ProjectLoadSettings.IgnoreMissingImports); public Project LoadProjectWithSettings(string path, ProjectLoadSettings settings) => new Project(path, null, null, this.Collection, settings); @@ -193,7 +193,7 @@ public bool Importing } } - private void ConnectTo (ProjectCollectionLinker other) + private void ConnectTo(ProjectCollectionLinker other) { if (other.CollectionId == this.CollectionId) { @@ -219,7 +219,7 @@ private void ConnectTo (ProjectCollectionLinker other) private static bool dbgValidateDuplicateViews = false; - internal void ValidateNoDuplicates() + internal void ValidateNoDuplicates() { foreach (var r in imported) { @@ -329,7 +329,7 @@ public void Export(T obj, out RMock remoter) { var proxy = (ILinkMock)external; - remoter = (RMock) proxy.Remoter; + remoter = (RMock)proxy.Remoter; return; } diff --git a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/LinkedObjectsMap.cs b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/LinkedObjectsMap.cs index da3a45fc598..e9716a0d517 100644 --- a/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/LinkedObjectsMap.cs +++ b/src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/LinkedObjectsMap.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -126,7 +126,7 @@ private LinkedObjectsMap(UInt32 id) } private UInt32 CollectionId { get; set; } - public static LinkedObjectsMap Create() + public static LinkedObjectsMap Create() { lock (Lock) { diff --git a/src/Build.OM.UnitTests/TransientIO.cs b/src/Build.OM.UnitTests/TransientIO.cs index 982474d02ea..2bf038c227c 100644 --- a/src/Build.OM.UnitTests/TransientIO.cs +++ b/src/Build.OM.UnitTests/TransientIO.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -24,8 +24,7 @@ private DirectoryInfo EnsureTempRoot() this.root = new DirectoryInfo( this.Parent != null ? this.Parent.GetAbsolutePath(this.SubFolder) - : FileUtilities.GetTemporaryDirectory(true) - ); + : FileUtilities.GetTemporaryDirectory(true)); } return this.root; @@ -45,7 +44,11 @@ private TransientIO(TransientIO parent, string subFolder) public bool IsControled(string path) { - if (this.root == null || path == null) return false; + if (this.root == null || path == null) + { + return false; + } + var tempRoot = this.RootFolder; path = Path.GetFullPath(path); return path != null && tempRoot != null @@ -90,7 +93,7 @@ public TransientIO GetSubFolder(string path) var subFolder = this.GetRelativePath(path); if (!this.Children.TryGetValue(subFolder, out var result)) { - result = new TransientIO(this, subFolder); + result = new TransientIO(this, subFolder); this.Children.Add(subFolder, result); } diff --git a/src/Build.UnitTests/AssemblyInfo.cs b/src/Build.UnitTests/AssemblyInfo.cs index 7f6f30fcef9..3b5d7bbb185 100644 --- a/src/Build.UnitTests/AssemblyInfo.cs +++ b/src/Build.UnitTests/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Build.UnitTests/BackEnd/AssemblyLoadContextTestTasks.cs b/src/Build.UnitTests/BackEnd/AssemblyLoadContextTestTasks.cs index 3b1628e1def..b11055c16c5 100644 --- a/src/Build.UnitTests/BackEnd/AssemblyLoadContextTestTasks.cs +++ b/src/Build.UnitTests/BackEnd/AssemblyLoadContextTestTasks.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs index c9266d1c53f..8ce02b04836 100644 --- a/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/AssemblyTaskFactory_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -57,8 +57,7 @@ public void NullLoadInfo() { AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); taskFactory.InitializeFactory(null, "TaskToTestFactories", new Dictionary(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty); - } - ); + }); } /// /// Make sure we get an invalid project file exception when a null task name is passed to the factory @@ -70,8 +69,7 @@ public void NullTaskName() { AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); taskFactory.InitializeFactory(_loadInfo, null, new Dictionary(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty); - } - ); + }); } /// /// Make sure we get an invalid project file exception when an empty task name is passed to the factory @@ -83,8 +81,7 @@ public void EmptyTaskName() { AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); taskFactory.InitializeFactory(_loadInfo, String.Empty, new Dictionary(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty); - } - ); + }); } /// /// Make sure we get an invalid project file exception when the task is not in the info @@ -96,8 +93,7 @@ public void GoodTaskNameButNotInInfo() { AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); taskFactory.InitializeFactory(_loadInfo, "RandomTask", new Dictionary(), string.Empty, null, false, null, ElementLocation.Create("NONE"), String.Empty); - } - ); + }); } /// /// Make sure we get an internal error when we call the initialize factory on the public method. @@ -111,8 +107,7 @@ public void CallPublicInitializeFactory() { AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); taskFactory.Initialize(String.Empty, new Dictionary(), String.Empty, null); - } - ); + }); } /// /// Make sure we get an internal error when we call the ITaskFactory2 version of initialize factory. @@ -126,8 +121,7 @@ public void CallPublicInitializeFactory2() { AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); taskFactory.Initialize(String.Empty, null, new Dictionary(), String.Empty, null); - } - ); + }); } #endregion @@ -158,8 +152,7 @@ public void CreatableByTaskFactoryNotInAssemblyEmptyTaskName() Assert.Throws(() => { Assert.False(_taskFactory.TaskNameCreatableByFactory(String.Empty, null, String.Empty, null, ElementLocation.Create(".", 1, 1))); - } - ); + }); } /// /// Expect a false answer when we ask for a task which is not in the factory. @@ -170,8 +163,7 @@ public void CreatableByTaskFactoryNullTaskName() Assert.Throws(() => { Assert.False(_taskFactory.TaskNameCreatableByFactory(null, null, String.Empty, null, ElementLocation.Create(".", 1, 1))); - } - ); + }); } /// /// Make sure that when an explicitly matching identity is specified (e.g. the identity is non-empty), diff --git a/src/Build.UnitTests/BackEnd/BatchingEngine_Tests.cs b/src/Build.UnitTests/BackEnd/BatchingEngine_Tests.cs index e2602d1f7bd..c47157d44fb 100644 --- a/src/Build.UnitTests/BackEnd/BatchingEngine_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BatchingEngine_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -166,8 +166,7 @@ public void InvalidUnqualifiedMetadataReference() // This is expected to throw because not all items contain a value for metadata "Culture". // Only a.foo has a Culture metadata. b.foo does not. BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance); - } - ); + }); } /// /// Tests the case where an unqualified metadata reference is used illegally. @@ -188,8 +187,7 @@ public void NoItemsConsumed() // This is expected to throw because we have no idea what item list %(Culture) refers to. BatchingEngine.PrepareBatchingBuckets(parameters, CreateLookup(itemsByType, properties), MockElementLocation.Instance); - } - ); + }); } /// /// Missing unittest found by mutation testing. diff --git a/src/Build.UnitTests/BackEnd/BinaryTranslator_Tests.cs b/src/Build.UnitTests/BackEnd/BinaryTranslator_Tests.cs index c0d9aa78bbc..528e53b0285 100644 --- a/src/Build.UnitTests/BackEnd/BinaryTranslator_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BinaryTranslator_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -550,7 +550,7 @@ public void AssemblyNameWithAllFields() ContentType = AssemblyContentType.WindowsRuntime, CultureName = "zh-HK", }; - value.SetPublicKey(new byte[]{ 3, 2, 1}); + value.SetPublicKey(new byte[] { 3, 2, 1 }); value.SetPublicKeyToken(new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }); TranslationHelpers.GetWriteTranslator().Translate(ref value); @@ -779,10 +779,22 @@ protected bool Equals(BaseClass other) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) return false; - return Equals((BaseClass) obj); + if (ReferenceEquals(null, obj)) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + if (obj.GetType() != this.GetType()) + { + return false; + } + + return Equals((BaseClass)obj); } public override int GetHashCode() @@ -793,7 +805,7 @@ public override int GetHashCode() /// /// Gets a comparer. /// - static public IComparer Comparer + public static IComparer Comparer { get { return new BaseClassComparer(); } } @@ -887,7 +899,7 @@ public DerivedClass(int derivedValue, int baseValue) /// /// Gets a comparer. /// - static new public IComparer Comparer + public static new IComparer Comparer { get { return new DerivedClassComparer(); } } diff --git a/src/Build.UnitTests/BackEnd/BuildEventArgTransportSink_Tests.cs b/src/Build.UnitTests/BackEnd/BuildEventArgTransportSink_Tests.cs index d17003e254e..063eb110090 100644 --- a/src/Build.UnitTests/BackEnd/BuildEventArgTransportSink_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildEventArgTransportSink_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -52,8 +52,7 @@ public void TestConsumeNullBuildEvent() { BuildEventArgTransportSink transportSink = new BuildEventArgTransportSink(PacketProcessor); transportSink.Consume(null, 0); - } - ); + }); } /// /// Verify consume properly packages up the message event into a packet and send it to the diff --git a/src/Build.UnitTests/BackEnd/BuildManager_Tests.cs b/src/Build.UnitTests/BackEnd/BuildManager_Tests.cs index fdaf722b36c..c2d0569cb90 100644 --- a/src/Build.UnitTests/BackEnd/BuildManager_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildManager_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -1143,8 +1143,7 @@ public void EndWithoutBegin() Assert.Throws(() => { _buildManager.EndBuild(); - } - ); + }); } [Fact] @@ -1575,7 +1574,10 @@ public void CancelledBuild() [Fact] public void CancelledBuildWithDelay20() { - if (FrameworkLocationHelper.PathToDotNetFrameworkV20 == null) return; + if (FrameworkLocationHelper.PathToDotNetFrameworkV20 == null) + { + return; + } string contents = CleanupFileContents(@" @@ -1611,7 +1613,10 @@ public void CancelledBuildWithDelay20() [Fact] public void CancelledBuildInTaskHostWithDelay20() { - if (FrameworkLocationHelper.PathToDotNetFrameworkV20 == null) return; + if (FrameworkLocationHelper.PathToDotNetFrameworkV20 == null) + { + return; + } string contents = CleanupFileContents(@" @@ -3785,8 +3790,7 @@ public void OutOfProcFileBasedP2PBuildSucceeds() new Dictionary(), MSBuildConstants.CurrentToolsVersion, new[] { "MainTarget" }, - null - ); + null); var submission = _buildManager.PendBuildRequest(buildRequestData); @@ -3943,8 +3947,7 @@ public void OutOfProcEvaluationIdsUnique() new Dictionary(), MSBuildConstants.CurrentToolsVersion, new[] { "MainTarget" }, - null - ); + null); var submission = _buildManager.PendBuildRequest(buildRequestData); diff --git a/src/Build.UnitTests/BackEnd/BuildRequestConfigurationResponse_Tests.cs b/src/Build.UnitTests/BackEnd/BuildRequestConfigurationResponse_Tests.cs index c34403403be..6ff99854a30 100644 --- a/src/Build.UnitTests/BackEnd/BuildRequestConfigurationResponse_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildRequestConfigurationResponse_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Xunit; diff --git a/src/Build.UnitTests/BackEnd/BuildRequestConfiguration_Tests.cs b/src/Build.UnitTests/BackEnd/BuildRequestConfiguration_Tests.cs index dc3d33b9784..3f0b73c8dbb 100644 --- a/src/Build.UnitTests/BackEnd/BuildRequestConfiguration_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildRequestConfiguration_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -42,8 +42,7 @@ public void TestConstructorNullFile() Assert.Throws(() => { BuildRequestData config1 = new BuildRequestData(null, new Dictionary(), "toolsVersion", Array.Empty(), null); - } - ); + }); } [Fact] public void TestConstructorNullProps() @@ -51,8 +50,7 @@ public void TestConstructorNullProps() Assert.Throws(() => { BuildRequestData config1 = new BuildRequestData("file", null, "toolsVersion", Array.Empty(), null); - } - ); + }); } [Fact] public void TestConstructor1() @@ -68,8 +66,7 @@ public void TestConstructorInvalidConfigId() BuildRequestData data = new BuildRequestData("file", new Dictionary(), "toolsVersion", Array.Empty(), null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(1, data, "2.0"); config1.ShallowCloneWithNewId(0); - } - ); + }); } [Fact] public void TestConstructor2PositiveConfigId() @@ -91,8 +88,7 @@ public void TestConstructor2NullFile() Assert.Throws(() => { BuildRequestData config1 = new BuildRequestData(null, new Dictionary(), "toolsVersion", Array.Empty(), null); - } - ); + }); } [Fact] @@ -101,8 +97,7 @@ public void TestConstructor2NullProps() Assert.Throws(() => { BuildRequestData config1 = new BuildRequestData("file", null, "toolsVersion", Array.Empty(), null); - } - ); + }); } [Fact] public void TestWasGeneratedByNode() @@ -144,8 +139,7 @@ public void TestSetConfigurationIdBad() BuildRequestData data = new BuildRequestData("file", new Dictionary(StringComparer.OrdinalIgnoreCase), "toolsVersion", Array.Empty(), null); BuildRequestConfiguration config1 = new BuildRequestConfiguration(-1, data, "2.0"); config1.ConfigurationId = -2; - } - ); + }); } [Fact] public void TestSetConfigurationIdGood() @@ -277,7 +271,7 @@ public void TestTranslationWithEntireProjectState() "); - Dictionary globalProperties = new (StringComparer.OrdinalIgnoreCase); + Dictionary globalProperties = new(StringComparer.OrdinalIgnoreCase); globalProperties["ThreeIn"] = "3"; Project project = new Project( @@ -472,7 +466,7 @@ public void WorksCorrectlyWithCurlyBraces() try { // Check if } do not cause it to crash due to usage of String.Format or such on code path - string problematicTmpPath = Path.Combine(originalTmp, "}", "blabla", "temp"); + string problematicTmpPath = Path.Combine(originalTmp, "}", "blabla", "temp"); Environment.SetEnvironmentVariable("TMP", problematicTmpPath); Environment.SetEnvironmentVariable("TEMP", problematicTmpPath); diff --git a/src/Build.UnitTests/BackEnd/BuildRequestEngine_Tests.cs b/src/Build.UnitTests/BackEnd/BuildRequestEngine_Tests.cs index 3a464d3c342..a2c9cd48246 100644 --- a/src/Build.UnitTests/BackEnd/BuildRequestEngine_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildRequestEngine_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Build.UnitTests/BackEnd/BuildRequestEntry_Tests.cs b/src/Build.UnitTests/BackEnd/BuildRequestEntry_Tests.cs index d81ca32ecba..e2bb6680df1 100644 --- a/src/Build.UnitTests/BackEnd/BuildRequestEntry_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildRequestEntry_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -37,8 +37,7 @@ public void TestConstructorBad() Assert.Throws(() => { BuildRequestEntry entry = new BuildRequestEntry(null, null); - } - ); + }); } [Fact] public void TestSimpleStateProgression() @@ -189,8 +188,7 @@ public void TestNoReadyToWaiting() BuildRequest waitingRequest1 = CreateNewBuildRequest(2, new string[1] { "bar" }); entry.WaitForResult(waitingRequest1); - } - ); + }); } [Fact] @@ -207,8 +205,7 @@ public void TestNoReadyToComplete() BuildResult requiredResult = new BuildResult(request); requiredResult.AddResultsForTarget("foo", BuildResultUtilities.GetEmptySucceedingTargetResult()); entry.Complete(requiredResult); - } - ); + }); } [Fact] @@ -232,8 +229,7 @@ public void TestNoWaitingToComplete() BuildResult requiredResult = new BuildResult(request); requiredResult.AddResultsForTarget("foo", BuildResultUtilities.GetEmptySucceedingTargetResult()); entry.Complete(requiredResult); - } - ); + }); } [Fact] @@ -256,8 +252,7 @@ public void TestNoCompleteToWaiting() BuildRequest waitingRequest1 = CreateNewBuildRequest(2, new string[1] { "bar" }); entry.WaitForResult(waitingRequest1); - } - ); + }); } [Fact] public void TestResultsWithNoMatch1() diff --git a/src/Build.UnitTests/BackEnd/BuildRequest_Tests.cs b/src/Build.UnitTests/BackEnd/BuildRequest_Tests.cs index f4cd9d64cf0..9ba42506c30 100644 --- a/src/Build.UnitTests/BackEnd/BuildRequest_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildRequest_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Versioning; @@ -29,13 +29,12 @@ public void TestConstructorBad() Assert.Throws(() => { CreateNewBuildRequest(0, null); - } - ); + }); } [Fact] public void TestConstructorGood() { - CreateNewBuildRequest(0, Array.Empty() ); + CreateNewBuildRequest(0, Array.Empty()); } [Fact] @@ -100,8 +99,7 @@ public void TestResolveConfigurationBad() { BuildRequest request = CreateNewBuildRequest(1, Array.Empty()); request.ResolveConfiguration(2); - } - ); + }); } [Fact] @@ -111,8 +109,7 @@ public void TestResolveConfigurationBad2() { BuildRequest request = CreateNewBuildRequest(0, Array.Empty()); request.ResolveConfiguration(-1); - } - ); + }); } [Fact] public void TestTranslation() diff --git a/src/Build.UnitTests/BackEnd/BuildResult_Tests.cs b/src/Build.UnitTests/BackEnd/BuildResult_Tests.cs index 9901c21cbca..13269b5221a 100644 --- a/src/Build.UnitTests/BackEnd/BuildResult_Tests.cs +++ b/src/Build.UnitTests/BackEnd/BuildResult_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -64,8 +64,7 @@ public void TestConstructorBad() Assert.Throws(() => { BuildResult result = new BuildResult(null); - } - ); + }); } [Fact] public void TestConfigurationId() @@ -142,8 +141,7 @@ public void TestIndexerBad1() BuildRequest request = CreateNewBuildRequest(1, Array.Empty()); BuildResult result = new BuildResult(request); ITargetResult targetResult = result["foo"]; - } - ); + }); } [Fact] @@ -155,8 +153,7 @@ public void TestIndexerBad2() BuildResult result = new BuildResult(request); result.AddResultsForTarget("foo", BuildResultUtilities.GetEmptySucceedingTargetResult()); ITargetResult targetResult = result["bar"]; - } - ); + }); } [Fact] @@ -167,8 +164,7 @@ public void TestAddResultsInvalid1() BuildRequest request = CreateNewBuildRequest(1, Array.Empty()); BuildResult result = new BuildResult(request); result.AddResultsForTarget(null, BuildResultUtilities.GetEmptySucceedingTargetResult()); - } - ); + }); } [Fact] @@ -179,8 +175,7 @@ public void TestAddResultsInvalid2() BuildRequest request = CreateNewBuildRequest(1, Array.Empty()); BuildResult result = new BuildResult(request); result.AddResultsForTarget("foo", null); - } - ); + }); } [Fact] @@ -191,8 +186,7 @@ public void TestAddResultsInvalid3() BuildRequest request = CreateNewBuildRequest(1, Array.Empty()); BuildResult result = new BuildResult(request); result.AddResultsForTarget(null, BuildResultUtilities.GetEmptySucceedingTargetResult()); - } - ); + }); } [Fact] public void TestMergeResults() @@ -229,8 +223,7 @@ public void TestMergeResultsBad1() result.AddResultsForTarget("foo", BuildResultUtilities.GetEmptySucceedingTargetResult()); result.MergeResults(null); - } - ); + }); } [Fact] @@ -247,8 +240,7 @@ public void TestMergeResultsBad3() result2.AddResultsForTarget("bar", BuildResultUtilities.GetEmptySucceedingTargetResult()); result.MergeResults(result2); - } - ); + }); } [Fact] public void TestHasResultsForTarget() diff --git a/src/Build.UnitTests/BackEnd/CacheAggregator_Tests.cs b/src/Build.UnitTests/BackEnd/CacheAggregator_Tests.cs index 0a55644bbf8..bbe0f749387 100644 --- a/src/Build.UnitTests/BackEnd/CacheAggregator_Tests.cs +++ b/src/Build.UnitTests/BackEnd/CacheAggregator_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; @@ -75,11 +75,11 @@ public void CannotAddAfterAggregation() public void RejectCachesWithMoreConfigEntriesThanResultEntries() { var configCache = new ConfigCache(); - configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); - configCache.AddConfiguration(new BuildRequestConfiguration(configId: 2, new BuildRequestData("path2", new Dictionary(){["p"] = "v"}, "13", new []{"c", "d"}, null), "13")); + configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); + configCache.AddConfiguration(new BuildRequestConfiguration(configId: 2, new BuildRequestData("path2", new Dictionary() { ["p"] = "v" }, "13", new[] { "c", "d" }, null), "13")); var resultsCache = new ResultsCache(); - var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache.AddResult(buildResult); @@ -97,15 +97,15 @@ public void RejectCachesWithMoreConfigEntriesThanResultEntries() public void RejectCachesWithMoreResultEntriesThanConfigEntries() { var configCache = new ConfigCache(); - configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); + configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); var resultsCache = new ResultsCache(); - var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache.AddResult(buildResult); - var buildResult2 = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult2 = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult2.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache.AddResult(buildResult2); @@ -126,10 +126,10 @@ public void RejectCachesWithMismatchedIds() // one entry in each cache but different config ids var configCache = new ConfigCache(); - configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); + configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); var resultsCache = new ResultsCache(); - var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache.AddResult(buildResult); @@ -148,18 +148,18 @@ public void RejectCollidingConfigurationsFromSeparateCaches() { // collides with the config id from configCache2 var configCache1 = new ConfigCache(); - configCache1.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); + configCache1.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); var resultsCache1 = new ResultsCache(); - var buildResult11 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult11 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult11.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache1.AddResult(buildResult11); var configCache2 = new ConfigCache(); - configCache2.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); + configCache2.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); var resultsCache2 = new ResultsCache(); - var buildResult21 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"e", "f"}, null, BuildEventContext.Invalid, null)); + var buildResult21 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "e", "f" }, null, BuildEventContext.Invalid, null)); buildResult21.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache2.AddResult(buildResult21); @@ -185,17 +185,17 @@ public void SingleEmpty() var results = aggregator.Aggregate(); - AssertAggregation(new[] {(configCache, resultsCache)}, results); + AssertAggregation(new[] { (configCache, resultsCache) }, results); } [Fact] public void SingleCacheWithSingleEntry() { var configCache = new ConfigCache(); - configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); + configCache.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); var resultsCache = new ResultsCache(); - var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache.AddResult(buildResult); @@ -203,32 +203,32 @@ public void SingleCacheWithSingleEntry() var results = aggregator.Aggregate(); - AssertAggregation(new[] {(configCache, resultsCache)}, results); + AssertAggregation(new[] { (configCache, resultsCache) }, results); } [Fact] public void MultipleCachesMultipleEntries() { var configCache1 = new ConfigCache(); - configCache1.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary(){["p"] = "v"}, "13", new []{"a", "b"}, null), "13")); - configCache1.AddConfiguration(new BuildRequestConfiguration(configId: 2, new BuildRequestData("path2", new Dictionary(){["p"] = "v"}, "13", new []{"c", "d"}, null), "13")); + configCache1.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path", new Dictionary() { ["p"] = "v" }, "13", new[] { "a", "b" }, null), "13")); + configCache1.AddConfiguration(new BuildRequestConfiguration(configId: 2, new BuildRequestData("path2", new Dictionary() { ["p"] = "v" }, "13", new[] { "c", "d" }, null), "13")); var resultsCache1 = new ResultsCache(); - var buildResult11 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"a", "b"}, null, BuildEventContext.Invalid, null)); + var buildResult11 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "a", "b" }, null, BuildEventContext.Invalid, null)); buildResult11.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); - var buildResult12 = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List(){"c", "d"}, null, BuildEventContext.Invalid, null)); + var buildResult12 = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List() { "c", "d" }, null, BuildEventContext.Invalid, null)); buildResult12.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache1.AddResult(buildResult11); resultsCache1.AddResult(buildResult12); var configCache2 = new ConfigCache(); - configCache2.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path3", new Dictionary(){["p"] = "v"}, "13", new []{"e", "f"}, null), "13")); - configCache2.AddConfiguration(new BuildRequestConfiguration(configId: 2, new BuildRequestData("path4", new Dictionary(){["p"] = "v"}, "13", new []{"g", "h"}, null), "13")); + configCache2.AddConfiguration(new BuildRequestConfiguration(configId: 1, new BuildRequestData("path3", new Dictionary() { ["p"] = "v" }, "13", new[] { "e", "f" }, null), "13")); + configCache2.AddConfiguration(new BuildRequestConfiguration(configId: 2, new BuildRequestData("path4", new Dictionary() { ["p"] = "v" }, "13", new[] { "g", "h" }, null), "13")); var resultsCache2 = new ResultsCache(); - var buildResult21 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List(){"e", "f"}, null, BuildEventContext.Invalid, null)); + var buildResult21 = new BuildResult(new BuildRequest(1, 2, configurationId: 1, new List() { "e", "f" }, null, BuildEventContext.Invalid, null)); buildResult21.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); - var buildResult22 = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List(){"g", "h"}, null, BuildEventContext.Invalid, null)); + var buildResult22 = new BuildResult(new BuildRequest(1, 2, configurationId: 2, new List() { "g", "h" }, null, BuildEventContext.Invalid, null)); buildResult22.AddResultsForTarget("a", GetNonEmptySucceedingTargetResult()); resultsCache2.AddResult(buildResult21); resultsCache2.AddResult(buildResult22); @@ -238,7 +238,7 @@ public void MultipleCachesMultipleEntries() var results = aggregator.Aggregate(); - AssertAggregation(new[] {(configCache1, resultsCache1), (configCache2, resultsCache2)}, results); + AssertAggregation(new[] { (configCache1, resultsCache1), (configCache2, resultsCache2) }, results); } private void AssertAggregation((ConfigCache configCache, ResultsCache resultsCache)[] inputCaches, CacheAggregation aggregation) diff --git a/src/Build.UnitTests/BackEnd/CacheSerialization_Tests.cs b/src/Build.UnitTests/BackEnd/CacheSerialization_Tests.cs index ba4539b6d77..527c35aa556 100644 --- a/src/Build.UnitTests/BackEnd/CacheSerialization_Tests.cs +++ b/src/Build.UnitTests/BackEnd/CacheSerialization_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/src/Build.UnitTests/BackEnd/CentralForwardingLogger_Tests.cs b/src/Build.UnitTests/BackEnd/CentralForwardingLogger_Tests.cs index 76f0641c76d..35a76ac4ae7 100644 --- a/src/Build.UnitTests/BackEnd/CentralForwardingLogger_Tests.cs +++ b/src/Build.UnitTests/BackEnd/CentralForwardingLogger_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.BackEnd.Logging; @@ -56,8 +56,7 @@ public void InitializeWithNullEventSourceILogger() { CentralForwardingLogger centralLogger = new CentralForwardingLogger(); centralLogger.Initialize(null); - } - ); + }); } /// /// Verify the correct exception is thrown when the logger is initialized with a null @@ -70,8 +69,7 @@ public void InitializeWithNullEventSourceINodeLogger() { CentralForwardingLogger centralLogger = new CentralForwardingLogger(); centralLogger.Initialize(null, 4); - } - ); + }); } /// /// Verify the shutdown method will null out the event redirector diff --git a/src/Build.UnitTests/BackEnd/ConfigCache_Tests.cs b/src/Build.UnitTests/BackEnd/ConfigCache_Tests.cs index 1593604ae74..3ca18bc9832 100644 --- a/src/Build.UnitTests/BackEnd/ConfigCache_Tests.cs +++ b/src/Build.UnitTests/BackEnd/ConfigCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; @@ -24,13 +24,13 @@ public static IEnumerable CacheSerializationTestData var brq1 = new BuildRequestConfiguration( 1, - new BuildRequestData("path1", new Dictionary {["a1"] = "b1"}, Constants.defaultToolsVersion, new[] {"target1"}, null), + new BuildRequestData("path1", new Dictionary { ["a1"] = "b1" }, Constants.defaultToolsVersion, new[] { "target1" }, null), Constants.defaultToolsVersion); var configCache1 = new ConfigCache(); configCache1.AddConfiguration(brq1.ShallowCloneWithNewId(1)); - yield return new[] {configCache1}; + yield return new[] { configCache1 }; var brq2 = new BuildRequestConfiguration( 2, @@ -46,8 +46,8 @@ public static IEnumerable CacheSerializationTestData new BuildRequestData("path3", new Dictionary { ["a3"] = "b3" }, Constants.defaultToolsVersion, new[] { "target3" }, null), Constants.defaultToolsVersion); - brq3.ProjectDefaultTargets = new List {"target3"}; - brq3.ProjectInitialTargets = new List {"targetInitial"}; + brq3.ProjectDefaultTargets = new List { "target3" }; + brq3.ProjectInitialTargets = new List { "targetInitial" }; var configCache3 = new ConfigCache(); configCache3.AddConfiguration(brq3.ShallowCloneWithNewId(3)); @@ -92,7 +92,7 @@ public static IEnumerable CacheSerializationTestDataMultipleConfigs [MemberData(nameof(CacheSerializationTestData))] public void ConfigCacheShouldBeTranslatable(object obj) { - var initial = (ConfigCache) obj; + var initial = (ConfigCache)obj; TranslationHelpers.GetWriteTranslator().Translate(ref initial); diff --git a/src/Build.UnitTests/BackEnd/ConfigurationMetadata_Tests.cs b/src/Build.UnitTests/BackEnd/ConfigurationMetadata_Tests.cs index 5cbdd3a1394..ed39c3676dd 100644 --- a/src/Build.UnitTests/BackEnd/ConfigurationMetadata_Tests.cs +++ b/src/Build.UnitTests/BackEnd/ConfigurationMetadata_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -39,8 +39,7 @@ public void TestConstructorNullConfiguration() { BuildRequestConfiguration config = null; ConfigurationMetadata metadata = new ConfigurationMetadata(config); - } - ); + }); } /// /// Verify that a null project thrown an ArgumentNullException @@ -52,8 +51,7 @@ public void TestConstructorNullProject() { Project project = null; ConfigurationMetadata metadata = new ConfigurationMetadata(project); - } - ); + }); } /// /// Verify that we get the project path and tools version from the configuration diff --git a/src/Build.UnitTests/BackEnd/CustomLogAndReturnTask.cs b/src/Build.UnitTests/BackEnd/CustomLogAndReturnTask.cs index 163716cb7fd..a1d51e3f959 100644 --- a/src/Build.UnitTests/BackEnd/CustomLogAndReturnTask.cs +++ b/src/Build.UnitTests/BackEnd/CustomLogAndReturnTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/BackEnd/CustomTaskHelper.cs b/src/Build.UnitTests/BackEnd/CustomTaskHelper.cs index cc4575f5e70..1b53811036a 100644 --- a/src/Build.UnitTests/BackEnd/CustomTaskHelper.cs +++ b/src/Build.UnitTests/BackEnd/CustomTaskHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.UnitTests/BackEnd/DebugUtils_tests.cs b/src/Build.UnitTests/BackEnd/DebugUtils_tests.cs index 0419a840a6c..aea8fff3734 100644 --- a/src/Build.UnitTests/BackEnd/DebugUtils_tests.cs +++ b/src/Build.UnitTests/BackEnd/DebugUtils_tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.UnitTests/BackEnd/EventRedirectorToSink_Tests.cs b/src/Build.UnitTests/BackEnd/EventRedirectorToSink_Tests.cs index ff207da4d88..429c8b56084 100644 --- a/src/Build.UnitTests/BackEnd/EventRedirectorToSink_Tests.cs +++ b/src/Build.UnitTests/BackEnd/EventRedirectorToSink_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.BackEnd.Logging; @@ -25,8 +25,7 @@ public void TestConstructorNegativeLoggerId() { EventSourceSink testSink = new EventSourceSink(); EventRedirectorToSink eventRedirector = new EventRedirectorToSink(-10, testSink); - } - ); + }); } /// /// Verify the correct exception is thrown when the logger is initialized with a null @@ -38,8 +37,7 @@ public void TestConstructorNullSink() Assert.Throws(() => { EventRedirectorToSink eventRedirector = new EventRedirectorToSink(0, null); - } - ); + }); } /// /// Verify an valid inputs work and do not produce an exception @@ -63,20 +61,13 @@ public void TestForwardingNotNullEvent() EventRedirectorToSink eventRedirector = new EventRedirectorToSink(5, testSink); BuildMessageEventArgs messageEvent = new BuildMessageEventArgs("My message", "Help me keyword", "Sender", MessageImportance.High); bool wentInHandler = false; - testSink.AnyEventRaised += new AnyEventHandler - ( - delegate - ( - object sender, - BuildEventArgs buildEvent - ) + testSink.AnyEventRaised += new AnyEventHandler( + delegate (object sender, BuildEventArgs buildEvent) { wentInHandler = true; BuildMessageEventArgs messageEventFromPacket = buildEvent as BuildMessageEventArgs; Assert.Equal(messageEvent, messageEventFromPacket); // "Expected messageEvent to be forwarded to match actually forwarded event" - } - - ); + }); ((IEventRedirector)eventRedirector).ForwardEvent(messageEvent); Assert.True(wentInHandler); // "Expected to go into event handler" @@ -93,8 +84,7 @@ public void TestForwardingNullEvent() EventSourceSink testSink = new EventSourceSink(); EventRedirectorToSink eventRedirector = new EventRedirectorToSink(5, testSink); ((IEventRedirector)eventRedirector).ForwardEvent(null); - } - ); + }); } } } diff --git a/src/Build.UnitTests/BackEnd/EventSourceSink_Tests.cs b/src/Build.UnitTests/BackEnd/EventSourceSink_Tests.cs index 62ead33ff5e..379f27a3f1c 100644 --- a/src/Build.UnitTests/BackEnd/EventSourceSink_Tests.cs +++ b/src/Build.UnitTests/BackEnd/EventSourceSink_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -125,8 +125,7 @@ public void RaiseGenericBuildEventArgs() EventSourceSink sink = new EventSourceSink(); RaiseEventHelper eventHelper = new RaiseEventHelper(sink); eventHelper.RaiseBuildEvent(RaiseEventHelper.GenericBuildEvent); - } - ); + }); } /// /// Verify that shutdown un registers all of the event handlers diff --git a/src/Build.UnitTests/BackEnd/FailingBuilderTask.cs b/src/Build.UnitTests/BackEnd/FailingBuilderTask.cs index c8701f6beb4..43938fa32b8 100644 --- a/src/Build.UnitTests/BackEnd/FailingBuilderTask.cs +++ b/src/Build.UnitTests/BackEnd/FailingBuilderTask.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System.Collections; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; @@ -8,7 +9,7 @@ namespace Microsoft.Build.UnitTests { - public class FailingBuilderTask : Task + public class FailingBuilderTask : Task { public FailingBuilderTask() : base(null) diff --git a/src/Build.UnitTests/BackEnd/FailingTask.cs b/src/Build.UnitTests/BackEnd/FailingTask.cs index b2c784c90ab..cec197974d3 100644 --- a/src/Build.UnitTests/BackEnd/FailingTask.cs +++ b/src/Build.UnitTests/BackEnd/FailingTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/BackEnd/FullyQualifiedBuildRequest_Tests.cs b/src/Build.UnitTests/BackEnd/FullyQualifiedBuildRequest_Tests.cs index 576661b9af0..8b270f23caa 100644 --- a/src/Build.UnitTests/BackEnd/FullyQualifiedBuildRequest_Tests.cs +++ b/src/Build.UnitTests/BackEnd/FullyQualifiedBuildRequest_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -31,8 +31,7 @@ public void TestConstructorBad1() Assert.Throws(() => { FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(null, new string[1] { "foo" }, true); - } - ); + }); } [Fact] @@ -41,8 +40,7 @@ public void TestConstructorBad2() Assert.Throws(() => { FullyQualifiedBuildRequest request = new FullyQualifiedBuildRequest(new BuildRequestConfiguration(new BuildRequestData("foo", new Dictionary(), "tools", Array.Empty(), null), "2.0"), null, true); - } - ); + }); } [Fact] public void TestProperties() diff --git a/src/Build.UnitTests/BackEnd/GenerateTemporaryTargetAssembly_Tests.cs b/src/Build.UnitTests/BackEnd/GenerateTemporaryTargetAssembly_Tests.cs index 4d3b8c7c06c..51748e79ab0 100644 --- a/src/Build.UnitTests/BackEnd/GenerateTemporaryTargetAssembly_Tests.cs +++ b/src/Build.UnitTests/BackEnd/GenerateTemporaryTargetAssembly_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using Microsoft.Build.UnitTests; using Shouldly; using System.Linq; @@ -10,7 +11,7 @@ namespace Microsoft.Build.Engine.UnitTests.BackEnd { - sealed public class GenerateTemporaryTargetAssembly_Tests + public sealed class GenerateTemporaryTargetAssembly_Tests { [Fact] public void FailsWithOnlyTargetErrors() diff --git a/src/Build.UnitTests/BackEnd/ITestTaskHost.cs b/src/Build.UnitTests/BackEnd/ITestTaskHost.cs index bf139b239a1..76ec9921152 100644 --- a/src/Build.UnitTests/BackEnd/ITestTaskHost.cs +++ b/src/Build.UnitTests/BackEnd/ITestTaskHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; diff --git a/src/Build.UnitTests/BackEnd/IntegrationTests.cs b/src/Build.UnitTests/BackEnd/IntegrationTests.cs index 9a951727c87..b2934bab86f 100644 --- a/src/Build.UnitTests/BackEnd/IntegrationTests.cs +++ b/src/Build.UnitTests/BackEnd/IntegrationTests.cs @@ -1,8 +1,11 @@ -#nullable disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable disable namespace Microsoft.Build.Unittest.BackEnd { - class IntegrationTests + internal class IntegrationTests { } } diff --git a/src/Build.UnitTests/BackEnd/IntrinsicTask_Tests.cs b/src/Build.UnitTests/BackEnd/IntrinsicTask_Tests.cs index 6497b641bbc..25e2ed70e01 100644 --- a/src/Build.UnitTests/BackEnd/IntrinsicTask_Tests.cs +++ b/src/Build.UnitTests/BackEnd/IntrinsicTask_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -97,8 +97,7 @@ public void PropertyGroupWithReservedProperty() "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task); - } - ); + }); } [Fact] @@ -114,12 +113,10 @@ public void PropertyGroupWithInvalidPropertyName() - " - ); + "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task); - } - ); + }); } [Fact] public void BlankProperty() @@ -132,8 +129,7 @@ public void BlankProperty() - " - ); + "); IntrinsicTask task = CreateIntrinsicTask(content); PropertyDictionary properties = new PropertyDictionary(); ExecuteTask(task, LookupHelpers.CreateLookup(properties)); @@ -153,12 +149,10 @@ public void PropertyGroupWithInvalidSyntax1() x - " - ); + "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] @@ -174,12 +168,10 @@ public void PropertyGroupWithInvalidSyntax2()

- " - ); + "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] public void PropertyGroupWithConditionOnGroup() @@ -661,8 +653,7 @@ public void ItemKeepMetadataAndRemoveMetadataMutuallyExclusive() IntrinsicTask task = CreateIntrinsicTask(content); Lookup lookup = LookupHelpers.CreateEmptyLookup(); ExecuteTask(task, lookup); - } - ); + }); } ///

/// Should not make items with an empty include. @@ -748,8 +739,7 @@ public void ItemGroupWithInvalidSyntax1() "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] @@ -767,8 +757,7 @@ public void ItemGroupWithInvalidSyntax2() "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] @@ -786,8 +775,7 @@ public void ItemGroupWithInvalidSyntax3() "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] public void ItemGroupWithTransform() @@ -1575,8 +1563,7 @@ public void IncludeNoOp() "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] public void RemoveNoOp() @@ -1739,7 +1726,7 @@ public void RemoveWithItemReferenceOnMatchingMetadata() var items = lookup.GetItems("I2"); - items.Select(i => i.EvaluatedInclude).ShouldBe(new []{"a2", "d2"}); + items.Select(i => i.EvaluatedInclude).ShouldBe(new[] { "a2", "d2" }); items.ElementAt(0).GetMetadataValue("M1").ShouldBe("x"); items.ElementAt(0).GetMetadataValue("M2").ShouldBe("c"); @@ -1796,7 +1783,7 @@ public void RemoveWithItemReferenceOnFilePathMatchingMetadata() - + @@ -2964,8 +2951,7 @@ public void ModifyItemWithUnqualifiedMetadataError() "); IntrinsicTask task = CreateIntrinsicTask(content); ExecuteTask(task, null); - } - ); + }); } [Fact] public void ModifyItemInTargetWithConditionWithoutItemTypeOnMetadataInCondition() diff --git a/src/Build.UnitTests/BackEnd/ItemCreationTask.cs b/src/Build.UnitTests/BackEnd/ItemCreationTask.cs index 717cdb9812f..602ba0caedd 100644 --- a/src/Build.UnitTests/BackEnd/ItemCreationTask.cs +++ b/src/Build.UnitTests/BackEnd/ItemCreationTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/BackEnd/KnownTelemetry_Tests.cs b/src/Build.UnitTests/BackEnd/KnownTelemetry_Tests.cs index a0ae7a9fafd..a33becfa758 100644 --- a/src/Build.UnitTests/BackEnd/KnownTelemetry_Tests.cs +++ b/src/Build.UnitTests/BackEnd/KnownTelemetry_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; diff --git a/src/Build.UnitTests/BackEnd/LoggingContext_Tests.cs b/src/Build.UnitTests/BackEnd/LoggingContext_Tests.cs index 8a372962d89..7ccbcc227b7 100644 --- a/src/Build.UnitTests/BackEnd/LoggingContext_Tests.cs +++ b/src/Build.UnitTests/BackEnd/LoggingContext_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Framework; @@ -60,8 +60,7 @@ public void InvalidNodeIdOnNodeLoggingContext() Assert.Throws(() => { _ = new NodeLoggingContext(new MockLoggingService(), -2, true); - } - ); + }); } [Fact] diff --git a/src/Build.UnitTests/BackEnd/LoggingServiceFactory_Tests.cs b/src/Build.UnitTests/BackEnd/LoggingServiceFactory_Tests.cs index d29d9623ecc..4d56352d241 100644 --- a/src/Build.UnitTests/BackEnd/LoggingServiceFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/LoggingServiceFactory_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.BackEnd; diff --git a/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs b/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs index 07e0760970e..504cbb3747b 100644 --- a/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs +++ b/src/Build.UnitTests/BackEnd/LoggingService_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -118,8 +118,7 @@ public void InitializeComponentNullHost() { IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); logServiceComponent.InitializeComponent(null); - } - ); + }); } /// /// Verify an exception is thrown if in initialized is called after the service has been shutdown @@ -131,8 +130,7 @@ public void InitializeComponentAfterShutdown() { _initializedService.ShutdownComponent(); _initializedService.InitializeComponent(new MockHost()); - } - ); + }); } /// /// Verify the correct exceptions are thrown if the loggers crash @@ -192,8 +190,7 @@ public void DoubleShutdown() { _initializedService.ShutdownComponent(); _initializedService.ShutdownComponent(); - } - ); + }); } #endregion @@ -207,8 +204,7 @@ public void NullLogger() Assert.Throws(() => { _initializedService.RegisterLogger(null); - } - ); + }); } /// /// Verify we get an exception when we try and register a logger @@ -222,8 +218,7 @@ public void RegisterLoggerServiceShutdown() _initializedService.ShutdownComponent(); RegularILogger regularILogger = new RegularILogger(); _initializedService.RegisterLogger(regularILogger); - } - ); + }); } /// /// Verify a logger exception when initializing a logger is rethrown @@ -236,8 +231,7 @@ public void LoggerExceptionInInitialize() { LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new LoggerException()); _initializedService.RegisterLogger(exceptionLogger); - } - ); + }); } /// /// Verify a general exception when initializing a logger is wrapped @@ -250,8 +244,7 @@ public void GeneralExceptionInInitialize() { LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new Exception()); _initializedService.RegisterLogger(exceptionLogger); - } - ); + }); } /// @@ -264,8 +257,7 @@ public void ILoggerExceptionInInitialize() { LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new StackOverflowException()); _initializedService.RegisterLogger(exceptionLogger); - } - ); + }); } /// @@ -327,8 +319,7 @@ public void NullForwardingLogger() Assert.Throws(() => { _initializedService.RegisterDistributedLogger(null, null); - } - ); + }); } /// /// Verify we get an exception when we try and register a distributed logger @@ -347,8 +338,7 @@ public void RegisterDistributedLoggerServiceShutdown() LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true); #endif _initializedService.RegisterDistributedLogger(null, description); - } - ); + }); } /// /// Register both a good central logger and a good forwarding logger @@ -512,8 +502,7 @@ public void NullDescriptionCollection() Assert.Throws(() => { _initializedService.InitializeNodeLoggers(null, new EventSourceSink(), 3); - } - ); + }); } /// /// Verify we get an exception when an empty description collection is passed in @@ -524,8 +513,7 @@ public void EmptyDescriptionCollection() Assert.Throws(() => { _initializedService.InitializeNodeLoggers(new List(), new EventSourceSink(), 3); - } - ); + }); } /// /// Verify we get an exception when we try and register a description and the component has already shutdown @@ -545,8 +533,7 @@ public void NullForwardingLoggerSink() List tempList = new List(); tempList.Add(description); _initializedService.InitializeNodeLoggers(tempList, new EventSourceSink(), 2); - } - ); + }); } /// /// Register both a good central logger and a good forwarding logger @@ -687,8 +674,7 @@ public void NullPacketReceived() { LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); loggingService.PacketReceived(1, null); - } - ); + }); } /// /// Verify when a non logging packet is received. @@ -702,8 +688,7 @@ public void NonLoggingPacketPacketReceived() LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); NonLoggingPacket packet = new NonLoggingPacket(); loggingService.PacketReceived(1, packet); - } - ); + }); } /// /// Verify when a logging packet is received the build event is @@ -1165,14 +1150,12 @@ private LoggerDescription CreateLoggerDescription(string loggerClassName, string eventsToForward = "BuildStartedEvent;BuildFinishedEvent;ProjectStartedEvent;ProjectFinishedEvent;TargetStartedEvent;TargetFinishedEvent;TaskStartedEvent;TaskFinishedEvent;ErrorEvent;WarningEvent;HighMessageEvent;NormalMessageEvent;LowMessageEvent;CustomEvent;CommandLine"; } - LoggerDescription centralLoggerDescrption = new LoggerDescription - ( + LoggerDescription centralLoggerDescrption = new LoggerDescription( loggerClassName, loggerAssemblyName, null /*Not needed as we are loading from current assembly*/, eventsToForward, - LoggerVerbosity.Diagnostic /*Not used, but the spirit of the logger is to forward everything so this is the most appropriate verbosity */ - ); + LoggerVerbosity.Diagnostic); /*Not used, but the spirit of the logger is to forward everything so this is the most appropriate verbosity */ return centralLoggerDescrption; } diff --git a/src/Build.UnitTests/BackEnd/LoggingServicesLogMethod_Tests.cs b/src/Build.UnitTests/BackEnd/LoggingServicesLogMethod_Tests.cs index c9964af9f2d..5942f8ab8e4 100644 --- a/src/Build.UnitTests/BackEnd/LoggingServicesLogMethod_Tests.cs +++ b/src/Build.UnitTests/BackEnd/LoggingServicesLogMethod_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -54,8 +54,7 @@ public void LogBuildEventNullEvent() { LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1); loggingService.LogBuildEvent(null); - } - ); + }); } /// @@ -105,8 +104,7 @@ public void LogErrorNullMessageResource() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogError(s_buildEventContext, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo("foo.cs"), null, "MyTask"); - } - ); + }); } /// @@ -119,8 +117,7 @@ public void LogErrorEmptyMessageResource() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogError(s_buildEventContext, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo("foo.cs"), string.Empty, "MyTask"); - } - ); + }); } /// @@ -157,8 +154,7 @@ public void LogInvalidProjectFileErrorNullEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogInvalidProjectFileError(null, new InvalidProjectFileException()); - } - ); + }); } /// @@ -171,8 +167,7 @@ public void LogInvalidProjectFileErrorNullException() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogInvalidProjectFileError(s_buildEventContext, null); - } - ); + }); } /// @@ -220,8 +215,7 @@ public void LogFatalErrorNullContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogFatalError(null, new Exception("SuperException"), new BuildEventFileInfo("foo.cs"), "FatalTaskError", "TaskName"); - } - ); + }); } /// @@ -234,8 +228,7 @@ public void LogFatalErrorNullFileInfo() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogFatalError(s_buildEventContext, new Exception("SuperException"), null, "FatalTaskError", "TaskName"); - } - ); + }); } /// @@ -267,8 +260,7 @@ public void LogFatalErrorNullMessageResourceName() BuildEventFileInfo fileInfo = new BuildEventFileInfo("foo.cs", 1, 2, 3, 4); ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogFatalError(s_buildEventContext, new Exception("SuperException"), fileInfo, null); - } - ); + }); } /// @@ -282,8 +274,7 @@ public void LogFatalErrorEmptyMessageResourceName() BuildEventFileInfo fileInfo = new BuildEventFileInfo("foo.cs", 1, 2, 3, 4); ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogFatalError(s_buildEventContext, new Exception("SuperException"), fileInfo, string.Empty, null); - } - ); + }); } /// @@ -343,8 +334,7 @@ public void LogFatalTaskErrorNullTaskNameName() BuildEventFileInfo fileInfo = new BuildEventFileInfo("foo.cs", 1, 2, 3, 4); ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogFatalTaskError(s_buildEventContext, new Exception("SuperException"), fileInfo, null); - } - ); + }); } /// @@ -384,8 +374,7 @@ public void LogErrorFromTextNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogErrorFromText(null, "SubCategoryForSolutionParsingErrors", "WarningCode", "HelpKeyword", new BuildEventFileInfo("foo.cs"), "Message"); - } - ); + }); } /// @@ -398,8 +387,7 @@ public void LogErrorFromTextNullFileInfo() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogErrorFromText(s_buildEventContext, "SubCategoryForSolutionParsingErrors", "WarningCode", "HelpKeyword", null, "Message"); - } - ); + }); } /// @@ -412,8 +400,7 @@ public void LogErrorFromTextNullMessage() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogErrorFromText(null, "SubCategoryForSolutionParsingErrors", "WarningCode", "HelpKeyword", new BuildEventFileInfo("foo.cs"), null); - } - ); + }); } /// @@ -522,8 +509,7 @@ public void LogTaskWarningFromExceptionNullTaskName() BuildEventFileInfo fileInfo = new BuildEventFileInfo("foo.cs", 1, 2, 3, 4); ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogTaskWarningFromException(s_buildEventContext, null, fileInfo, null); - } - ); + }); } /// @@ -537,8 +523,7 @@ public void LogTaskWarningFromExceptionEmptyTaskName() BuildEventFileInfo fileInfo = new BuildEventFileInfo("foo.cs", 1, 2, 3, 4); ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogTaskWarningFromException(s_buildEventContext, null, fileInfo, null); - } - ); + }); } /// @@ -581,8 +566,7 @@ public void LogWarningNullMessageResource() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogWarning(s_buildEventContext, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo("foo.cs"), null, "MyTask"); - } - ); + }); } /// @@ -595,8 +579,7 @@ public void LogWarningEmptyMessageResource() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogWarning(s_buildEventContext, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo("foo.cs"), string.Empty, "MyTask"); - } - ); + }); } /// @@ -623,8 +606,7 @@ public void LogWarningFromTextNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogWarningFromText(null, "SubCategoryForSolutionParsingErrors", "WarningCode", "HelpKeyword", new BuildEventFileInfo("foo.cs"), "Message"); - } - ); + }); } /// @@ -637,8 +619,7 @@ public void LogWarningFromTextNullFileInfo() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogWarningFromText(s_buildEventContext, "SubCategoryForSolutionParsingErrors", "WarningCode", "HelpKeyword", null, "Message"); - } - ); + }); } /// @@ -651,8 +632,7 @@ public void LogWarningFromTextNullMessage() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogWarningFromText(null, "SubCategoryForSolutionParsingErrors", "WarningCode", "HelpKeyword", new BuildEventFileInfo("foo.cs"), null); - } - ); + }); } /// @@ -696,8 +676,7 @@ public void LogCommentNullMessageResourceName() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogComment(s_buildEventContext, MessageImportance.Low, null, null); - } - ); + }); } /// @@ -710,8 +689,7 @@ public void LogCommentEmptyMessageResourceName() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogComment(s_buildEventContext, MessageImportance.Low, String.Empty, null); - } - ); + }); } /// @@ -751,8 +729,7 @@ public void LogCommentFromTextNullMessage() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogCommentFromText(s_buildEventContext, MessageImportance.Low, null); - } - ); + }); } /// @@ -775,8 +752,7 @@ public void LogCommentFromTextNullBuildEventContextMessage() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogCommentFromText(null, MessageImportance.Low, "Hello"); - } - ); + }); } /// @@ -816,8 +792,7 @@ public void ProjectStartedNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogProjectStarted(null, 1, 2, s_buildEventContext, "ProjectFile", "TargetNames", null, null); - } - ); + }); } /// @@ -831,8 +806,7 @@ public void ProjectStartedNullParentBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogProjectStarted(s_buildEventContext, 1, 2, null, "ProjectFile", "TargetNames", null, null); - } - ); + }); } /// @@ -1001,8 +975,7 @@ public void ProjectFinishedNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogProjectFinished(null, "ProjectFile", true); - } - ); + }); } /// @@ -1119,8 +1092,7 @@ public void TaskStartedNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogTaskStarted(null, "MyTask", "ProjectFile", "ProjectFileOfTask"); - } - ); + }); } /// @@ -1155,8 +1127,7 @@ public void TaskFinishedNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogTaskFinished(null, "MyTask", "ProjectFile", "ProjectFileOfTask", true); - } - ); + }); } /// @@ -1196,8 +1167,7 @@ public void TargetStartedNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogTargetStarted(null, "MyTarget", "ProjectFile", "ProjectFileOfTarget", null, TargetBuiltReason.None); - } - ); + }); } /// @@ -1245,8 +1215,7 @@ public void TargetFinishedNullBuildEventContext() { ProcessBuildEventHelper service = (ProcessBuildEventHelper)ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1); service.LogTargetFinished(null, "MyTarget", "ProjectFile", "ProjectFileOfTarget", true, null); - } - ); + }); } /// @@ -1450,8 +1419,7 @@ private void TestProjectFinishedEvent(string projectFile, bool success) cache.AddConfiguration(config); // Now do it the right way -- with a matching ProjectStarted. - BuildEventContext projectContext = service.LogProjectStarted - ( + BuildEventContext projectContext = service.LogProjectStarted( new BuildEventContext(1, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId), 1, 2, @@ -1459,8 +1427,7 @@ private void TestProjectFinishedEvent(string projectFile, bool success) projectFile, null, null, - null - ); + null); service.LogProjectFinished(projectContext, projectFile, success); @@ -1599,8 +1566,7 @@ private void TestTargetStartedWithParentTargetEvent(string targetName, string pr /// LoggingService mock object which overrides ProcessBuildEvent and can provide a ProcessedBuildEvent (the event which would have been sent to the loggers) private void VerifyTargetFinishedEvent(string targetName, string projectFile, string projectFileOfTarget, bool succeeded, string message, ProcessBuildEventHelper service, IEnumerable targetOutputs) { - TargetFinishedEventArgs targetEvent = new TargetFinishedEventArgs - ( + TargetFinishedEventArgs targetEvent = new TargetFinishedEventArgs( message, null, targetName, @@ -1608,8 +1574,7 @@ private void VerifyTargetFinishedEvent(string targetName, string projectFile, st projectFileOfTarget, succeeded, service.ProcessedBuildEvent.Timestamp, - targetOutputs - ); + targetOutputs); targetEvent.BuildEventContext = s_targetBuildEventContext; Assert.True(((TargetFinishedEventArgs)service.ProcessedBuildEvent).IsEquivalent(targetEvent)); } @@ -1624,8 +1589,7 @@ private void VerifyTargetFinishedEvent(string targetName, string projectFile, st /// LoggingService mock object which overrides ProcessBuildEvent and can provide a ProcessedBuildEvent (the event which would have been sent to the loggers) private void VerifyTargetStartedEvent(string targetName, string projectFile, string projectFileOfTarget, string message, ProcessBuildEventHelper service) { - TargetStartedEventArgs buildEvent = new TargetStartedEventArgs - ( + TargetStartedEventArgs buildEvent = new TargetStartedEventArgs( message, null, // no help keyword targetName, @@ -1633,8 +1597,7 @@ private void VerifyTargetStartedEvent(string targetName, string projectFile, str projectFileOfTarget, String.Empty, TargetBuiltReason.None, - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); buildEvent.BuildEventContext = s_targetBuildEventContext; Assert.True(((TargetStartedEventArgs)service.ProcessedBuildEvent).IsEquivalent(buildEvent)); } @@ -1650,16 +1613,14 @@ private void VerifyTargetStartedEvent(string targetName, string projectFile, str /// LoggingService mock object which overrides ProcessBuildEvent and can provide a ProcessedBuildEvent (the event which would have been sent to the loggers) private void VerifyTaskFinishedEvent(string taskName, string projectFile, string projectFileOfTask, bool succeeded, string message, ProcessBuildEventHelper service) { - TaskFinishedEventArgs taskEvent = new TaskFinishedEventArgs - ( + TaskFinishedEventArgs taskEvent = new TaskFinishedEventArgs( message, null, projectFile, projectFileOfTask, taskName, succeeded, - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); taskEvent.BuildEventContext = s_buildEventContext; Assert.True(((TaskFinishedEventArgs)service.ProcessedBuildEvent).IsEquivalent(taskEvent)); } @@ -1674,15 +1635,13 @@ private void VerifyTaskFinishedEvent(string taskName, string projectFile, string /// LoggingService mock object which overrides ProcessBuildEvent and can provide a ProcessedBuildEvent (the event which would have been sent to the loggers) private void VerifyTaskStartedEvent(string taskName, string projectFile, string projectFileOfTask, string message, ProcessBuildEventHelper service) { - TaskStartedEventArgs taskEvent = new TaskStartedEventArgs - ( + TaskStartedEventArgs taskEvent = new TaskStartedEventArgs( message, null, // no help keyword projectFile, projectFileOfTask, taskName, - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); taskEvent.BuildEventContext = s_buildEventContext; Assert.True(((TaskStartedEventArgs)service.ProcessedBuildEvent).IsEquivalent(taskEvent)); } @@ -1697,14 +1656,12 @@ private void VerifyTaskStartedEvent(string taskName, string projectFile, string /// Success value to create the comparison event with private void VerifyProjectFinishedEvent(ProcessBuildEventHelper service, BuildEventContext projectContext, string message, string projectFile, bool success) { - ProjectFinishedEventArgs projectEvent = new ProjectFinishedEventArgs - ( + ProjectFinishedEventArgs projectEvent = new ProjectFinishedEventArgs( message, null, projectFile, success, - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); projectEvent.BuildEventContext = projectContext; Assert.True(((ProjectFinishedEventArgs)service.ProcessedBuildEvent).IsEquivalent(projectEvent)); } @@ -1720,8 +1677,7 @@ private void VerifyProjectFinishedEvent(ProcessBuildEventHelper service, BuildEv /// ParentBuildEventContext to create the comparison event with. private void VerifyProjectStartedEventArgs(ProcessBuildEventHelper service, int projectId, string message, string projectFile, string targetNames, BuildEventContext parentBuildEventContext, BuildEventContext generatedContext) { - ProjectStartedEventArgs buildEvent = new ProjectStartedEventArgs - ( + ProjectStartedEventArgs buildEvent = new ProjectStartedEventArgs( projectId, message, null, // no help keyword @@ -1730,8 +1686,7 @@ private void VerifyProjectStartedEventArgs(ProcessBuildEventHelper service, int null, null, parentBuildEventContext, - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); buildEvent.BuildEventContext = generatedContext; Assert.True(((ProjectStartedEventArgs)service.ProcessedBuildEvent).IsEquivalent(buildEvent)); } @@ -1744,14 +1699,12 @@ private void VerifyProjectStartedEventArgs(ProcessBuildEventHelper service, int /// Message to create the comparison event with private void VerityBuildMessageEventArgs(ProcessBuildEventHelper service, MessageImportance messageImportance, string message) { - BuildMessageEventArgs buildMessageEvent = new BuildMessageEventArgs - ( + BuildMessageEventArgs buildMessageEvent = new BuildMessageEventArgs( message, null, "MSBuild", messageImportance, - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); buildMessageEvent.BuildEventContext = s_buildEventContext; Assert.True(((BuildMessageEventArgs)service.ProcessedBuildEvent).IsEquivalent(buildMessageEvent)); @@ -1768,8 +1721,7 @@ private void VerityBuildMessageEventArgs(ProcessBuildEventHelper service, Messag /// Subcategory to create the comparison event with private void VerifyBuildWarningEventArgs(BuildEventFileInfo fileInfo, string warningCode, string helpKeyword, string message, ProcessBuildEventHelper service, string subcategory) { - BuildWarningEventArgs buildEvent = new BuildWarningEventArgs - ( + BuildWarningEventArgs buildEvent = new BuildWarningEventArgs( subcategory, warningCode, fileInfo.File, @@ -1780,8 +1732,7 @@ private void VerifyBuildWarningEventArgs(BuildEventFileInfo fileInfo, string war message, helpKeyword, "MSBuild", - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); buildEvent.BuildEventContext = s_buildEventContext; Assert.True(buildEvent.IsEquivalent((BuildWarningEventArgs)service.ProcessedBuildEvent)); } @@ -1797,8 +1748,7 @@ private void VerifyBuildWarningEventArgs(BuildEventFileInfo fileInfo, string war /// Subcategory to create the comparison event with private void VerifyBuildErrorEventArgs(BuildEventFileInfo fileInfo, string errorCode, string helpKeyword, string message, ProcessBuildEventHelper service, string subcategory) { - BuildErrorEventArgs buildEvent = new BuildErrorEventArgs - ( + BuildErrorEventArgs buildEvent = new BuildErrorEventArgs( subcategory, errorCode, fileInfo.File, @@ -1809,8 +1759,7 @@ private void VerifyBuildErrorEventArgs(BuildEventFileInfo fileInfo, string error message, helpKeyword, "MSBuild", - service.ProcessedBuildEvent.Timestamp - ); + service.ProcessedBuildEvent.Timestamp); buildEvent.BuildEventContext = s_buildEventContext; Assert.True(buildEvent.IsEquivalent((BuildErrorEventArgs)service.ProcessedBuildEvent)); } @@ -1880,7 +1829,7 @@ public BuildEventArgs ProcessedBuildEvent /// /// Logger mode, this is not used /// Instantiated LoggingServiceOverrideProcessBuildEvent - public new static IBuildComponent CreateLoggingService(LoggerMode mode, int nodeId) + public static new IBuildComponent CreateLoggingService(LoggerMode mode, int nodeId) { return new ProcessBuildEventHelper(mode, nodeId, null); } diff --git a/src/Build.UnitTests/BackEnd/Lookup_Tests.cs b/src/Build.UnitTests/BackEnd/Lookup_Tests.cs index ae99bbcc52f..2ca5c9a96c4 100644 --- a/src/Build.UnitTests/BackEnd/Lookup_Tests.cs +++ b/src/Build.UnitTests/BackEnd/Lookup_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -213,9 +213,9 @@ public void AddsWithDuplicateRemovalWithMetadata() ProjectItemInstance[] newItems = new ProjectItemInstance[] { new ProjectItemInstance(project, "i1", "a1", project.FullPath), // Should get added - new ProjectItemInstance(project, "i1", "a2", new KeyValuePair[] { new KeyValuePair( "m1", "m1" ) }, project.FullPath), // Should get added - new ProjectItemInstance(project, "i1", "a1", new KeyValuePair[] { new KeyValuePair( "m1", "m1" ) }, project.FullPath), // Should not get added - new ProjectItemInstance(project, "i1", "a1", new KeyValuePair[] { new KeyValuePair( "m1", "m3" ) }, project.FullPath), // Should get added + new ProjectItemInstance(project, "i1", "a2", new KeyValuePair[] { new KeyValuePair( "m1", "m1") }, project.FullPath), // Should get added + new ProjectItemInstance(project, "i1", "a1", new KeyValuePair[] { new KeyValuePair( "m1", "m1") }, project.FullPath), // Should not get added + new ProjectItemInstance(project, "i1", "a1", new KeyValuePair[] { new KeyValuePair( "m1", "m3") }, project.FullPath), // Should get added }; // Perform the addition @@ -1014,8 +1014,7 @@ public void ModifyItemInOutsideScope() ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); Lookup lookup = LookupHelpers.CreateLookup(new ItemDictionary()); lookup.AddNewItem(new ProjectItemInstance(project, "x", "y", project.FullPath)); - } - ); + }); } /// /// After modification, should be able to GetItem and then modify it again diff --git a/src/Build.UnitTests/BackEnd/MSBuild_Tests.cs b/src/Build.UnitTests/BackEnd/MSBuild_Tests.cs index c802415a697..a948c97234a 100644 --- a/src/Build.UnitTests/BackEnd/MSBuild_Tests.cs +++ b/src/Build.UnitTests/BackEnd/MSBuild_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/BackEnd/MockHost.cs b/src/Build.UnitTests/BackEnd/MockHost.cs index dc4aaff843e..caae65aa14d 100644 --- a/src/Build.UnitTests/BackEnd/MockHost.cs +++ b/src/Build.UnitTests/BackEnd/MockHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.Logging; diff --git a/src/Build.UnitTests/BackEnd/MockLoggingService.cs b/src/Build.UnitTests/BackEnd/MockLoggingService.cs index 681e0d155c4..63872aacec7 100644 --- a/src/Build.UnitTests/BackEnd/MockLoggingService.cs +++ b/src/Build.UnitTests/BackEnd/MockLoggingService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build.UnitTests/BackEnd/MockRemoteHostObject.cs b/src/Build.UnitTests/BackEnd/MockRemoteHostObject.cs index 4ce3b3498cf..26c55e26571 100644 --- a/src/Build.UnitTests/BackEnd/MockRemoteHostObject.cs +++ b/src/Build.UnitTests/BackEnd/MockRemoteHostObject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; diff --git a/src/Build.UnitTests/BackEnd/MockRunningObjectTable.cs b/src/Build.UnitTests/BackEnd/MockRunningObjectTable.cs index ce9ad201d0a..07e98fef1b8 100644 --- a/src/Build.UnitTests/BackEnd/MockRunningObjectTable.cs +++ b/src/Build.UnitTests/BackEnd/MockRunningObjectTable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/BackEnd/MockSdkResolverService.cs b/src/Build.UnitTests/BackEnd/MockSdkResolverService.cs index b1c4ccd843f..8d4c69d1e0b 100644 --- a/src/Build.UnitTests/BackEnd/MockSdkResolverService.cs +++ b/src/Build.UnitTests/BackEnd/MockSdkResolverService.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.BackEnd; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.BackEnd.SdkResolution; using Microsoft.Build.Construction; diff --git a/src/Build.UnitTests/BackEnd/MockTaskBuilder.cs b/src/Build.UnitTests/BackEnd/MockTaskBuilder.cs index 4cdbfdaa711..c69de1ec4ee 100644 --- a/src/Build.UnitTests/BackEnd/MockTaskBuilder.cs +++ b/src/Build.UnitTests/BackEnd/MockTaskBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/BackEnd/NodeEndpointInProc_Tests.cs b/src/Build.UnitTests/BackEnd/NodeEndpointInProc_Tests.cs index 7b6a17d9d9d..7675567e257 100644 --- a/src/Build.UnitTests/BackEnd/NodeEndpointInProc_Tests.cs +++ b/src/Build.UnitTests/BackEnd/NodeEndpointInProc_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -185,8 +185,7 @@ public void ConstructionSynchronousWithInvalidHost() { NodeEndpointInProc.CreateInProcEndpoints( NodeEndpointInProc.EndpointMode.Synchronous, null); - } - ); + }); } [Fact] @@ -196,8 +195,7 @@ public void ConstructionAsynchronousWithInvalidHost() { NodeEndpointInProc.CreateInProcEndpoints( NodeEndpointInProc.EndpointMode.Asynchronous, null); - } - ); + }); } /// /// Verify that the links: diff --git a/src/Build.UnitTests/BackEnd/NodePackets_Tests.cs b/src/Build.UnitTests/BackEnd/NodePackets_Tests.cs index 98d9ffdd515..9287c529d6c 100644 --- a/src/Build.UnitTests/BackEnd/NodePackets_Tests.cs +++ b/src/Build.UnitTests/BackEnd/NodePackets_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -32,8 +32,7 @@ public void LogMessageConstructorNullBuildEvent() Assert.Throws(() => { LogMessagePacket packet = new LogMessagePacket(null); - } - ); + }); } /// @@ -215,7 +214,8 @@ public void TestTranslation() string _initialTargetOutputLogging = Environment.GetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING"); Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", "1"); - try { + try + { BuildEventArgs[] testArgs = new BuildEventArgs[] { new BuildFinishedEventArgs("Message", "Keyword", true), @@ -252,7 +252,9 @@ public void TestTranslation() CompareLogMessagePackets(packet, deserializedPacket); } - } finally { + } + finally + { Environment.SetEnvironmentVariable("MSBUILDTARGETOUTPUTLOGGING", _initialTargetOutputLogging); } } diff --git a/src/Build.UnitTests/BackEnd/NullMetadataTask.cs b/src/Build.UnitTests/BackEnd/NullMetadataTask.cs index 0a06cbdcbea..f30a88b9058 100644 --- a/src/Build.UnitTests/BackEnd/NullMetadataTask.cs +++ b/src/Build.UnitTests/BackEnd/NullMetadataTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/BackEnd/OnError_Tests.cs b/src/Build.UnitTests/BackEnd/OnError_Tests.cs index bc8849c9dfe..bdab3015c8c 100644 --- a/src/Build.UnitTests/BackEnd/OnError_Tests.cs +++ b/src/Build.UnitTests/BackEnd/OnError_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -22,7 +22,7 @@ namespace Microsoft.Build.UnitTests.BackEnd * * Tests that exercise the tag. */ - sealed public class OnError_Tests + public sealed class OnError_Tests { /* * Method: Basic @@ -558,8 +558,7 @@ public void OutOfOrderOnError() ")))); /* No build required */ - } - ); + }); } [Theory] @@ -583,7 +582,7 @@ public void ErrorWhenTaskFailsWithoutLoggingErrorEscapeHatch(string failureRespo else { logger.ErrorCount.ShouldBe(0); - logger.AssertLogContains( String.Format(MockLogger.GetString("TaskReturnedFalseButDidNotLogError"), "FailingTask") ); + logger.AssertLogContains(String.Format(MockLogger.GetString("TaskReturnedFalseButDidNotLogError"), "FailingTask")); } } @@ -598,10 +597,8 @@ public void ErrorWhenTaskFailsWithoutLoggingErrorEscapeHatch(string failureRespo public void PostBuildBasic() { MockLogger l = new MockLogger(); - Project p = new Project - ( - XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.Nowhere))) - ); + Project p = new Project( + XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.Nowhere)))); p.Build(new string[] { "Build" }, new ILogger[] { l }); @@ -622,10 +619,8 @@ public void PostBuildBasic() public void PostBuildOnSuccessWhereCompileFailed() { MockLogger l = new MockLogger(); - Project p = new Project - ( - XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.Compile))) - ); + Project p = new Project( + XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.Compile)))); p.Build(new string[] { "Build" }, new ILogger[] { l }); @@ -647,10 +642,8 @@ public void PostBuildOnSuccessWhereCompileFailed() public void PostBuildOnSuccessWhereGenerateSatellitesFailed() { MockLogger l = new MockLogger(); - Project p = new Project - ( - XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.GenerateSatellites))) - ); + Project p = new Project( + XmlReader.Create(new StringReader(PostBuildBuilder("On_Success", FailAt.GenerateSatellites)))); p.Build(new string[] { "Build" }, new ILogger[] { l }); @@ -672,10 +665,8 @@ public void PostBuildOnSuccessWhereGenerateSatellitesFailed() public void PostBuildAlwaysWhereCompileFailed() { MockLogger l = new MockLogger(); - Project p = new Project - ( - XmlReader.Create(new StringReader(PostBuildBuilder("Always", FailAt.Compile))) - ); + Project p = new Project( + XmlReader.Create(new StringReader(PostBuildBuilder("Always", FailAt.Compile)))); p.Build(new string[] { "Build" }, new ILogger[] { l }); @@ -697,10 +688,8 @@ public void PostBuildAlwaysWhereCompileFailed() public void PostBuildFinalOutputChangedWhereCompileFailed() { MockLogger l = new MockLogger(); - Project p = new Project - ( - XmlReader.Create(new StringReader(PostBuildBuilder("Final_Output_Changed", FailAt.Compile))) - ); + Project p = new Project( + XmlReader.Create(new StringReader(PostBuildBuilder("Final_Output_Changed", FailAt.Compile)))); p.Build(new string[] { "Build" }, new ILogger[] { l }); @@ -722,10 +711,8 @@ public void PostBuildFinalOutputChangedWhereCompileFailed() public void PostBuildFinalOutputChangedWhereGenerateSatellitesFailed() { MockLogger l = new MockLogger(); - Project p = new Project - ( - XmlReader.Create(new StringReader(PostBuildBuilder("Final_Output_Changed", FailAt.GenerateSatellites))) - ); + Project p = new Project( + XmlReader.Create(new StringReader(PostBuildBuilder("Final_Output_Changed", FailAt.GenerateSatellites)))); p.Build(new string[] { "Build" }, new ILogger[] { l }); @@ -756,11 +743,9 @@ private enum FailAt * conditions. * */ - private static string PostBuildBuilder - ( + private static string PostBuildBuilder( string controlFlag, // On_Success, Always, Final_Output_Changed - FailAt failAt - ) + FailAt failAt) { string compileStep = ""; if (FailAt.Compile == failAt) diff --git a/src/Build.UnitTests/BackEnd/ProcessIdTask.cs b/src/Build.UnitTests/BackEnd/ProcessIdTask.cs index ffc97d6f455..6dc7565ad85 100644 --- a/src/Build.UnitTests/BackEnd/ProcessIdTask.cs +++ b/src/Build.UnitTests/BackEnd/ProcessIdTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/BackEnd/RedirectConsoleWriter_Tests.cs b/src/Build.UnitTests/BackEnd/RedirectConsoleWriter_Tests.cs index a5d7d8be2a2..0e83218dce7 100644 --- a/src/Build.UnitTests/BackEnd/RedirectConsoleWriter_Tests.cs +++ b/src/Build.UnitTests/BackEnd/RedirectConsoleWriter_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.UnitTests/BackEnd/RequestBuilder_Tests.cs b/src/Build.UnitTests/BackEnd/RequestBuilder_Tests.cs index 2abb906a34c..ae711aeac89 100644 --- a/src/Build.UnitTests/BackEnd/RequestBuilder_Tests.cs +++ b/src/Build.UnitTests/BackEnd/RequestBuilder_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/BackEnd/ResultsCache_Tests.cs b/src/Build.UnitTests/BackEnd/ResultsCache_Tests.cs index 63479f7c6c3..60e08fe2019 100644 --- a/src/Build.UnitTests/BackEnd/ResultsCache_Tests.cs +++ b/src/Build.UnitTests/BackEnd/ResultsCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -145,8 +145,7 @@ public void TestRetrieveIncompleteResults() cache.AddResult(result); cache.GetResultForRequest(request); - } - ); + }); } [Fact] public void TestRetrieveSubsetResults() @@ -211,10 +210,10 @@ public static IEnumerable CacheSerializationTestData { get { - yield return new[] {new ResultsCache()}; + yield return new[] { new ResultsCache() }; - var request1 = new BuildRequest(1, 2, 3, new[] {"target1"}, null, BuildEventContext.Invalid, null); - var request2 = new BuildRequest(4, 5, 6, new[] {"target2"}, null, BuildEventContext.Invalid, null); + var request1 = new BuildRequest(1, 2, 3, new[] { "target1" }, null, BuildEventContext.Invalid, null); + var request2 = new BuildRequest(4, 5, 6, new[] { "target2" }, null, BuildEventContext.Invalid, null); var br1 = new BuildResult(request1); br1.AddResultsForTarget("target1", BuildResultUtilities.GetEmptySucceedingTargetResult()); @@ -222,7 +221,7 @@ public static IEnumerable CacheSerializationTestData var resultsCache = new ResultsCache(); resultsCache.AddResult(br1.Clone()); - yield return new[] {resultsCache}; + yield return new[] { resultsCache }; var br2 = new BuildResult(request2); br2.AddResultsForTarget("target2", BuildResultUtilities.GetEmptyFailingTargetResult()); @@ -231,7 +230,7 @@ public static IEnumerable CacheSerializationTestData resultsCache2.AddResult(br1.Clone()); resultsCache2.AddResult(br2.Clone()); - yield return new[] {resultsCache2}; + yield return new[] { resultsCache2 }; } } @@ -270,7 +269,7 @@ public void TestResultsCacheTranslation(object obj) #region Helper Methods - static internal bool AreResultsIdentical(BuildResult a, BuildResult b) + internal static bool AreResultsIdentical(BuildResult a, BuildResult b) { if (a.ConfigurationId != b.ConfigurationId) { @@ -314,7 +313,7 @@ static internal bool AreResultsIdentical(BuildResult a, BuildResult b) return true; } - static internal bool AreResultsIdenticalForTargets(BuildResult a, BuildResult b, string[] targets) + internal static bool AreResultsIdenticalForTargets(BuildResult a, BuildResult b, string[] targets) { foreach (string target in targets) { @@ -327,7 +326,7 @@ static internal bool AreResultsIdenticalForTargets(BuildResult a, BuildResult b, return true; } - static private bool AreResultsIdenticalForTarget(BuildResult a, BuildResult b, string target) + private static bool AreResultsIdenticalForTarget(BuildResult a, BuildResult b, string target) { if (!a.HasResultsForTarget(target) || !b.HasResultsForTarget(target)) { @@ -347,7 +346,7 @@ static private bool AreResultsIdenticalForTarget(BuildResult a, BuildResult b, s return true; } - static private bool AreItemsIdentical(IList a, IList b) + private static bool AreItemsIdentical(IList a, IList b) { // Exhaustive comparison of items should not be necessary since we don't merge on the item level. return a.Count == b.Count; diff --git a/src/Build.UnitTests/BackEnd/ReturnFailureWithoutLoggingErrorTask.cs b/src/Build.UnitTests/BackEnd/ReturnFailureWithoutLoggingErrorTask.cs index f630dc546de..9732fc3727a 100644 --- a/src/Build.UnitTests/BackEnd/ReturnFailureWithoutLoggingErrorTask.cs +++ b/src/Build.UnitTests/BackEnd/ReturnFailureWithoutLoggingErrorTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; #nullable disable diff --git a/src/Build.UnitTests/BackEnd/Scheduler_Tests.cs b/src/Build.UnitTests/BackEnd/Scheduler_Tests.cs index c6406b169b7..94079fa39f1 100644 --- a/src/Build.UnitTests/BackEnd/Scheduler_Tests.cs +++ b/src/Build.UnitTests/BackEnd/Scheduler_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -504,7 +504,7 @@ public void TestMaxNodeCountNodesNotExceededWithSomeOOPRequests2() public void SchedulerShouldHonorDisableInprocNode() { var s = new Scheduler(); - s.InitializeComponent(new MockHost(new BuildParameters {DisableInProcNode = true})); + s.InitializeComponent(new MockHost(new BuildParameters { DisableInProcNode = true })); s.ForceAffinityOutOfProc.ShouldBeTrue(); } @@ -544,7 +544,7 @@ public void TestProxyAffinityIsInProc() CreateConfiguration(1, "foo.csproj"); - BuildRequest request1 = CreateProxyBuildRequest(1, 1, new ProxyTargets(new Dictionary {{"foo", "bar"}}), null); + BuildRequest request1 = CreateProxyBuildRequest(1, 1, new ProxyTargets(new Dictionary { { "foo", "bar" } }), null); BuildRequestBlocker blocker = new BuildRequestBlocker(-1, Array.Empty(), new[] { request1 }); List response = new List(_scheduler.ReportRequestBlocked(1, blocker)); diff --git a/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs b/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs index e8b3812ab57..3a8b2877175 100644 --- a/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs +++ b/src/Build.UnitTests/BackEnd/SdkResolverLoader_Tests.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using Shouldly; using System.IO; @@ -48,8 +51,8 @@ public void AssertDefaultLoaderReturnsDefaultResolvers() var resolvers = loader.LoadAllResolvers(_loggingContext, new MockElementLocation("file")); - resolvers.Select(i => i.GetType().FullName).ShouldBe(new [] { typeof(DefaultSdkResolver).FullName }); - + resolvers.Select(i => i.GetType().FullName).ShouldBe(new[] { typeof(DefaultSdkResolver).FullName }); + _logger.ErrorCount.ShouldBe(0); _logger.WarningCount.ShouldBe(0); } @@ -342,7 +345,8 @@ public void SdkResolverLoaderHonorsIncludeDefaultEnvVar() Environment.SetEnvironmentVariable("MSBUILDINCLUDEDEFAULTSDKRESOLVER", "false"); SdkResolverLoader loader = new MockSdkResolverLoader() { - LoadResolversAction = (resolverPath, loggingContext, location, resolvers) => { + LoadResolversAction = (resolverPath, loggingContext, location, resolvers) => + { resolvers.Add(new MockSdkResolverWithAssemblyPath(resolverPath)); } }; diff --git a/src/Build.UnitTests/BackEnd/SdkResolverService_Tests.cs b/src/Build.UnitTests/BackEnd/SdkResolverService_Tests.cs index e63f9733bec..5dbc1c65571 100644 --- a/src/Build.UnitTests/BackEnd/SdkResolverService_Tests.cs +++ b/src/Build.UnitTests/BackEnd/SdkResolverService_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.BackEnd.SdkResolution; @@ -87,8 +87,7 @@ public void AssertResolutionWarnsIfResolvedVersionIsDifferentFromReferencedVersi sdk, "path", "2.0.0", - Enumerable.Empty() - )) + Enumerable.Empty())) }); var result = SdkResolverService.Instance.ResolveSdk(BuildEventContext.InvalidSubmissionId, sdk, _loggingContext, new MockElementLocation("file"), "sln", "projectPath", interactive: false, isRunningInVisualStudio: false, failOnUnresolvedSdk: true); @@ -266,8 +265,7 @@ public void CachingWrapperShouldWarnWhenMultipleVersionsAreReferenced() sdk, "path", "1.0.0", - Enumerable.Empty() - )); + Enumerable.Empty())); var service = new CachingSdkResolverService(); service.InitializeForTests( @@ -354,8 +352,7 @@ public void SdkResolverCanReturnNoPaths(bool includePropertiesAndItems) version: null, propertiesToAdd, itemsToAdd, - warnings: null - )); + warnings: null)); SdkResolverService.Instance.InitializeForTests(null, new List() { resolver }); @@ -381,7 +378,7 @@ public void SdkResultCanReturnPropertiesAndItems() Dictionary propertiesToAdd; Dictionary itemsToAdd; - + CreateMockSdkResultPropertiesAndItems(out propertiesToAdd, out itemsToAdd); var resolver = new SdkUtilities.ConfigurableMockSdkResolver( @@ -391,8 +388,7 @@ public void SdkResultCanReturnPropertiesAndItems() version: "1.0", propertiesToAdd, itemsToAdd, - warnings: null - )); + warnings: null)); SdkResolverService.Instance.InitializeForTests(null, new List() { resolver }); @@ -430,7 +426,7 @@ public void SdkResultCanReturnMultiplePaths(bool includePropertiesAndItems) var resolver = new SdkUtilities.ConfigurableMockSdkResolver( new SdkResultImpl( sdk, - new [] + new[] { expectedPath1, expectedPath2 @@ -438,8 +434,7 @@ public void SdkResultCanReturnMultiplePaths(bool includePropertiesAndItems) version: "1.0", propertiesToAdd, itemsToAdd, - warnings: null - )); + warnings: null)); SdkResolverService.Instance.InitializeForTests(null, new List() { resolver }); @@ -484,8 +479,7 @@ public void AssertResolutionWarnsIfResolvedVersionIsDifferentFromReferencedVersi version: "1.1", propertiesToAdd, itemsToAdd, - warnings: null - )); + warnings: null)); SdkResolverService.Instance.InitializeForTests(null, new List() { resolver }); @@ -522,8 +516,7 @@ public void CachingWrapperShouldOnlyResolveOnce() sdk, "path", "1.0.0", - Enumerable.Empty() - )); + Enumerable.Empty())); var service = new CachingSdkResolverService(); service.InitializeForTests( @@ -654,7 +647,7 @@ internal override IList GetResolversManifests(LoggingContex ElementLocation location) { var manifests = new List(); - foreach(SdkResolver resolver in _resolvers) + foreach (SdkResolver resolver in _resolvers) { SdkResolverManifest sdkResolverManifest = new SdkResolverManifest(resolver.Name, null, null); manifests.Add(sdkResolverManifest); @@ -664,8 +657,7 @@ internal override IList GetResolversManifests(LoggingContex SdkResolverManifest sdkResolverManifest = new SdkResolverManifest( pair.Resolver.Name, null, - new Regex(pair.ResolvableSdkPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(500)) - ); + new Regex(pair.ResolvableSdkPattern, RegexOptions.Compiled | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(500))); manifests.Add(sdkResolverManifest); } return manifests; @@ -717,7 +709,9 @@ public override SdkResultBase Resolve(SdkReference sdk, SdkResolverContextBase r resolverContext.Logger.LogMessage("MockSdkResolver1 running", MessageImportance.Normal); if (sdk.Name.StartsWith("1")) + { return factory.IndicateSuccess("resolverpath1", "version1"); + } return factory.IndicateFailure(new[] { "ERROR1" }); } @@ -734,9 +728,11 @@ public override SdkResultBase Resolve(SdkReference sdk, SdkResolverContextBase r resolverContext.Logger.LogMessage("MockSdkResolver2 running", MessageImportance.Normal); if (sdk.Name.StartsWith("2")) - return factory.IndicateSuccess("resolverpath2", "version2", new[] {"WARNING2"}); + { + return factory.IndicateSuccess("resolverpath2", "version2", new[] { "WARNING2" }); + } - return factory.IndicateFailure(new[] {"ERROR2"}, new[] {"WARNING2"}); + return factory.IndicateFailure(new[] { "ERROR2" }, new[] { "WARNING2" }); } } @@ -751,7 +747,9 @@ public override SdkResultBase Resolve(SdkReference sdk, SdkResolverContextBase r resolverContext.Logger.LogMessage("MockSdkResolverWithResolvableSdkPattern1 running", MessageImportance.Normal); if (sdk.Name.StartsWith("11")) + { return factory.IndicateSuccess("resolverpathwithresolvablesdkpattern1", "version3"); + } return factory.IndicateFailure(new[] { "ERROR3" }); } @@ -768,7 +766,9 @@ public override SdkResultBase Resolve(SdkReference sdk, SdkResolverContextBase r resolverContext.Logger.LogMessage("MockSdkResolverWithResolvableSdkPattern2 running", MessageImportance.Normal); if (sdk.Name.StartsWith("2")) + { return factory.IndicateSuccess("resolverpathwithresolvablesdkpattern2", "version4", new[] { "WARNING4" }); + } return factory.IndicateFailure(new[] { "ERROR4" }, new[] { "WARNING4" }); } @@ -790,7 +790,7 @@ public override SdkResultBase Resolve(SdkReference sdkReference, SdkResolverCont } if (resolverContext.State != null) { - return factory.IndicateSuccess((string) resolverContext.State, "1.0"); + return factory.IndicateSuccess((string)resolverContext.State, "1.0"); } resolverContext.State = Expected; diff --git a/src/Build.UnitTests/BackEnd/SdkResultOutOfProc_Tests.cs b/src/Build.UnitTests/BackEnd/SdkResultOutOfProc_Tests.cs index 55e51e5823b..7a2fedacf27 100644 --- a/src/Build.UnitTests/BackEnd/SdkResultOutOfProc_Tests.cs +++ b/src/Build.UnitTests/BackEnd/SdkResultOutOfProc_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.BackEnd.SdkResolution; @@ -255,8 +255,7 @@ private SdkResolver SetupSdkResolver(string projectFolder) { { "ItemFromResolver", new SdkResultItem("ItemValueFromResolver", null) } }, - warnings: null - )); + warnings: null)); EvaluationContext.TestOnlyHookOnCreate = context => { diff --git a/src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs b/src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs index 64682d0e709..802920e0bd4 100644 --- a/src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TargetBuilder_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -249,8 +249,7 @@ public void SkippedTargetsShouldOnlyInferOutputsOnce() Thread.Sleep(100); - string content = String.Format - ( + string content = String.Format( @" @@ -285,8 +284,7 @@ public void SkippedTargetsShouldOnlyInferOutputsOnce() ", - path - ); + path); Project p = new Project(XmlReader.Create(new StringReader(content))); p.Build(new string[] { "Build" }, new ILogger[] { logger }); diff --git a/src/Build.UnitTests/BackEnd/TargetEntry_Tests.cs b/src/Build.UnitTests/BackEnd/TargetEntry_Tests.cs index 7a1c46263d2..4bcb6fcd531 100644 --- a/src/Build.UnitTests/BackEnd/TargetEntry_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TargetEntry_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -84,8 +84,7 @@ public void TestConstructorNullTarget() BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config); Lookup lookup = new Lookup(new ItemDictionary(project.Items), new PropertyDictionary(project.Properties)); TargetEntry entry = new TargetEntry(requestEntry, this, null, lookup, null, TargetBuiltReason.None, _host, false); - } - ); + }); } /// /// Tests a constructor with a null lookup. @@ -99,8 +98,7 @@ public void TestConstructorNullLookup() BuildRequestConfiguration config = new BuildRequestConfiguration(1, new BuildRequestData("foo", new Dictionary(), "foo", Array.Empty(), null), "2.0"); BuildRequestEntry requestEntry = new BuildRequestEntry(CreateNewBuildRequest(1, new string[] { "foo" }), config); TargetEntry entry = new TargetEntry(requestEntry, this, new TargetSpecification("Empty", null), null, null, TargetBuiltReason.None, _host, false); - } - ); + }); } /// /// Tests a constructor with a null host. @@ -116,8 +114,7 @@ public void TestConstructorNullHost() Lookup lookup = new Lookup(new ItemDictionary(project.Items), new PropertyDictionary(project.Properties)); TargetEntry entry = new TargetEntry(requestEntry, this, new TargetSpecification("Empty", null), lookup, null, TargetBuiltReason.None, null, false); - } - ); + }); } /// /// Tests a valid constructor call. @@ -142,8 +139,7 @@ public void TestInvalidState_Execution() TargetEntry entry = CreateStandardTargetEntry(project, "Empty"); Assert.Equal(TargetEntryState.Dependencies, entry.State); ExecuteEntry(project, entry); - } - ); + }); } /// /// Tests incorrect invocation of GatherResults. @@ -157,8 +153,7 @@ public void TestInvalidState_Completed() TargetEntry entry = CreateStandardTargetEntry(project, "Empty"); Assert.Equal(TargetEntryState.Dependencies, entry.State); entry.GatherResults(); - } - ); + }); } /// /// Verifies that the dependencies specified for a target are returned by the GetDependencies call. diff --git a/src/Build.UnitTests/BackEnd/TargetResult_Tests.cs b/src/Build.UnitTests/BackEnd/TargetResult_Tests.cs index a4bcc061187..716d67fd83b 100644 --- a/src/Build.UnitTests/BackEnd/TargetResult_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TargetResult_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd; @@ -53,8 +53,7 @@ public void TestConstructorNullItems() Assert.Throws(() => { TargetResult result = new TargetResult(null, BuildResultUtilities.GetStopWithErrorResult()); - } - ); + }); } /// /// Tests a constructor with an exception passed. diff --git a/src/Build.UnitTests/BackEnd/TargetUpToDateChecker_Tests.cs b/src/Build.UnitTests/BackEnd/TargetUpToDateChecker_Tests.cs index ae3e2cd371c..4e870f62a04 100644 --- a/src/Build.UnitTests/BackEnd/TargetUpToDateChecker_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TargetUpToDateChecker_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -512,28 +512,24 @@ public FileWriteInfo(string path, DateTime lastWriteTime) /// The setup required here suggests that the TargetDependencyAnalyzer /// class should be refactored. /// - private DependencyAnalysisResult PerformDependencyAnalysisTestHelper - ( + private DependencyAnalysisResult PerformDependencyAnalysisTestHelper( FileWriteInfo[] filesToAnalyze, ItemDictionary itemsByName, string inputs, - string outputs - ) + string outputs) { ItemDictionary h1 = new ItemDictionary(); ItemDictionary h2 = new ItemDictionary(); return PerformDependencyAnalysisTestHelper(filesToAnalyze, itemsByName, inputs, outputs, out h1, out h2); } - private DependencyAnalysisResult PerformDependencyAnalysisTestHelper - ( + private DependencyAnalysisResult PerformDependencyAnalysisTestHelper( FileWriteInfo[] filesToAnalyze, ItemDictionary itemsByName, string inputs, string outputs, out ItemDictionary changedTargetInputs, - out ItemDictionary upToDateTargetInputs - ) + out ItemDictionary upToDateTargetInputs) { List filesToDelete = new List(); @@ -583,7 +579,10 @@ out ItemDictionary upToDateTargetInputs // finally clean up foreach (string path in filesToDelete) { - if (File.Exists(path)) File.Delete(path); + if (File.Exists(path)) + { + File.Delete(path); + } } ProjectCollection.GlobalProjectCollection.UnloadAllProjects(); @@ -596,14 +595,12 @@ out ItemDictionary upToDateTargetInputs [Fact] public void TestIsAnyOutOfDate1() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2001, 1, 1), /* output1 */ new DateTime(2001, 1, 1), /* output2 */ - false /* none out of date */ - ); + false); /* none out of date */ } /// @@ -612,14 +609,12 @@ public void TestIsAnyOutOfDate1() [Fact] public void TestIsAnyOutOfDate2() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2002, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2003, 1, 1), /* output1 */ new DateTime(2001, 1, 1), /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } /// @@ -628,14 +623,12 @@ public void TestIsAnyOutOfDate2() [Fact] public void TestIsAnyOutOfDate3() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2002, 1, 1), /* input2 */ new DateTime(2001, 1, 1), /* output1 */ new DateTime(2003, 1, 1), /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } /// @@ -644,14 +637,12 @@ public void TestIsAnyOutOfDate3() [Fact] public void TestIsAnyOutOfDate4() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2000, 1, 1), /* output1 */ new DateTime(2000, 1, 1), /* output2 */ - false /* none out of date */ - ); + false); /* none out of date */ } /// @@ -660,14 +651,12 @@ public void TestIsAnyOutOfDate4() [Fact] public void TestIsAnyOutOfDate5() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( null, /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ new DateTime(2002, 1, 1), /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } @@ -677,14 +666,12 @@ public void TestIsAnyOutOfDate5() [Fact] public void TestIsAnyOutOfDate6() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ null, /* input2 */ new DateTime(2002, 1, 1), /* output1 */ new DateTime(2002, 1, 1), /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } /// @@ -693,14 +680,12 @@ public void TestIsAnyOutOfDate6() [Fact] public void TestIsAnyOutOfDate7() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ null, /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } /// @@ -709,14 +694,12 @@ public void TestIsAnyOutOfDate7() [Fact] public void TestIsAnyOutOfDate8() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ null, /* output1 */ new DateTime(2002, 1, 1), /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } /// @@ -725,14 +708,12 @@ public void TestIsAnyOutOfDate8() [Fact] public void TestIsAnyOutOfDate9() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( null, /* input1 */ new DateTime(2000, 1, 1), /* input2 */ null, /* output1 */ new DateTime(2002, 1, 1), /* output2 */ - true /* some out of date */ - ); + true); /* some out of date */ } /// @@ -741,8 +722,7 @@ public void TestIsAnyOutOfDate9() [Fact] public void TestIsAnyOutOfDate10() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2002, 1, 1), /* input1 */ null, /* input2 */ new DateTime(2000, 1, 1), /* output1 */ @@ -751,8 +731,7 @@ public void TestIsAnyOutOfDate10() true, /* include input1 */ false, /* do not include input2 */ true, /* include output1 */ - true /* include output2 */ - ); + true); /* include output2 */ } /// @@ -761,8 +740,7 @@ public void TestIsAnyOutOfDate10() [Fact] public void TestIsAnyOutOfDate11() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ null, /* input2 */ new DateTime(2002, 1, 1), /* output1 */ @@ -771,8 +749,7 @@ public void TestIsAnyOutOfDate11() true, /* include input1 */ false, /* do not include input2 */ true, /* include output1 */ - true /* include output2 */ - ); + true); /* include output2 */ } /// @@ -781,8 +758,7 @@ public void TestIsAnyOutOfDate11() [Fact] public void TestIsAnyOutOfDate12() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2000, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ @@ -791,8 +767,7 @@ public void TestIsAnyOutOfDate12() true, /* include input1 */ true, /* include input2 */ true, /* include output1 */ - false /* do not include output2 */ - ); + false); /* do not include output2 */ } /// @@ -801,8 +776,7 @@ public void TestIsAnyOutOfDate12() [Fact] public void TestIsAnyOutOfDate13() { - IsAnyOutOfDateTestHelper - ( + IsAnyOutOfDateTestHelper( new DateTime(2000, 1, 1), /* input1 */ new DateTime(2003, 1, 1), /* input2 */ new DateTime(2002, 1, 1), /* output1 */ @@ -811,8 +785,7 @@ public void TestIsAnyOutOfDate13() true, /* include input1 */ true, /* include input2 */ true, /* include output1 */ - false /* do not include output2 */ - ); + false); /* do not include output2 */ } /// @@ -825,14 +798,12 @@ public void TestIsAnyOutOfDate13() /// /// /// - private void IsAnyOutOfDateTestHelper - ( + private void IsAnyOutOfDateTestHelper( DateTime? input1Time, DateTime? input2Time, DateTime? output1Time, DateTime? output2Time, - bool isUpToDate - ) + bool isUpToDate) { IsAnyOutOfDateTestHelper(input1Time, input2Time, output1Time, output2Time, isUpToDate, true, true, true, true); } @@ -847,8 +818,7 @@ bool isUpToDate /// /// /// - private void IsAnyOutOfDateTestHelper - ( + private void IsAnyOutOfDateTestHelper( DateTime? input1Time, DateTime? input2Time, DateTime? output1Time, @@ -857,8 +827,7 @@ private void IsAnyOutOfDateTestHelper bool includeInput1, bool includeInput2, bool includeOutput1, - bool includeOutput2 - ) + bool includeOutput2) { List inputs = new List(); List outputs = new List(); @@ -898,20 +867,50 @@ bool includeOutput2 File.SetLastWriteTime(output2, (DateTime)output2Time); } - if (includeInput1) inputs.Add(input1); - if (includeInput2) inputs.Add(input2); - if (includeOutput1) outputs.Add(output1); - if (includeOutput2) outputs.Add(output2); + if (includeInput1) + { + inputs.Add(input1); + } + + if (includeInput2) + { + inputs.Add(input2); + } + + if (includeOutput1) + { + outputs.Add(output1); + } + + if (includeOutput2) + { + outputs.Add(output2); + } DependencyAnalysisLogDetail detail; Assert.Equal(expectedAnyOutOfDate, TargetUpToDateChecker.IsAnyOutOfDate(out detail, Directory.GetCurrentDirectory(), inputs, outputs)); } finally { - if (File.Exists(input1)) File.Delete(input1); - if (File.Exists(input2)) File.Delete(input2); - if (File.Exists(output1)) File.Delete(output1); - if (File.Exists(output2)) File.Delete(output2); + if (File.Exists(input1)) + { + File.Delete(input1); + } + + if (File.Exists(input2)) + { + File.Delete(input2); + } + + if (File.Exists(output1)) + { + File.Delete(output1); + } + + if (File.Exists(output2)) + { + File.Delete(output2); + } } } @@ -925,7 +924,7 @@ bool includeOutput2 public void NewSymlinkOldDestinationIsUpToDate() { SimpleSymlinkInputCheck(symlinkWriteTime: New, - targetWriteTime: Old, + targetWriteTime: Old, outputWriteTime: Middle, expectedOutOfDate: false); } @@ -966,7 +965,7 @@ public void NewSymlinkNewDestinationIsNotUpToDate() [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] [SupportedOSPlatform("windows")] - static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, UInt32 dwFlags); + private static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, UInt32 dwFlags); [DllImport("kernel32.dll", SetLastError = true)] [SupportedOSPlatform("windows")] @@ -1036,9 +1035,20 @@ private void SimpleSymlinkInputCheck(DateTime symlinkWriteTime, DateTime targetW } finally { - if (File.Exists(inputTarget)) File.Delete(inputTarget); - if (File.Exists(inputSymlink)) File.Delete(inputSymlink); - if (File.Exists(outputTarget)) File.Delete(outputTarget); + if (File.Exists(inputTarget)) + { + File.Delete(inputTarget); + } + + if (File.Exists(inputSymlink)) + { + File.Delete(inputSymlink); + } + + if (File.Exists(outputTarget)) + { + File.Delete(outputTarget); + } } } } diff --git a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs index 7f390cdf98c..27775be9a60 100644 --- a/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs +++ b/src/Build.UnitTests/BackEnd/TaskBuilderTestTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build.UnitTests/BackEnd/TaskBuilder_Tests.cs b/src/Build.UnitTests/BackEnd/TaskBuilder_Tests.cs index c08997ed64c..09a8655bf48 100644 --- a/src/Build.UnitTests/BackEnd/TaskBuilder_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskBuilder_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs index a858d3fb9a4..994620b917a 100644 --- a/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskExecutionHost_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -156,8 +156,7 @@ public void ValidateNoParameters_MissingRequired() { var parameters = new Dictionary(StringComparer.OrdinalIgnoreCase); _host.SetTaskParameters(parameters); - } - ); + }); } /// /// Validate that setting a non-existent parameter fails, but does not throw an exception. @@ -489,8 +488,7 @@ public void TestSetItemParamDouble() Assert.Throws(() => { ValidateTaskParameterItems("ItemParam", "@(ItemListContainingTwoItems)", _twoItems); - } - ); + }); } /// /// Validate that setting an item with a string results in an item with the evaluated include set to the string. @@ -648,8 +646,7 @@ public void TestExecuteThrow() Assert.True(_host.SetTaskParameters(parameters)); _host.Execute(); - } - ); + }); } #endregion @@ -931,8 +928,7 @@ public void TestArrayListParameter() Assert.Throws(() => { ValidateOutputItems("ArrayListOutput", Array.Empty()); - } - ); + }); } /// /// Attempts to gather outputs from a non-existent output. This should fail. @@ -943,8 +939,7 @@ public void TestNonexistantOutput() Assert.Throws(() => { Assert.False(_host.GatherTaskOutputs("NonExistentOutput", ElementLocation.Create(".", 1, 1), true, "output")); - } - ); + }); } /// /// object[] should not be a supported output type. @@ -955,8 +950,7 @@ public void TestOutputObjectArrayToProperty() Assert.Throws(() => { ValidateOutputProperty("ObjectArrayOutput", ""); - } - ); + }); } #endregion @@ -988,8 +982,7 @@ public void TestTaskResolutionFailureWithUsingTask() TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)); ProjectInstance project = CreateTestProject(); - _host.InitializeForTask - ( + _host.InitializeForTask( this, tlc, project, @@ -1001,12 +994,10 @@ public void TestTaskResolutionFailureWithUsingTask() null, #endif false, - CancellationToken.None - ); + CancellationToken.None); _host.FindTask(null); _host.InitializeForBatch(new TaskLoggingContext(_loggingService, tlc.BuildEventContext), _bucket, null); - } - ); + }); } /// /// Test that specifying a task with no using task logs an error, but does not throw. @@ -1019,8 +1010,7 @@ public void TestTaskResolutionFailureWithNoUsingTask() TargetLoggingContext tlc = new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)); ProjectInstance project = CreateTestProject(); - _host.InitializeForTask - ( + _host.InitializeForTask( this, tlc, project, @@ -1032,8 +1022,7 @@ public void TestTaskResolutionFailureWithNoUsingTask() null, #endif false, - CancellationToken.None - ); + CancellationToken.None); _host.FindTask(null); _host.InitializeForBatch(new TaskLoggingContext(_loggingService, tlc.BuildEventContext), _bucket, null); @@ -1043,7 +1032,7 @@ public void TestTaskResolutionFailureWithNoUsingTask() #endregion #region ITestTaskHost Members - #pragma warning disable xUnit1013 +#pragma warning disable xUnit1013 /// /// Records that a parameter was set on the task. @@ -1125,7 +1114,7 @@ public bool BuildProjectFile(string projectFileName, string[] targetNames, IDict throw new NotImplementedException(); } - #pragma warning restore xUnit1013 +#pragma warning restore xUnit1013 #endregion #region Validation Routines @@ -1167,8 +1156,7 @@ private void InitializeHost(bool throwOnExecute) taskFactory.ThrowOnExecute = throwOnExecute; string taskName = "TaskBuilderTestTask"; (_host as TaskExecutionHost)._UNITTESTONLY_TaskFactoryWrapper = new TaskFactoryWrapper(taskFactory, loadedType, taskName, null); - _host.InitializeForTask - ( + _host.InitializeForTask( this, tlc, project, @@ -1180,8 +1168,7 @@ private void InitializeHost(bool throwOnExecute) null, #endif false, - CancellationToken.None - ); + CancellationToken.None); ProjectTaskInstance taskInstance = project.Targets["foo"].Tasks.First(); TaskLoggingContext talc = tlc.LogTaskBatchStarted(".", taskInstance); diff --git a/src/Build.UnitTests/BackEnd/TaskHostConfiguration_Tests.cs b/src/Build.UnitTests/BackEnd/TaskHostConfiguration_Tests.cs index c885fbea105..0d4a6fc7cba 100644 --- a/src/Build.UnitTests/BackEnd/TaskHostConfiguration_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskHostConfiguration_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -63,8 +63,7 @@ public void ConstructorWithNullName() warningsAsErrors: null, warningsNotAsErrors: null, warningsAsMessages: null); - } - ); + }); } /// /// Test that an exception is thrown when the task name is empty. @@ -99,8 +98,7 @@ public void ConstructorWithEmptyName() warningsAsErrors: null, warningsNotAsErrors: null, warningsAsMessages: null); - } - ); + }); } /// /// Test that an exception is thrown when the path to the task assembly is null @@ -135,8 +133,7 @@ public void ConstructorWithNullLocation() warningsAsErrors: null, warningsNotAsErrors: null, warningsAsMessages: null); - } - ); + }); } #if !FEATURE_ASSEMBLYLOADCONTEXT @@ -173,8 +170,7 @@ public void ConstructorWithEmptyLocation() warningsAsErrors: null, warningsNotAsErrors: null, warningsAsMessages: null); - } - ); + }); } #endif diff --git a/src/Build.UnitTests/BackEnd/TaskHostFactory_Tests.cs b/src/Build.UnitTests/BackEnd/TaskHostFactory_Tests.cs index 69c142d7712..6688e687a44 100644 --- a/src/Build.UnitTests/BackEnd/TaskHostFactory_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskHostFactory_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; using Microsoft.Build.Execution; @@ -16,7 +17,7 @@ namespace Microsoft.Build.Engine.UnitTests.BackEnd { public sealed class TaskHostFactory_Tests { - ITestOutputHelper _output; + private ITestOutputHelper _output; public TaskHostFactory_Tests(ITestOutputHelper testOutputHelper) { @@ -89,6 +90,6 @@ public void VariousParameterTypesCanBeTransmittedToAndRecievedFromTaskHost() TransientTestProjectWithFiles project = env.CreateTestProjectWithFiles(projectContents); ProjectInstance projectInstance = new(project.ProjectFile); projectInstance.Build(new[] { new MockLogger(env.Output) }).ShouldBeTrue(); - } + } } } diff --git a/src/Build.UnitTests/BackEnd/TaskHostTaskCancelled_Tests.cs b/src/Build.UnitTests/BackEnd/TaskHostTaskCancelled_Tests.cs index df7e6dafa41..7c0369ec0ae 100644 --- a/src/Build.UnitTests/BackEnd/TaskHostTaskCancelled_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskHostTaskCancelled_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Xunit; diff --git a/src/Build.UnitTests/BackEnd/TaskHostTaskComplete_Tests.cs b/src/Build.UnitTests/BackEnd/TaskHostTaskComplete_Tests.cs index 1b46cfd3090..ec73cdbc6d9 100644 --- a/src/Build.UnitTests/BackEnd/TaskHostTaskComplete_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskHostTaskComplete_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/BackEnd/TaskHost_Tests.cs b/src/Build.UnitTests/BackEnd/TaskHost_Tests.cs index 7733f0aac37..821e0e2644e 100644 --- a/src/Build.UnitTests/BackEnd/TaskHost_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskHost_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -236,8 +236,7 @@ public void TestLogErrorEventNull() Assert.Throws(() => { _taskHost.LogErrorEvent(null); - } - ); + }); } /// /// Test that a null warning event will cause an exception @@ -248,8 +247,7 @@ public void TestLogWarningEventNull() Assert.Throws(() => { _taskHost.LogWarningEvent(null); - } - ); + }); } /// /// Test that a null message event will cause an exception @@ -260,8 +258,7 @@ public void TestLogMessageEventNull() Assert.Throws(() => { _taskHost.LogMessageEvent(null); - } - ); + }); } /// /// Test that a null custom event will cause an exception @@ -272,8 +269,7 @@ public void TestLogCustomEventNull() Assert.Throws(() => { _taskHost.LogCustomEvent(null); - } - ); + }); } /// /// Test that errors are logged properly @@ -808,10 +804,8 @@ internal class MyCustomMessageEvent : BuildMessageEventArgs /// /// Constructor /// - internal MyCustomMessageEvent - ( - string message - ) + internal MyCustomMessageEvent( + string message) : base(message, null, null, MessageImportance.High) { } @@ -868,10 +862,8 @@ internal class MyCustomBuildErrorEventArgs : BuildErrorEventArgs /// /// Constructor /// - internal MyCustomBuildErrorEventArgs - ( - string message - ) + internal MyCustomBuildErrorEventArgs( + string message) : base(null, null, null, 0, 0, 0, 0, message, null, null) { } @@ -907,10 +899,8 @@ internal class MyCustomBuildWarningEventArgs : BuildWarningEventArgs /// /// Constructor /// - internal MyCustomBuildWarningEventArgs - ( - string message - ) + internal MyCustomBuildWarningEventArgs( + string message) : base(null, null, null, 0, 0, 0, 0, message, null, null) { } @@ -945,10 +935,8 @@ internal class MyCustomMessageEventNotSerializable : BuildMessageEventArgs /// /// Constructor /// - internal MyCustomMessageEventNotSerializable - ( - string message - ) + internal MyCustomMessageEventNotSerializable( + string message) : base(message, null, null, MessageImportance.High) { } @@ -1005,10 +993,8 @@ internal class MyCustomBuildErrorEventArgsNotSerializable : BuildErrorEventArgs /// /// Constructor /// - internal MyCustomBuildErrorEventArgsNotSerializable - ( - string message - ) + internal MyCustomBuildErrorEventArgsNotSerializable( + string message) : base(null, null, null, 0, 0, 0, 0, message, null, null) { } @@ -1043,10 +1029,8 @@ internal class MyCustomBuildWarningEventArgsNotSerializable : BuildWarningEventA /// /// Constructor /// - internal MyCustomBuildWarningEventArgsNotSerializable - ( - string message - ) + internal MyCustomBuildWarningEventArgsNotSerializable( + string message) : base(null, null, null, 0, 0, 0, 0, message, null, null) { } diff --git a/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs b/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs index 7138a700b21..025477ab3bd 100644 --- a/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs +++ b/src/Build.UnitTests/BackEnd/TaskRegistry_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -358,26 +358,22 @@ public void RetrieveFromCacheTaskDoesNotExist_ExactMatch() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // Not in registry, so shouldn't match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: null, architecture: null, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // Still not in registry, so shouldn't match this time either -- and we should pull from the cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: null, architecture: null, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: true - ); + shouldBeRetrievedFromCache: true); } /// @@ -398,26 +394,22 @@ public void RetrieveFromCacheTaskDoesNotExist_FuzzyMatch() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // Not in registry, so shouldn't match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, architecture: null, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // Still not in registry, so shouldn't match this time either -- and we should pull from the cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, architecture: null, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: true - ); + shouldBeRetrievedFromCache: true); } /// @@ -440,26 +432,22 @@ public void RetrieveFromCacheMatchingTaskDoesNotExist_FuzzyMatch() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // Not in registry, so shouldn't match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: "CLR2", architecture: "*", shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // Still not in registry, so shouldn't match this time either -- and we should pull from the cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: "CLR2", architecture: "*", shouldBeRetrieved: false, - shouldBeRetrievedFromCache: true - ); + shouldBeRetrievedFromCache: true); } /// @@ -482,26 +470,22 @@ public void RetrieveFromCacheMatchingTaskDoesNotExistOnFirstCallButDoesOnSecond( TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // Not in registry, so shouldn't match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: "CLR2", architecture: "*", shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // Still not in registry, so shouldn't match this time either -- and we should pull from the cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, architecture: null, shouldBeRetrieved: true, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); } /// @@ -524,59 +508,49 @@ public void RetrieveFromCacheMatchingExactParameters() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // no parameters - no match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: null, architecture: null, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // parameters that would be a successful fuzzy match - no match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, architecture: XMakeAttributes.MSBuildArchitectureValues.any, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // parameters that are a successful exact match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, architecture: XMakeAttributes.MSBuildArchitectureValues.x86, shouldBeRetrieved: true, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // parameters that do not match - should not retrieve - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: XMakeAttributes.MSBuildRuntimeValues.clr2, architecture: XMakeAttributes.MSBuildArchitectureValues.x64, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // exact match #2 -- should get it from the cache this time - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: true, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, architecture: XMakeAttributes.MSBuildArchitectureValues.x86, shouldBeRetrieved: true, - shouldBeRetrievedFromCache: true - ); + shouldBeRetrievedFromCache: true); } /// @@ -607,29 +581,25 @@ public void RetrieveFromCacheMatchingExactParameters_AdditionalParameters() taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.x86); taskParameters.Add("Foo", "Bar"); - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, true /* exact match */, taskParameters, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // However, it should still match itself -- so if we try again, we should get the "no match" // back from the cache this time. - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, true /* exact match */, taskParameters, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: true - ); + shouldBeRetrievedFromCache: true); } [Theory] - [InlineData("x64","true","x86","", "x64")] // x64 wins + [InlineData("x64", "true", "x86", "", "x64")] // x64 wins [InlineData("x64", "false", "x86", "true", "x86")] // x86 wins public void OverriddenTask_AlwaysWins(string firstArch, string firstOverride, string secondArch, string secondOverride, string expectedArch) { @@ -651,8 +621,7 @@ public void OverriddenTask_AlwaysWins(string firstArch, string firstOverride, st TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // no parameters - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, @@ -660,12 +629,10 @@ public void OverriddenTask_AlwaysWins(string firstArch, string firstOverride, st shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: expectedArch - ); + expectedArchitecture: expectedArch); // no parameters, fuzzy match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, @@ -673,8 +640,7 @@ public void OverriddenTask_AlwaysWins(string firstArch, string firstOverride, st shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: expectedArch - ); + expectedArchitecture: expectedArch); } [Fact] @@ -738,8 +704,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // no parameters - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, @@ -747,12 +712,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters() shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that are a successful exact match - should retrieve from cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -760,12 +723,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that would be a successful fuzzy match - should still be retrieved from the cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -773,23 +734,19 @@ public void RetrieveFromCacheFuzzyMatchingParameters() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that do not match -- but would match the previous fuzzy match request. Should NOT retrieve anything - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, architecture: XMakeAttributes.MSBuildArchitectureValues.x64, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // and another fuzzy match -- should still be pulling from the cache. - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.any, @@ -797,8 +754,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); } /// @@ -821,8 +777,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_RecoverFromFailure() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // no parameters - should retrieve the record - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, @@ -830,23 +785,19 @@ public void RetrieveFromCacheFuzzyMatchingParameters_RecoverFromFailure() shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that do not match at all - shouldn't retrieve anything - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr2, architecture: XMakeAttributes.MSBuildArchitectureValues.x86, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // parameters that are a successful match - should retrieve from the cache this time - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -854,8 +805,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_RecoverFromFailure() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); } /// @@ -884,8 +834,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // no parameters -- gets the first one (CLR4|x86) - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: null, @@ -893,12 +842,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that are a successful exact match for CLR4|x86 -- should come from cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -906,12 +853,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that would be a successful fuzzy match for either, so should get the one in the cache (CLR4|x86) - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -919,12 +864,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // parameters that match *|x64 - should retrieve that - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -932,12 +875,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64); // match CLR4|x86 again - comes from the cache - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.any, @@ -945,12 +886,10 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // match *|x64 again - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr2, @@ -958,23 +897,19 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64); // CLR2|x86 should not match either task record - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr2, architecture: XMakeAttributes.MSBuildArchitectureValues.x86, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // match *|x64 again -- should still be a cache hit - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr2, @@ -982,8 +917,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64); } /// @@ -1014,8 +948,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks_PreferCa TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // CLR4|x64 -- should be fulfilled by *|x64 - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -1023,13 +956,11 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks_PreferCa shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64); // CLR4|* -- could be filled by either, would normally be filled by CLR4|x86 (since it was registered first), // but since *|x64 is in the cache already, we return that one. - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -1037,8 +968,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_MultipleUsingTasks_PreferCa shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.any, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x64); } /// @@ -1061,8 +991,7 @@ public void RetrieveFromCacheFuzzyMatchingParameters_ExactMatches() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); // CLR4|* should match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -1070,23 +999,19 @@ public void RetrieveFromCacheFuzzyMatchingParameters_ExactMatches() shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // CLR4|x64 should not match - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, architecture: XMakeAttributes.MSBuildArchitectureValues.x64, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: false - ); + shouldBeRetrievedFromCache: false); // try CLR4|* again -- should resolve correctly from the cache. - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, @@ -1094,19 +1019,16 @@ public void RetrieveFromCacheFuzzyMatchingParameters_ExactMatches() shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // try CLR4|x64 again -- should also come from the catch (but needless to say, still not be a match) - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, exactMatchRequired: false, runtime: XMakeAttributes.MSBuildRuntimeValues.clr4, architecture: XMakeAttributes.MSBuildArchitectureValues.x64, shouldBeRetrieved: false, - shouldBeRetrievedFromCache: true - ); + shouldBeRetrievedFromCache: true); } /// @@ -1136,28 +1058,24 @@ public void RetrieveFromCacheFuzzyMatchingParameters_AdditionalParameters() taskParameters.Add(XMakeAttributes.architecture, XMakeAttributes.MSBuildArchitectureValues.x86); taskParameters.Add("Foo", "Bar"); - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, false /* fuzzy match */, taskParameters, shouldBeRetrieved: true, shouldBeRetrievedFromCache: false, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); // And if we try again, we should get it from the cache this time. - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, false /* fuzzy match */, taskParameters, shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); taskParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); taskParameters.Add(XMakeAttributes.runtime, XMakeAttributes.MSBuildRuntimeValues.clr4); @@ -1167,16 +1085,14 @@ public void RetrieveFromCacheFuzzyMatchingParameters_AdditionalParameters() // Even with a different value to the additional parameter, because it's a fuzzy equals and because all // our equivalence check looks for is runtime and architecture, it still successfully retrieves the // existing record from the cache. - RetrieveAndValidateRegisteredTaskRecord - ( + RetrieveAndValidateRegisteredTaskRecord( registry, false /* fuzzy match */, taskParameters, shouldBeRetrieved: true, shouldBeRetrievedFromCache: true, expectedRuntime: XMakeAttributes.MSBuildRuntimeValues.clr4, - expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86 - ); + expectedArchitecture: XMakeAttributes.MSBuildArchitectureValues.x86); } #endregion @@ -1319,7 +1235,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); element.TaskFactory = typeof(NullTaskTypeTaskFactory).FullName; @@ -1328,7 +1244,7 @@ public void TaskFactoryWithNullTaskTypeLogsError() TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); InvalidProjectFileException exception = Should.Throw(() => registry.GetRegisteredTask("Task1", "none", null, false, new TargetLoggingContext(_loggingService, new BuildEventContext(1, 1, BuildEventContext.InvalidProjectContextId, 1)), ElementLocation.Create("none", 1, 2))); - + exception.ErrorCode.ShouldBe("MSB4175"); exception.Message.ShouldContain("The task factory must return a value for the \"TaskType\" property."); @@ -1464,8 +1380,7 @@ public void RandomTypeOnParameter() List elementList = CreateParameterElementWithAttributes(output, required, type); CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify the following types work when registered as input parameters @@ -1508,8 +1423,7 @@ public void BadArrayInputOnInputParameter() List elementList = CreateParameterElementWithAttributes(output, required, type); TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify that value types and (string and ITaskItem classes) can be registered as input parameters @@ -1555,8 +1469,7 @@ public void BadScalarInputOnInputParameterDerivedFromITask() List elementList = CreateParameterElementWithAttributes(output, required, type); TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify when a random scalar input class is attempted to be registered that we get an invalid project file exceptions. @@ -1574,8 +1487,7 @@ public void BadScalarInputOnInputParameter() List elementList = CreateParameterElementWithAttributes(output, required, type); TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify the expected output parameters are supported @@ -1646,8 +1558,7 @@ public void BadOutputParameter() List elementList = CreateParameterElementWithAttributes(output, required, type); TaskRegistry registry = CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify when the output parameter is not set that it defaults to false @@ -1694,8 +1605,7 @@ public void RandomOutput() List elementList = CreateParameterElementWithAttributes(output, required, type); CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify an empty required value results in a default value of false @@ -1742,8 +1652,7 @@ public void RandomRequired() List elementList = CreateParameterElementWithAttributes(output, required, type); CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify that expansion of the attributes works. @@ -1900,8 +1809,7 @@ public void RandomEvaluate() List elementList = CreateTaskBodyElementWithAttributes(evaluate, ""); CreateTaskRegistryAndRegisterTasks(elementList); Assert.True(false); - } - ); + }); } /// /// Verify when false is passed to evaluate value results in a false value being set @@ -1984,17 +1892,16 @@ public static IEnumerable TaskRegistryTranslationTestData new PropertyDictionary(toolsetGlobalProperties), new Dictionary { - {"1.0", new SubToolset("1.0", new PropertyDictionary(subToolsetProperties))}, - {"2.0", new SubToolset("2.0", new PropertyDictionary(subToolsetProperties))} + {"1.0", new SubToolset("1.0", new PropertyDictionary(subToolsetProperties)) }, + {"2.0", new SubToolset("2.0", new PropertyDictionary(subToolsetProperties)) } }, "motp", "dotv", new Dictionary { - {"a", new ProjectImportPathMatch("a", new List {"b", "c"})}, - {"d", new ProjectImportPathMatch("d", new List {"e", "f"})} - } - ); + {"a", new ProjectImportPathMatch("a", new List {"b", "c"}) }, + {"d", new ProjectImportPathMatch("d", new List {"e", "f"}) } + }); ProjectRootElement project = ProjectRootElement.Create(); @@ -2090,16 +1997,14 @@ public void TaskRegistryCanSerializeViaTranslator(List /// - that the record that was retrieved had the expected runtime and architecture /// values as its factory parameters. /// - private void RetrieveAndValidateRegisteredTaskRecord - ( + private void RetrieveAndValidateRegisteredTaskRecord( TaskRegistry registry, bool exactMatchRequired, Dictionary taskParameters, bool shouldBeRetrieved, bool shouldBeRetrievedFromCache, string expectedRuntime, - string expectedArchitecture - ) + string expectedArchitecture) { bool retrievedFromCache; var record = registry.GetTaskRegistrationRecord(TestTaskName, null, taskParameters, exactMatchRequired, _targetLoggingContext, _elementLocation, out retrievedFromCache); @@ -2134,8 +2039,7 @@ string expectedArchitecture /// - that the record that was retrieved had the expected runtime and architecture /// values as its factory parameters. /// - private void RetrieveAndValidateRegisteredTaskRecord - ( + private void RetrieveAndValidateRegisteredTaskRecord( TaskRegistry registry, bool exactMatchRequired, string runtime, @@ -2143,8 +2047,7 @@ private void RetrieveAndValidateRegisteredTaskRecord bool shouldBeRetrieved, bool shouldBeRetrievedFromCache, string expectedRuntime, - string expectedArchitecture - ) + string expectedArchitecture) { Dictionary parameters = null; if (runtime != null || architecture != null) @@ -2281,8 +2184,7 @@ internal TaskRegistry CreateTaskRegistryAndRegisterTasks(List e.ResponseFilePath); } - + [Fact] public void RoundtripCriticalBuildMessageEventArgs() { diff --git a/src/Build.UnitTests/BuildResultUtilities.cs b/src/Build.UnitTests/BuildResultUtilities.cs index b637deaee69..e587fbef48f 100644 --- a/src/Build.UnitTests/BuildResultUtilities.cs +++ b/src/Build.UnitTests/BuildResultUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd; @@ -24,7 +24,7 @@ public static TargetResult GetEmptySucceedingTargetResult() public static TargetResult GetNonEmptySucceedingTargetResult() { - return new TargetResult(new TaskItem[1] { new TaskItem("i", "v")}, BuildResultUtilities.GetSuccessResult()); + return new TargetResult(new TaskItem[1] { new TaskItem("i", "v") }, BuildResultUtilities.GetSuccessResult()); } public static WorkUnitResult GetSuccessResult() diff --git a/src/Build.UnitTests/ChangeWaves_Tests.cs b/src/Build.UnitTests/ChangeWaves_Tests.cs index 010c83fa619..ebb131da07d 100644 --- a/src/Build.UnitTests/ChangeWaves_Tests.cs +++ b/src/Build.UnitTests/ChangeWaves_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Xunit; using Shouldly; @@ -15,9 +15,9 @@ namespace Microsoft.Build.Engine.UnitTests { - sealed public class ChangeWaves_Tests + public sealed class ChangeWaves_Tests { - ITestOutputHelper _output; + private ITestOutputHelper _output; public ChangeWaves_Tests(ITestOutputHelper output) { _output = output; diff --git a/src/Build.UnitTests/Collections/CopyOnReadEnumerable_Tests.cs b/src/Build.UnitTests/Collections/CopyOnReadEnumerable_Tests.cs index 59c625f5ddd..dd12ad7f9ec 100644 --- a/src/Build.UnitTests/Collections/CopyOnReadEnumerable_Tests.cs +++ b/src/Build.UnitTests/Collections/CopyOnReadEnumerable_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Collections; diff --git a/src/Build.UnitTests/Collections/CopyOnWritePropertyDictionary_Tests.cs b/src/Build.UnitTests/Collections/CopyOnWritePropertyDictionary_Tests.cs index 6e287228194..f204e2b163f 100644 --- a/src/Build.UnitTests/Collections/CopyOnWritePropertyDictionary_Tests.cs +++ b/src/Build.UnitTests/Collections/CopyOnWritePropertyDictionary_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Collections; diff --git a/src/Build.UnitTests/Collections/MSBuildNameIgnoreCaseComparer_Tests.cs b/src/Build.UnitTests/Collections/MSBuildNameIgnoreCaseComparer_Tests.cs index 98458c643a6..f7b81000d87 100644 --- a/src/Build.UnitTests/Collections/MSBuildNameIgnoreCaseComparer_Tests.cs +++ b/src/Build.UnitTests/Collections/MSBuildNameIgnoreCaseComparer_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Collections; @@ -83,8 +83,7 @@ public void InvalidValue2() Assert.Throws(() => { MSBuildNameIgnoreCaseComparer.Default.Equals("x", "y", -1, 0); - } - ); + }); } /// /// Invalid small end @@ -95,8 +94,7 @@ public void InvalidValue4() Assert.Throws(() => { MSBuildNameIgnoreCaseComparer.Default.Equals("x", "y", 0, -1); - } - ); + }); } /// /// Invalid large end @@ -107,8 +105,7 @@ public void InvalidValue5() Assert.Throws(() => { MSBuildNameIgnoreCaseComparer.Default.Equals("x", "y", 0, 2); - } - ); + }); } /// /// End past the end of other string diff --git a/src/Build.UnitTests/Collections/MultiDictionary_Tests.cs b/src/Build.UnitTests/Collections/MultiDictionary_Tests.cs index ae9415481aa..75d3029570a 100644 --- a/src/Build.UnitTests/Collections/MultiDictionary_Tests.cs +++ b/src/Build.UnitTests/Collections/MultiDictionary_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Collections; diff --git a/src/Build.UnitTests/Collections/OMcollections_tests.cs b/src/Build.UnitTests/Collections/OMcollections_tests.cs index 19b4c44ab26..dbc03d5df13 100644 --- a/src/Build.UnitTests/Collections/OMcollections_tests.cs +++ b/src/Build.UnitTests/Collections/OMcollections_tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Collections; @@ -116,7 +116,7 @@ public void BasicItemDictionary() enumerator.MoveNext().ShouldBeFalse(); Should.Throw(() => { - object o = ((IEnumerator) enumerator).Current; + object o = ((IEnumerator)enumerator).Current; }); enumerator.Current.ShouldBeNull(); } @@ -241,8 +241,7 @@ public void ReadOnlyCollectionNullBacking() Assert.Throws(() => { new ReadOnlyCollection(null); - } - ); + }); } /// /// Verify non generic enumeration does not recurse diff --git a/src/Build.UnitTests/ConfigureableForwardingLogger_Tests.cs b/src/Build.UnitTests/ConfigureableForwardingLogger_Tests.cs index 3e17a8bf6ef..1612c82f6a5 100644 --- a/src/Build.UnitTests/ConfigureableForwardingLogger_Tests.cs +++ b/src/Build.UnitTests/ConfigureableForwardingLogger_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/ConsoleLogger_Tests.cs b/src/Build.UnitTests/ConsoleLogger_Tests.cs index be8dfc1cdb2..622e8c81c88 100644 --- a/src/Build.UnitTests/ConsoleLogger_Tests.cs +++ b/src/Build.UnitTests/ConsoleLogger_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build.UnitTests/ConsoleOutputAlignerTests.cs b/src/Build.UnitTests/ConsoleOutputAlignerTests.cs index 8c5db6c2e03..87dc12b963d 100644 --- a/src/Build.UnitTests/ConsoleOutputAlignerTests.cs +++ b/src/Build.UnitTests/ConsoleOutputAlignerTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd.Logging; @@ -75,8 +75,8 @@ public void NoAlignPrefixAlreadyWritten_NotChanged(string input) } [Theory] - [InlineData("", "123")] - [InlineData(" ", "12")] + [InlineData("", "123")] + [InlineData(" ", "12")] [InlineData(" ", "1")] public void SmallerThanBuffer_NotAligned(string indent, string input) { @@ -107,7 +107,7 @@ public void BiggerThanBuffer_AlignedWithIndent(string indent, string input, stri [InlineData(" ", "12345678", " 12\n" + " 34\n" + " 56\n" + - " 78\n" )] + " 78\n")] [InlineData(" ", "1234", " 1\n" + " 2\n" + " 3\n" + @@ -311,7 +311,7 @@ public void TabsMakesItJustOverLimit_IndentAndAlign(string prefix, string input, // +----+----+---+---+---+---+---+---+ // | b | | | | | | | | // +----+----+---+---+---+---+---+---+ - [InlineData("", "\t1\na\tb", "\t\n1\na\t\nb\n", 8, false)] + [InlineData("", "\t1\na\tb", "\t\n1\na\t\nb\n", 8, false)] // +---+---+---+----+---+---+---+---+----+ // | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | // +---+---+---+----+---+---+---+---+----+ diff --git a/src/Build.UnitTests/Construction/ElementLocation_Tests.cs b/src/Build.UnitTests/Construction/ElementLocation_Tests.cs index 38dcb87dd5d..2a5130e7bde 100644 --- a/src/Build.UnitTests/Construction/ElementLocation_Tests.cs +++ b/src/Build.UnitTests/Construction/ElementLocation_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Exceptions; @@ -212,8 +212,7 @@ public void ConstructorWithNegativeIndicesTest1() Assert.Throws(() => { ElementLocation.Create("file", -1, 2); - } - ); + }); } /// /// Tests constructor specifying file, line, negative column @@ -224,8 +223,7 @@ public void ConstructorWithNegativeIndicesTest2n() Assert.Throws(() => { ElementLocation.Create("file", 1, -2); - } - ); + }); } /// /// Tests constructor with invalid null file. @@ -355,8 +353,7 @@ public void SaveReadOnly1() doc.Load(_pathToCommonTargets); Assert.True(doc.IsReadOnly); doc.Save(FileUtilities.GetTemporaryFile()); - } - ); + }); } /// @@ -370,7 +367,8 @@ public void SaveReadOnly2() var doc = new XmlDocumentWithLocation(loadAsReadOnly: true); doc.Load(_pathToCommonTargets); Assert.True(doc.IsReadOnly); - Assert.Throws(() => { + Assert.Throws(() => + { doc.Save(new MemoryStream()); }); } diff --git a/src/Build.UnitTests/Construction/ProjectImportElement_Tests.cs b/src/Build.UnitTests/Construction/ProjectImportElement_Tests.cs index 0fcd05dc03b..aab1c6b3273 100644 --- a/src/Build.UnitTests/Construction/ProjectImportElement_Tests.cs +++ b/src/Build.UnitTests/Construction/ProjectImportElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; diff --git a/src/Build.UnitTests/Construction/ProjectRootElement_Tests.cs b/src/Build.UnitTests/Construction/ProjectRootElement_Tests.cs index 08b5820f23c..f1c67899aea 100644 --- a/src/Build.UnitTests/Construction/ProjectRootElement_Tests.cs +++ b/src/Build.UnitTests/Construction/ProjectRootElement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build.UnitTests/Construction/SolutionFile_Tests.cs b/src/Build.UnitTests/Construction/SolutionFile_Tests.cs index 819688c22a2..a8f04046ca2 100644 --- a/src/Build.UnitTests/Construction/SolutionFile_Tests.cs +++ b/src/Build.UnitTests/Construction/SolutionFile_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Exceptions; @@ -35,11 +35,9 @@ public void BasicParseFirstProjectLine() p.FullPath = NativeMethodsShared.IsWindows ? "c:\\foo.sln" : "/foo.sln"; ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\"{Project GUID}\") = \"Project name\", \"Relative path to project file\", \"Unique name-GUID\"", - proj - ); + proj); proj.ProjectType.ShouldBe(SolutionProjectType.Unknown); proj.ProjectName.ShouldBe("Project name"); proj.RelativePath.ShouldBe("Relative path to project file"); @@ -62,11 +60,9 @@ public void ParseFirstProjectLine_VC() p.FullPath = "c:\\foo.sln"; ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"Project name.vcproj\", \"Relative path\\to\\Project name.vcproj\", \"Unique name-GUID\"", - proj - ); + proj); }); } /// @@ -81,11 +77,9 @@ public void ParseFirstProjectLine_VC2() p.FullPath = NativeMethodsShared.IsWindows ? "c:\\foo.sln" : "/foo.sln"; ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"Project name.myvctype\", \"Relative path\\to\\Project name.myvctype\", \"Unique name-GUID\"", - proj - ); + proj); proj.ProjectType.ShouldBe(SolutionProjectType.KnownToBeMSBuildFormat); proj.ProjectName.ShouldBe("Project name.myvctype"); proj.RelativePath.ShouldBe("Relative path\\to\\Project name.myvctype"); @@ -102,11 +96,9 @@ public void ParseFirstProjectLineWithDifferentSpacing() p.FullPath = NativeMethodsShared.IsWindows ? "c:\\foo.sln" : "/foo.sln"; ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\" {Project GUID} \") = \" Project name \", \" Relative path to project file \" , \" Unique name-GUID \"", - proj - ); + proj); proj.ProjectType.ShouldBe(SolutionProjectType.Unknown); proj.ProjectName.ShouldBe("Project name"); proj.RelativePath.ShouldBe("Relative path to project file"); @@ -124,11 +116,9 @@ public void ParseFirstProjectLine_InvalidProject() p.FullPath = NativeMethodsShared.IsWindows ? "c:\\foo.sln" : "/foo.sln"; ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\"{Project GUID}\") = \"\", \"src\\.proj\", \"Unique name-GUID\"", - proj - ); + proj); proj.ProjectType.ShouldBe(SolutionProjectType.Unknown); proj.ProjectName.ShouldStartWith("EmptyProjectName"); proj.RelativePath.ShouldBe("src\\.proj"); @@ -690,11 +680,9 @@ public void ParseFirstProjectLineWhereProjectNameHasSpecialCharacters() p.FullPath = NativeMethodsShared.IsWindows ? "c:\\foo.sln" : "/foo.sln"; ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\"{Project GUID}\") = \"MyProject,(=IsGreat)\", \"Relative path to project file\" , \"Unique name-GUID\"", - proj - ); + proj); proj.ProjectType.ShouldBe(SolutionProjectType.Unknown); proj.ProjectName.ShouldBe("MyProject,(=IsGreat)"); proj.RelativePath.ShouldBe("Relative path to project file"); @@ -718,11 +706,9 @@ public void ParseFirstProjectLineWhereProjectPathHasBackslash() p.SolutionFileDirectory = Path.GetFullPath(solutionFolder.Path); ProjectInSolution proj = new ProjectInSolution(p); - p.ParseFirstProjectLine - ( + p.ParseFirstProjectLine( "Project(\"{Project GUID}\") = \"ProjectInSubdirectory\", \"RelativePath\\project file\" , \"Unique name-GUID\"", - proj - ); + proj); proj.ProjectType.ShouldBe(SolutionProjectType.Unknown); proj.ProjectName.ShouldBe("ProjectInSubdirectory"); proj.RelativePath.ShouldBe(Path.Combine("RelativePath", "project file")); @@ -736,7 +722,7 @@ public void ParseFirstProjectLineWhereProjectPathHasBackslash() /// /// /// - static internal SolutionFile ParseSolutionHelper(string solutionFileContents) + internal static SolutionFile ParseSolutionHelper(string solutionFileContents) { solutionFileContents = solutionFileContents.Replace('\'', '"'); StreamReader sr = StreamHelpers.StringToStreamReader(solutionFileContents); @@ -783,8 +769,7 @@ public void VersionTooLow() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Ensure that an unsupported version greater than the current maximum (10) in the .SLN file results in a @@ -1736,8 +1721,7 @@ public void ParseInvalidSolutionConfigurations1() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Test some invalid cases for solution configuration parsing @@ -1763,8 +1747,7 @@ public void ParseInvalidSolutionConfigurations2() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// /// Test some invalid cases for solution configuration parsing @@ -1790,8 +1773,7 @@ public void ParseInvalidSolutionConfigurations3() "; ParseSolutionHelper(solutionFileContents); - } - ); + }); } /// diff --git a/src/Build.UnitTests/Construction/SolutionProjectGenerator_Tests.cs b/src/Build.UnitTests/Construction/SolutionProjectGenerator_Tests.cs index 92a1591a313..4e20b2d9617 100644 --- a/src/Build.UnitTests/Construction/SolutionProjectGenerator_Tests.cs +++ b/src/Build.UnitTests/Construction/SolutionProjectGenerator_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -765,8 +765,7 @@ public void SolutionWithMissingDependencies() SolutionFile sp = SolutionFile_Tests.ParseSolutionHelper(solutionFileContents); ProjectInstance[] instances = SolutionProjectGenerator.Generate(sp, null, null, _buildEventContext, CreateMockLoggingService()); - } - ); + }); } /// /// Blob should contain dependency info @@ -1504,46 +1503,38 @@ public void TestDisambiguateProjectTargetName() ProjectTargetInstance publishTarget = instances[0].Targets.Where(target => String.Equals(target.Value.Name, "Publish", StringComparison.OrdinalIgnoreCase)).First().Value; // Check that the appropriate target is being passed to the child projects - Assert.Null(buildTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Targets")); - - Assert.Equal("Clean", cleanTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Targets")); - - Assert.Equal("Rebuild", rebuildTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Targets")); - - Assert.Equal("Publish", publishTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Targets")); + Assert.Null(buildTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Targets")); + + Assert.Equal("Clean", cleanTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Targets")); + + Assert.Equal("Rebuild", rebuildTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Targets")); + + Assert.Equal("Publish", publishTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Targets")); // Check that the child projects in question are the members of the "ProjectReference" item group - Assert.Equal("@(ProjectReference)", buildTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Projects")); - - Assert.Equal("@(ProjectReference->Reverse())", cleanTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Projects")); - - Assert.Equal("@(ProjectReference)", rebuildTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Projects")); - - Assert.Equal("@(ProjectReference)", publishTarget.Tasks.Where - ( - task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase) - ).First().GetParameter("Projects")); + Assert.Equal("@(ProjectReference)", buildTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Projects")); + + Assert.Equal("@(ProjectReference->Reverse())", cleanTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Projects")); + + Assert.Equal("@(ProjectReference)", rebuildTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Projects")); + + Assert.Equal("@(ProjectReference)", publishTarget.Tasks.Where( + task => String.Equals(task.Name, "MSBuild", StringComparison.OrdinalIgnoreCase)) + .First().GetParameter("Projects")); // We should have only the four standard targets plus the two validation targets (ValidateSolutionConfiguration and ValidateToolsVersions). } @@ -2251,13 +2242,16 @@ public void TestTargetFrameworkVersionGreaterThan4() ProjectCollection collection = new ProjectCollection(); collection.RegisterLogger(logger); +#pragma warning disable format #if !FEATURE_ASPNET_COMPILER - Assert.Throws(() => { + Assert.Throws(() => + { #endif - ProjectInstance[] instances = SolutionProjectGenerator.Generate(solution, globalProperties, null, BuildEventContext.Invalid, collection.LoggingService); + ProjectInstance[] instances = SolutionProjectGenerator.Generate(solution, globalProperties, null, BuildEventContext.Invalid, collection.LoggingService); #if !FEATURE_ASPNET_COMPILER }); #endif +#pragma warning restore format #if FEATURE_ASPNET_COMPILER Version ver = new Version("4.34"); @@ -2277,8 +2271,8 @@ public void TestTargetFrameworkVersionGreaterThan4() [Fact] public void CustomTargetNamesAreInInMetaproj() { - SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper - (@" + SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper( + @" Microsoft Visual Studio Solution File, Format Version 14.00 # Visual Studio 2015 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary1"", ""ClassLibrary1.csproj"", ""{6185CC21-BE89-448A-B3C0-D1C27112E595}"" @@ -2327,8 +2321,8 @@ public void CustomTargetNamesAreInInMetaproj() [InlineData(true)] public void IllegalUserTargetNamesDoNotThrow(bool forceCaseDifference) { - SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper - (@" + SolutionFile solution = SolutionFile_Tests.ParseSolutionHelper( + @" Microsoft Visual Studio Solution File, Format Version 14.00 # Visual Studio 2015 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""ClassLibrary1"", ""ClassLibrary1.csproj"", ""{6185CC21-BE89-448A-B3C0-D1C27112E595}"" diff --git a/src/Build.UnitTests/Construction/XmlReaderWithoutLocation_Tests.cs b/src/Build.UnitTests/Construction/XmlReaderWithoutLocation_Tests.cs index 703e0a5b7ee..db3134ae8eb 100644 --- a/src/Build.UnitTests/Construction/XmlReaderWithoutLocation_Tests.cs +++ b/src/Build.UnitTests/Construction/XmlReaderWithoutLocation_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System.Xml; @@ -155,12 +155,10 @@ public override string Value [Fact] public void CreateProjectWithoutLineInfo() { - XmlReader reader = XmlReader.Create(new StringReader - ( + XmlReader reader = XmlReader.Create(new StringReader( @" - " - )); + ")); XmlReader noLineInfoReader = new XmlReaderNoIXmlLineInfo(reader); Project project = new Project(noLineInfoReader); Assert.Single(project.Targets); diff --git a/src/Build.UnitTests/Definition/ItemDataCollectionValue_Tests.cs b/src/Build.UnitTests/Definition/ItemDataCollectionValue_Tests.cs index b1499384ed5..7c5978dbb40 100644 --- a/src/Build.UnitTests/Definition/ItemDataCollectionValue_Tests.cs +++ b/src/Build.UnitTests/Definition/ItemDataCollectionValue_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs b/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs index 3d766374a9e..d155a128239 100644 --- a/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs +++ b/src/Build.UnitTests/Definition/ItemDefinitionGroup_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -178,8 +178,7 @@ public void ItemDefinitionDoesntAllowItemExpansion() "))); - } - ); + }); } /// /// Tests that item definition metadata doesn't allow item expansion for the conditional. @@ -207,8 +206,7 @@ public void ItemDefinitionMetadataConditionDoesntAllowItemExpansion() "))); - } - ); + }); } /// /// Tests that item definition metadata doesn't allow item expansion for the value. @@ -236,8 +234,7 @@ public void ItemDefinitionMetadataDoesntAllowItemExpansion() "))); - } - ); + }); } /// /// Tests that item metadata which contains a metadata expansion referring to an item type other @@ -804,8 +801,7 @@ public void ItemExpressionInDefaultMetadataValueErrors() "))); p.Build("t", new ILogger[] { logger }); - } - ); + }); } [Fact] public void UnqualifiedMetadataConditionOnItemDefinitionGroupErrors() @@ -820,8 +816,7 @@ public void UnqualifiedMetadataConditionOnItemDefinitionGroupErrors() "))); p.Build("t", new ILogger[] { logger }); - } - ); + }); } [Fact] @@ -837,8 +832,7 @@ public void QualifiedMetadataConditionOnItemDefinitionGroupErrors() "))); p.Build("t", new ILogger[] { logger }); - } - ); + }); } [Fact] public void MetadataConditionOnItemDefinition() @@ -1045,8 +1039,7 @@ public void ItemDefinitionInTargetErrors() "))); bool result = p.Build("t", new ILogger[] { logger }); - } - ); + }); } #if FEATURE_ASSEMBLY_LOCATION diff --git a/src/Build.UnitTests/Definition/ProjectEvaluationContext_Tests.cs b/src/Build.UnitTests/Definition/ProjectEvaluationContext_Tests.cs index f542b837ee5..443871defb6 100644 --- a/src/Build.UnitTests/Definition/ProjectEvaluationContext_Tests.cs +++ b/src/Build.UnitTests/Definition/ProjectEvaluationContext_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -34,8 +34,8 @@ public ProjectEvaluationContext_Tests() _resolver = new SdkUtilities.ConfigurableMockSdkResolver( new Dictionary { - {"foo", new SdkResult(new SdkReference("foo", "1.0.0", null), "path", "1.0.0", null)}, - {"bar", new SdkResult(new SdkReference("bar", "1.0.0", null), "path", "1.0.0", null)} + {"foo", new SdkResult(new SdkReference("foo", "1.0.0", null), "path", "1.0.0", null) }, + {"bar", new SdkResult(new SdkReference("bar", "1.0.0", null), "path", "1.0.0", null) } }); } @@ -49,9 +49,9 @@ public void Dispose() private static void SetResolverForContext(EvaluationContext context, SdkResolver resolver) { - var sdkService = (SdkResolverService) context.SdkResolverService; + var sdkService = (SdkResolverService)context.SdkResolverService; - sdkService.InitializeForTests(null, new List {resolver}); + sdkService.InitializeForTests(null, new List { resolver }); } [Theory] @@ -109,8 +109,7 @@ public void PassedInFileSystemShouldBeReusedInSharedContext() { ProjectCollection = projectCollection, EvaluationContext = evaluationContext - } - ); + }); } fileSystem.ExistenceChecks.OrderBy(kvp => kvp.Key) @@ -145,8 +144,7 @@ public void EvaluationShouldUseDirectoryCache() { ProjectCollection = projectCollection, DirectoryCacheFactory = directoryCacheFactory, - } - ); + }); directoryCacheFactory.DirectoryCaches.Count.ShouldBe(1); var directoryCache = directoryCacheFactory.DirectoryCaches[0]; @@ -359,8 +357,7 @@ public void ContextCachesItemElementGlobExpansions(EvaluationContext.SharingPoli File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.cs"), ""); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); - } - ); + }); } public static IEnumerable ContextDisambiguatesRelativeGlobsData @@ -408,7 +405,7 @@ public void ContextDisambiguatesSameRelativeGlobsPointingInsideDifferentProjectC File.WriteAllText(Path.Combine(projectDirectory2, $"2.{evaluationCount}.cs"), ""); EvaluateProjects( - new [] + new[] { new ProjectSpecification( Path.Combine(projectDirectory1, "1"), @@ -440,8 +437,7 @@ public void ContextDisambiguatesSameRelativeGlobsPointingInsideDifferentProjectC File.WriteAllText(Path.Combine(projectDirectory1, $"1.{evaluationCount}.cs"), ""); File.WriteAllText(Path.Combine(projectDirectory2, $"2.{evaluationCount}.cs"), ""); - } - ); + }); } [Theory] @@ -464,7 +460,7 @@ public void ContextDisambiguatesSameRelativeGlobsPointingOutsideDifferentProject File.WriteAllText(Path.Combine(project2GlobDirectory, $"2.{evaluationCount}.cs"), ""); EvaluateProjects( - new [] + new[] { new ProjectSpecification( Path.Combine(project1Directory, "1"), @@ -498,8 +494,7 @@ public void ContextDisambiguatesSameRelativeGlobsPointingOutsideDifferentProject File.WriteAllText(Path.Combine(project1GlobDirectory, $"1.{evaluationCount}.cs"), ""); File.WriteAllText(Path.Combine(project2GlobDirectory, $"2.{evaluationCount}.cs"), ""); - } - ); + }); } [Theory] @@ -526,7 +521,7 @@ public void ContextDisambiguatesAFullyQualifiedGlobPointingInAnotherRelativeGlob File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), ""); EvaluateProjects( - new [] + new[] { // first project uses a relative path new ProjectSpecification( @@ -569,8 +564,7 @@ public void ContextDisambiguatesAFullyQualifiedGlobPointingInAnotherRelativeGlob evaluationCount++; File.WriteAllText(Path.Combine(project1GlobDirectory, $"{evaluationCount}.cs"), ""); - } - ); + }); } [Theory] @@ -594,7 +588,7 @@ public void ContextDisambiguatesDistinctRelativeGlobsPointingOutsideOfSameProjec File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); EvaluateProjects( - new [] + new[] { new ProjectSpecification( Path.Combine(project1Directory.Path, "1"), @@ -630,8 +624,7 @@ public void ContextDisambiguatesDistinctRelativeGlobsPointingOutsideOfSameProjec evaluationCount++; File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); - } - ); + }); } [Theory] @@ -642,7 +635,7 @@ public void ContextCachesCommonOutOfProjectConeFullyQualifiedGlob(EvaluationCont ContextCachesCommonOutOfProjectCone(itemSpecPathIsRelative: false, policy: policy, expectedGlobExpansions: expectedGlobExpansions); } - [Theory (Skip="https://github.com/dotnet/msbuild/issues/3889")] + [Theory(Skip = "https://github.com/dotnet/msbuild/issues/3889")] [MemberData(nameof(ContextPinsGlobExpansionCacheData))] // projects should cache glob expansions when the __relative__ glob is shared between projects and points outside of project cone public void ContextCachesCommonOutOfProjectConeRelativeGlob(EvaluationContext.SharingPolicy policy, string[][] expectedGlobExpansions) @@ -703,8 +696,7 @@ private void ContextCachesCommonOutOfProjectCone(bool itemSpecPathIsRelative, Ev File.WriteAllText(Path.Combine(globDirectory.Path, $"{evaluationCount}.cs"), ""); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); - } - ); + }); } private static string[] _projectsWithGlobImports = @@ -741,8 +733,7 @@ public void ContextCachesImportGlobExpansions(EvaluationContext.SharingPolicy po File.WriteAllText(Path.Combine(projectDirectory, $"{evaluationCount}.props"), $"".Cleanup()); ObjectModelHelpers.AssertItems(expectedGlobExpansion, project.GetItems("i")); - } - ); + }); } private static string[] _projectsWithConditions = @@ -804,8 +795,7 @@ public void ContextCachesExistenceChecksInConditions(EvaluationContext.SharingPo throw new ArgumentOutOfRangeException(nameof(policy), policy, null); } } - } - ); + }); } [Theory] @@ -822,7 +812,7 @@ public void ContextCachesExistenceChecksInGetDirectoryNameOfFileAbove(Evaluation int evaluationCount = 0; EvaluateProjects( - new [] + new[] { $@" @@ -876,7 +866,7 @@ public void ContextCachesExistenceChecksInGetPathOfFileAbove(EvaluationContext.S int evaluationCount = 0; EvaluateProjects( - new [] + new[] { $@" diff --git a/src/Build.UnitTests/Definition/ProjectHelpers.cs b/src/Build.UnitTests/Definition/ProjectHelpers.cs index de7960e5361..7159cc57fc0 100644 --- a/src/Build.UnitTests/Definition/ProjectHelpers.cs +++ b/src/Build.UnitTests/Definition/ProjectHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; @@ -21,12 +21,10 @@ internal static class ProjectHelpers /// A project instance. internal static ProjectInstance CreateEmptyProjectInstance() { - XmlReader reader = XmlReader.Create(new StringReader - ( + XmlReader reader = XmlReader.Create(new StringReader( @" - " - )); + ")); Project project = new Project(reader); ProjectInstance instance = project.CreateProjectInstance(); diff --git a/src/Build.UnitTests/Definition/ProjectItem_Tests.cs b/src/Build.UnitTests/Definition/ProjectItem_Tests.cs index 6410e2474d2..86311e423a3 100644 --- a/src/Build.UnitTests/Definition/ProjectItem_Tests.cs +++ b/src/Build.UnitTests/Definition/ProjectItem_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -46,8 +46,7 @@ public void CopyFromClonesMetadata() /// private static IList GetItemsFromFragment(string fragment) { - string content = String.Format - ( + string content = String.Format( ObjectModelHelpers.CleanupFileContents(@" @@ -55,8 +54,7 @@ private static IList GetItemsFromFragment(string fragment) "), - fragment - ); + fragment); IList items = GetItems(content); return items; diff --git a/src/Build.UnitTests/Definition/Project_Internal_Tests.cs b/src/Build.UnitTests/Definition/Project_Internal_Tests.cs index c2a03e57d20..507514617ea 100644 --- a/src/Build.UnitTests/Definition/Project_Internal_Tests.cs +++ b/src/Build.UnitTests/Definition/Project_Internal_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/Definition/ToolsVersion_Tests.cs b/src/Build.UnitTests/Definition/ToolsVersion_Tests.cs index 9d292500a86..2e9ac12c15f 100644 --- a/src/Build.UnitTests/Definition/ToolsVersion_Tests.cs +++ b/src/Build.UnitTests/Definition/ToolsVersion_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -393,8 +393,7 @@ public void InvalidToolsVersion() ")), null /* no global properties */, "goober", p); success = project.Build(mockLogger); // BANG! - } - ); + }); } /// /// Even a valid toolsversion should be forced to the current ToolsVersion if MSBUILDTREATALLTOOLSVERSIONSASCURRENT diff --git a/src/Build.UnitTests/Definition/ToolsetConfigurationReaderTestHelper.cs b/src/Build.UnitTests/Definition/ToolsetConfigurationReaderTestHelper.cs index 3f71617095f..bf0eed44d46 100644 --- a/src/Build.UnitTests/Definition/ToolsetConfigurationReaderTestHelper.cs +++ b/src/Build.UnitTests/Definition/ToolsetConfigurationReaderTestHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Configuration; diff --git a/src/Build.UnitTests/Definition/ToolsetConfigurationReader_Tests.cs b/src/Build.UnitTests/Definition/ToolsetConfigurationReader_Tests.cs index e0a0f3dfeee..4d3962dfa70 100644 --- a/src/Build.UnitTests/Definition/ToolsetConfigurationReader_Tests.cs +++ b/src/Build.UnitTests/Definition/ToolsetConfigurationReader_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Configuration; using Microsoft.Build.Collections; @@ -221,8 +221,7 @@ public void ToolsVersionTest_NameNotSpecified() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } /// /// More than 1 toolset element with the same name @@ -250,8 +249,7 @@ public void ToolsVersionTest_MultipleElementsWithSameName() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } /// /// empty toolset element @@ -278,8 +276,7 @@ public void ToolsVersionTest_EmptyElement() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } #endregion @@ -346,8 +343,7 @@ public void PropertyTest_NameNotSpecified() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } /// /// value attribute is missing @@ -372,8 +368,7 @@ public void PropertyTest_ValueNotSpecified() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } /// /// more than 1 property element with the same name @@ -399,8 +394,7 @@ public void PropertyTest_MultipleElementsWithSameName() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } /// /// property element is an empty element @@ -427,8 +421,7 @@ public void PropertyTest_EmptyElement() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } #endregion @@ -567,7 +560,7 @@ public void ExtensionPathsTest_Basic1() Assert.Equal("unix", allPaths.GetElement(2).OS); Assert.Single(allPaths.GetElement(2).PropertyElements); - Assert.Equal( @"/tmp/bar", allPaths.GetElement(2).PropertyElements.GetElement("MSBuildExtensionsPath").Value); + Assert.Equal(@"/tmp/bar", allPaths.GetElement(2).PropertyElements.GetElement("MSBuildExtensionsPath").Value); var reader = GetStandardConfigurationReader(); Dictionary toolsets = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -578,17 +571,17 @@ public void ExtensionPathsTest_Basic1() Dictionary pathsTable = toolsets["2.0"].ImportPropertySearchPathsTable; if (NativeMethodsShared.IsWindows) { - CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"c:\\foo"}); - CheckPathsTable(pathsTable, "MSBuildExtensionsPath64", new string[] {"c:\\foo64", "c:\\bar64"}); + CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] { "c:\\foo" }); + CheckPathsTable(pathsTable, "MSBuildExtensionsPath64", new string[] { "c:\\foo64", "c:\\bar64" }); } else if (NativeMethodsShared.IsOSX) { - CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"/tmp/foo"}); - CheckPathsTable(pathsTable, "MSBuildExtensionsPath32", new string[] {"/tmp/foo32", "/tmp/bar32"}); + CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] { "/tmp/foo" }); + CheckPathsTable(pathsTable, "MSBuildExtensionsPath32", new string[] { "/tmp/foo32", "/tmp/bar32" }); } else { - CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] {"/tmp/bar"}); + CheckPathsTable(pathsTable, "MSBuildExtensionsPath", new string[] { "/tmp/bar" }); } } @@ -636,8 +629,7 @@ public void ExtensionsPathsTest_MultipleElementsWithSameOS() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } /// @@ -670,8 +662,7 @@ public void ExtensionsPathsTest_MultipleElementsWithSamePropertyNameForSameOS() Configuration config = ToolsetConfigurationReaderTestHelper.ReadApplicationConfigurationTest(); config.GetSection(s_msbuildToolsets); - } - ); + }); } private ToolsetConfigurationReader GetStandardConfigurationReader() diff --git a/src/Build.UnitTests/Definition/ToolsetReader_Tests.cs b/src/Build.UnitTests/Definition/ToolsetReader_Tests.cs index 07ab3ac1d6a..f37d6c7329c 100644 --- a/src/Build.UnitTests/Definition/ToolsetReader_Tests.cs +++ b/src/Build.UnitTests/Definition/ToolsetReader_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -267,8 +267,7 @@ public void GetToolsetDataFromConfiguration_InvalidXmlFile() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Tests the case where application configuration file is invalid @@ -297,8 +296,7 @@ public void GetToolsetDataFromConfiguration_InvalidConfigFile() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Tests the case where application configuration file is empty @@ -317,8 +315,7 @@ public void GetToolsetDataFromConfiguration_FileEmpty() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Tests the case when ReadConfiguration throws exception @@ -339,8 +336,7 @@ public void GetToolsetDataFromConfiguration_ConfigurationExceptionThrown() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Tests the case when ReadConfiguration throws exception @@ -361,8 +357,7 @@ public void GetToolsetDataFromConfiguration_ConfigurationErrorsExceptionThrown() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Tests the case where default attribute is not specified in the config file @@ -570,8 +565,7 @@ public void GetToolsetDataFromConfiguration_ToolsVersionIsEmptyString() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// If both MSBuildToolsPath and MSBuildBinPath are present, they must match @@ -601,8 +595,7 @@ public void GetToolsetDataFromConfiguration_ToolsPathAndBinPathDiffer() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Tests the case when a blank value of PropertyName is specified in the config file @@ -633,8 +626,7 @@ public void BlankPropertyNameInConfigFile() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } #endif @@ -654,8 +646,7 @@ public void BlankPropertyNameInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should throw ... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -663,10 +654,8 @@ public void BlankPropertyNameInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } /// /// Tests the case when a blank property name is specified in the registry in a @@ -689,8 +678,7 @@ public void BlankPropertyNameInRegistrySubToolset() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should throw ... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -698,10 +686,8 @@ public void BlankPropertyNameInRegistrySubToolset() #endif new ProjectCollection().EnvironmentProperties, globalProperties, - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } #endif #if FEATURE_SYSTEM_CONFIGURATION @@ -749,8 +735,7 @@ public void BlankPropertyValueInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should not throw ... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -758,8 +743,7 @@ public void BlankPropertyValueInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); + ToolsetDefinitionLocations.Registry); } /// @@ -778,8 +762,7 @@ public void BlankPropertyValueInRegistrySubToolset() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should not throw ... - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -787,8 +770,7 @@ public void BlankPropertyValueInRegistrySubToolset() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); + ToolsetDefinitionLocations.Registry); Assert.Equal("2.0", defaultToolsVersion); Assert.Empty(values["2.0"].Properties); @@ -827,8 +809,7 @@ public void InvalidPropertyNameInConfigFile() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), true, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } #endif @@ -847,8 +828,7 @@ public void InvalidPropertyNameInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should throw ... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -856,10 +836,8 @@ public void InvalidPropertyNameInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } /// /// Tests the case when an invalid value of PropertyName is specified in the registry @@ -878,8 +856,7 @@ public void InvalidPropertyNameInRegistrySubToolset() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should throw ... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -887,10 +864,8 @@ public void InvalidPropertyNameInRegistrySubToolset() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } #if FEATURE_SYSTEM_CONFIGURATION @@ -988,7 +963,9 @@ public void GetToolsetDataFromConfiguration_XmlEscapedCharacters() Assert.Equal(@"some>value", values["2>.0"].Properties["foo"].EvaluatedValue); } #endif - #endregion +#pragma warning disable format + #endregion +#pragma warning restore format #region "GetToolsetData tests" @@ -1032,8 +1009,7 @@ public void GetToolsetData_NoConflict() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1041,8 +1017,7 @@ public void GetToolsetData_NoConflict() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); // Verifications Assert.Equal(4, values.Count); @@ -1085,8 +1060,7 @@ public void ToolsetInitializationFlagsSetToNone() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1094,8 +1068,7 @@ public void ToolsetInitializationFlagsSetToNone() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.None - ); + ToolsetDefinitionLocations.None); // Verifications Assert.Single(values); @@ -1142,8 +1115,7 @@ public void ToolsetInitializationFlagsSetToRegistry() #endif Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1151,8 +1123,7 @@ public void ToolsetInitializationFlagsSetToRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); + ToolsetDefinitionLocations.Registry); // Verifications Assert.Equal(2, values.Count); @@ -1175,8 +1146,7 @@ public void ThrowOnNonStringRegistryValueTypes() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // Should throw ... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1184,10 +1154,8 @@ public void ThrowOnNonStringRegistryValueTypes() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } [Fact] public void PropertiesInRegistryCannotReferToOtherPropertiesInRegistry() @@ -1202,8 +1170,7 @@ public void PropertiesInRegistryCannotReferToOtherPropertiesInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1211,8 +1178,7 @@ public void PropertiesInRegistryCannotReferToOtherPropertiesInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); + ToolsetDefinitionLocations.Registry); Assert.Equal("", values["2.0"].Properties["p0"].EvaluatedValue); Assert.Equal("v", values["2.0"].Properties["p1"].EvaluatedValue); @@ -1234,8 +1200,7 @@ public void SubToolsetPropertiesInRegistryCannotReferToOtherPropertiesInRegistry Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1243,8 +1208,7 @@ public void SubToolsetPropertiesInRegistryCannotReferToOtherPropertiesInRegistry #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); + ToolsetDefinitionLocations.Registry); Assert.Equal("", values["2.0"].Properties["p0"].EvaluatedValue); Assert.Equal("v", values["2.0"].Properties["p1"].EvaluatedValue); @@ -1268,8 +1232,7 @@ public void SubToolsetsCannotDefineMSBuildToolsPath() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // throws - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1277,10 +1240,8 @@ public void SubToolsetsCannotDefineMSBuildToolsPath() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } /// /// Tests that ToolsetInitialization are respected. @@ -1317,8 +1278,7 @@ public void ToolsetInitializationFlagsSetToConfigurationFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1326,8 +1286,7 @@ public void ToolsetInitializationFlagsSetToConfigurationFile() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); + ToolsetDefinitionLocations.ConfigurationFile); // Verifications Assert.Equal(2, values.Count); @@ -1375,8 +1334,7 @@ public void PropertyInConfigurationFileReferencesRegistryLocation() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1384,8 +1342,7 @@ public void PropertyInConfigurationFileReferencesRegistryLocation() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Single(values); Assert.Equal(@"D:\somePathToTasks", values["2.0"].ToolsPath); @@ -1408,8 +1365,7 @@ public void ToolsPathInRegistryHasInvalidPathChars() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); // should throw... - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1417,10 +1373,8 @@ public void ToolsPathInRegistryHasInvalidPathChars() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } #if FEATURE_SYSTEM_CONFIGURATION @@ -1446,17 +1400,14 @@ public void SamePropertyDefinedMultipleTimesForSingleToolsVersionInConfiguration Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, null, GetStandardConfigurationReader(), new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); - } - ); + ToolsetDefinitionLocations.ConfigurationFile); + }); } [Fact] @@ -1481,17 +1432,14 @@ public void SamePropertyDifferentCaseDefinedMultipleTimesForSingleToolsVersionIn Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, null, GetStandardConfigurationReader(), new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); - } - ); + ToolsetDefinitionLocations.ConfigurationFile); + }); } @@ -1523,17 +1471,14 @@ public void SameToolsVersionDefinedMultipleTimesInConfigurationFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, null, GetStandardConfigurationReader(), new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); - } - ); + ToolsetDefinitionLocations.ConfigurationFile); + }); } [Fact] @@ -1564,17 +1509,14 @@ public void SameToolsVersionDifferentCaseDefinedMultipleTimesInConfigurationFile Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, null, GetStandardConfigurationReader(), new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); - } - ); + ToolsetDefinitionLocations.ConfigurationFile); + }); } [Fact] @@ -1597,17 +1539,14 @@ public void CannotSetReservedPropertyInConfigFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, null, GetStandardConfigurationReader(), new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); - } - ); + ToolsetDefinitionLocations.ConfigurationFile); + }); } #endif @@ -1623,8 +1562,7 @@ public void CannotSetReservedPropertyInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1632,10 +1570,8 @@ public void CannotSetReservedPropertyInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } [Fact] @@ -1651,8 +1587,7 @@ public void CannotSetReservedPropertyInRegistrySubToolset() subKey1.SetValue("MSBuildProjectFile", @"SomeRegistryValue"); Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1660,10 +1595,8 @@ public void CannotSetReservedPropertyInRegistrySubToolset() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); - } - ); + ToolsetDefinitionLocations.Registry); + }); } #if FEATURE_SYSTEM_CONFIGURATION @@ -1697,16 +1630,14 @@ public void NoInterferenceBetweenToolsetDefinitions() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, null, GetStandardConfigurationReader(), new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); + ToolsetDefinitionLocations.ConfigurationFile); Assert.Equal(2, values.Count); @@ -1883,8 +1814,7 @@ private void RegistryValidRegistryExpressionHelper(string propertyExpression, st Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1892,8 +1822,7 @@ private void RegistryValidRegistryExpressionHelper(string propertyExpression, st #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Registry - ); + ToolsetDefinitionLocations.Registry); Assert.Single(values); Assert.Equal(expectedValue, values["2.0"].Properties["p"].EvaluatedValue); @@ -1944,8 +1873,7 @@ private void ConfigFileValidRegistryExpressionHelper(string propertyExpression, Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1953,8 +1881,7 @@ private void ConfigFileValidRegistryExpressionHelper(string propertyExpression, #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.ConfigurationFile - ); + ToolsetDefinitionLocations.ConfigurationFile); Assert.Single(values); Assert.Equal(expectedValue, values["2.0"].Properties["p"].EvaluatedValue); @@ -1988,8 +1915,7 @@ public void GetToolsetData_ConflictingPropertyValuesSameCase() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -1997,8 +1923,7 @@ public void GetToolsetData_ConflictingPropertyValuesSameCase() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Single(values); Assert.Empty(values["2.0"].Properties); @@ -2034,8 +1959,7 @@ public void GetToolsetData_ConflictingPropertyValuesRegistryThrows() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2043,8 +1967,7 @@ public void GetToolsetData_ConflictingPropertyValuesRegistryThrows() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Single(values); Assert.Empty(values["2.0"].Properties); @@ -2084,8 +2007,7 @@ public void GetToolsetData_NoMerging() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2093,8 +2015,7 @@ public void GetToolsetData_NoMerging() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Single(values); Assert.Single(values["2.0"].Properties); @@ -2169,8 +2090,7 @@ public void GetToolsetData_RegistryNotPresent() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2178,8 +2098,7 @@ public void GetToolsetData_RegistryNotPresent() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Single(values); Assert.Empty(values["2.0"].Properties); @@ -2201,8 +2120,7 @@ public void GetToolsetData_ConfigFileNotPresent() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2210,8 +2128,7 @@ public void GetToolsetData_ConfigFileNotPresent() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Single(values); Assert.Empty(values["2.0"].Properties); @@ -2226,8 +2143,7 @@ public void GetToolsetData_RegistryAndConfigNotPresent() { Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2235,8 +2151,7 @@ public void GetToolsetData_RegistryAndConfigNotPresent() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); // Should either be the last-ditch 2.0 toolset, or if 2.0 is not installed, then the last-last-ditch of 4.0 Assert.Single(values); @@ -2269,8 +2184,7 @@ public void GetToolsetData_ReadConfigThrowsException() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2278,10 +2192,8 @@ public void GetToolsetData_ReadConfigThrowsException() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); - } - ); + ToolsetDefinitionLocations.Default); + }); } /// /// Tests the case where reading from registry throws exception @@ -2310,8 +2222,7 @@ public void GetToolsetData_ReadRegistryOpenSubKeyThrowsException() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, new ToolsetRegistryReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), mockRegistryKey), #if FEATURE_SYSTEM_CONFIGURATION @@ -2319,8 +2230,7 @@ public void GetToolsetData_ReadRegistryOpenSubKeyThrowsException() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); }); } @@ -2361,8 +2271,7 @@ public void SetDefaultToolsetVersion_SpecifiedInRegistryAndConfigFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2370,8 +2279,7 @@ public void SetDefaultToolsetVersion_SpecifiedInRegistryAndConfigFile() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("5.0", defaultToolsVersion); } @@ -2406,8 +2314,7 @@ public void SetDefaultToolsetVersion_SpecifiedOnlyInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2415,8 +2322,7 @@ public void SetDefaultToolsetVersion_SpecifiedOnlyInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("4.0", defaultToolsVersion); } @@ -2456,8 +2362,7 @@ public void SetOverrideTasks_SpecifiedOnlyInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2465,8 +2370,7 @@ public void SetOverrideTasks_SpecifiedOnlyInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("4.0", defaultToolsVersion); Assert.Equal(overridePath, values["4.0"].OverrideTasksPath); @@ -2505,8 +2409,7 @@ public void SetDefaultOverrideToolsVersion_SpecifiedOnlyInRegistry() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2514,8 +2417,7 @@ public void SetDefaultOverrideToolsVersion_SpecifiedOnlyInRegistry() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("13.0", values["4.0"].DefaultOverrideToolsVersion); } @@ -2545,8 +2447,7 @@ public void SetDefaultToolsetVersion_SpecifiedOnlyInConfigFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2554,8 +2455,7 @@ public void SetDefaultToolsetVersion_SpecifiedOnlyInConfigFile() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("5.0", defaultToolsVersion); @@ -2587,8 +2487,7 @@ public void SetOverrideTaskPath_SpecifiedOnlyInConfigFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2596,8 +2495,7 @@ public void SetOverrideTaskPath_SpecifiedOnlyInConfigFile() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("5.0", defaultToolsVersion); @@ -2629,8 +2527,7 @@ public void SetDefaultOverrideToolsVersion_SpecifiedOnlyInConfigFile() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2638,8 +2535,7 @@ public void SetDefaultOverrideToolsVersion_SpecifiedOnlyInConfigFile() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("5.0", defaultToolsVersion); Assert.Equal("3.0", values["4.0"].DefaultOverrideToolsVersion); @@ -2671,8 +2567,7 @@ public void SetDefaultToolsetVersion_SpecifiedNowhere() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - string defaultToolsVersion = ToolsetReader.ReadAllToolsets - ( + string defaultToolsVersion = ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2680,8 +2575,7 @@ public void SetDefaultToolsetVersion_SpecifiedNowhere() #endif new ProjectCollection().EnvironmentProperties, new PropertyDictionary(), - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); string expectedDefault = "2.0"; if (FrameworkLocationHelper.PathToDotNetFrameworkV20 == null) @@ -2719,8 +2613,7 @@ public void PropertiesInToolsetsFromConfigFileAreExpanded() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2728,8 +2621,7 @@ public void PropertiesInToolsetsFromConfigFileAreExpanded() #endif new ProjectCollection().EnvironmentProperties, new ProjectCollection().GlobalPropertiesCollection, - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("v1", values["4.0"].Properties["p1"].EvaluatedValue); // Properties can refer to other properties also defined in the config file @@ -2769,8 +2661,7 @@ public void PropertiesInToolsetsFromConfigFileAreExpandedInToolsPath() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2778,8 +2669,7 @@ public void PropertiesInToolsetsFromConfigFileAreExpandedInToolsPath() #endif new ProjectCollection().EnvironmentProperties, new ProjectCollection().GlobalPropertiesCollection, - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("Microsoft.NET", values["4.0"].Properties["p1"].EvaluatedValue); Assert.Equal("windows", values["4.0"].Properties["p2"].EvaluatedValue); @@ -2821,8 +2711,7 @@ public void GlobalPropertiesInToolsetsAreExpandedButAreNotOverwritten() ProjectCollection e = new ProjectCollection(globalProperties, null, ToolsetDefinitionLocations.None); Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); - ToolsetReader.ReadAllToolsets - ( + ToolsetReader.ReadAllToolsets( values, GetStandardRegistryReader(), #if FEATURE_SYSTEM_CONFIGURATION @@ -2830,8 +2719,7 @@ public void GlobalPropertiesInToolsetsAreExpandedButAreNotOverwritten() #endif e.EnvironmentProperties, e.GlobalPropertiesCollection, - ToolsetDefinitionLocations.Default - ); + ToolsetDefinitionLocations.Default); Assert.Equal("gv1", values["4.0"].Properties["p1"].EvaluatedValue); Assert.Equal("gv1", values["4.0"].Properties["p2"].EvaluatedValue); diff --git a/src/Build.UnitTests/Definition/ToolsetRegistryReader_Tests.cs b/src/Build.UnitTests/Definition/ToolsetRegistryReader_Tests.cs index 5b15463db12..a39a6b336b0 100644 --- a/src/Build.UnitTests/Definition/ToolsetRegistryReader_Tests.cs +++ b/src/Build.UnitTests/Definition/ToolsetRegistryReader_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #if FEATURE_WIN32_REGISTRY using System; @@ -244,8 +245,7 @@ public void ReadRegistry_NonStringData() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Registry has the following structure @@ -463,8 +463,7 @@ public void GetDefaultToolsVersionFromRegistry_NonStringData() Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } private ToolsetRegistryReader GetStandardRegistryReader() { @@ -523,8 +522,7 @@ public void GetOverrideTasksPathFromRegistry_NonStringData() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } /// /// Regular case of getting the default override toolsversion @@ -573,8 +571,7 @@ public void GetDefaultOverrideToolsVersionFromRegistry_NonStringData() string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary(), new PropertyDictionary(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); - } - ); + }); } [Fact] public void ReadToolsets_NoBinPathOrToolsPath() diff --git a/src/Build.UnitTests/Definition/Toolset_Tests.cs b/src/Build.UnitTests/Definition/Toolset_Tests.cs index 5e5a3260b5d..aaaade0b2b2 100644 --- a/src/Build.UnitTests/Definition/Toolset_Tests.cs +++ b/src/Build.UnitTests/Definition/Toolset_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -25,8 +25,7 @@ public void ToolsetCtorErrors1() Assert.Throws(() => { Toolset t = new Toolset(null, "x", new ProjectCollection(), null); - } - ); + }); } [Fact] @@ -35,8 +34,7 @@ public void ToolsetCtorErrors2() Assert.Throws(() => { Toolset t = new Toolset("x", null, new ProjectCollection(), null); - } - ); + }); } [Fact] @@ -45,8 +43,7 @@ public void ToolsetCtorErrors3() Assert.Throws(() => { Toolset t = new Toolset(String.Empty, "x", new ProjectCollection(), null); - } - ); + }); } [Fact] @@ -119,7 +116,7 @@ public void ValidateToolsetTranslation() Toolset t = new Toolset("4.0", "c:\\bar", buildProperties, environmentProperties, globalProperties, subToolsets, "c:\\foo", "4.0", new Dictionary { - ["MSBuildExtensionsPath"] = new ProjectImportPathMatch("MSBuildExtensionsPath", new List {@"c:\foo"}) + ["MSBuildExtensionsPath"] = new ProjectImportPathMatch("MSBuildExtensionsPath", new List { @"c:\foo" }) }); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); diff --git a/src/Build.UnitTests/EndToEndCondition_Tests.cs b/src/Build.UnitTests/EndToEndCondition_Tests.cs index 22845c25d9f..042f448a655 100644 --- a/src/Build.UnitTests/EndToEndCondition_Tests.cs +++ b/src/Build.UnitTests/EndToEndCondition_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Execution; diff --git a/src/Build.UnitTests/EscapingInProjects_Tests.cs b/src/Build.UnitTests/EscapingInProjects_Tests.cs index 5622f9e6bf6..93a4f449f12 100644 --- a/src/Build.UnitTests/EscapingInProjects_Tests.cs +++ b/src/Build.UnitTests/EscapingInProjects_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -51,7 +51,7 @@ public ITaskItem TaskItemParam } } - override public bool Execute() + public override bool Execute() { if (TaskItemParam != null) { @@ -564,8 +564,15 @@ public void InferEscapedOutputsFromTask() } finally { - if (inputFile != null) File.Delete(inputFile); - if (outputFile != null) File.Delete(outputFile); + if (inputFile != null) + { + File.Delete(inputFile); + } + + if (outputFile != null) + { + File.Delete(outputFile); + } } } @@ -650,8 +657,15 @@ public void FullPathMetadataOnItemUnescaped() } finally { - if (File.Exists(projectAbsolutePath)) File.Delete(projectAbsolutePath); - if (Directory.Exists(path)) FileUtilities.DeleteWithoutTrailingBackslash(path); + if (File.Exists(projectAbsolutePath)) + { + File.Delete(projectAbsolutePath); + } + + if (Directory.Exists(path)) + { + FileUtilities.DeleteWithoutTrailingBackslash(path); + } } } diff --git a/src/Build.UnitTests/Evaluation/EvaluationLogging_Tests.cs b/src/Build.UnitTests/Evaluation/EvaluationLogging_Tests.cs index 3f8e86969ed..8b7ecc8f0b0 100644 --- a/src/Build.UnitTests/Evaluation/EvaluationLogging_Tests.cs +++ b/src/Build.UnitTests/Evaluation/EvaluationLogging_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build.UnitTests/Evaluation/Evaluator_Tests.cs b/src/Build.UnitTests/Evaluation/Evaluator_Tests.cs index 43e9e639f96..c58a0dc6ad7 100644 --- a/src/Build.UnitTests/Evaluation/Evaluator_Tests.cs +++ b/src/Build.UnitTests/Evaluation/Evaluator_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -1027,8 +1027,7 @@ public void RejectCircularImportsWithCircularImports() File.Delete(importPath1); File.Delete(importPath2); } - } - ); + }); } /// /// MSBuildDefaultTargets was not getting cleared out between reevaluations. @@ -3066,8 +3065,7 @@ public void VerifyInvalidTreatAsLocalProperty() // Should not reach this point. Assert.True(false); - } - ); + }); } /// /// Basic verification -- whitespace in the TreatAsLocalProperty definition should be trimmed. @@ -4442,7 +4440,7 @@ public void ThrownInvalidProjectExceptionProperlyHandled() File.WriteAllText(primaryProject, projectContents); File.WriteAllText(import, importContents); - InvalidProjectFileException ex = Assert.Throws( () => + InvalidProjectFileException ex = Assert.Throws(() => { Project unused = new Project(primaryProject, null, null); }) @@ -4885,7 +4883,9 @@ private void VerifyPropertyTrackingLoggingScenario(string envVarValue, Action /// /// - private void CreateComplexPropertiesItemsMetadata - ( + private void CreateComplexPropertiesItemsMetadata( out Lookup readOnlyLookup, - out StringMetadataTable itemMetadata - ) + out StringMetadataTable itemMetadata) { ProjectInstance project = ProjectHelpers.CreateEmptyProjectInstance(); Dictionary itemMetadataTable = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1692,8 +1690,7 @@ public void RegistryPropertyInvalidPrefixError() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped(@"$(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\VSTSDB@XXXXDBDirectory)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// In the general case, we should still error for properties that incorrectly miss the Registry: prefix, like @@ -1710,8 +1707,7 @@ public void RegistryPropertyInvalidPrefixError2() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped(@"$(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\VSTSDB@VSTSDBDirectoryX)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } [Fact] @@ -2297,8 +2293,7 @@ public void PropertyFunctionInvalid1() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff($(Value)))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// @@ -2316,8 +2311,7 @@ public void PropertyFunctionInvalid2() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Lgg)]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// Expand property function - invalid since properties don't have properties and don't support '.' in them @@ -2334,8 +2328,7 @@ public void PropertyFunctionInvalid3() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToUpperInvariant().Foo)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// Expand property function - properties don't take arguments @@ -2352,8 +2345,7 @@ public void PropertyFunctionInvalid4() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff($(System.DateTime.Now)))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// @@ -2370,8 +2362,7 @@ public void PropertyFunctionInvalid5() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("$(SomeStuff.ToLowerInvariant()_goop)", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// Expand property function - functions with invalid arguments @@ -2387,8 +2378,7 @@ public void PropertyFunctionInvalid6() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Substring(HELLO!))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// Expand property function - functions with invalid arguments @@ -2404,8 +2394,7 @@ public void PropertyFunctionInvalid7() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("[$(SomeStuff.Substring(-10))]", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// Expand property function that calls a static method with quoted arguments @@ -2420,8 +2409,7 @@ public void PropertyFunctionInvalid8() Expander expander = new Expander(pg, FileSystems.Default); expander.ExpandIntoStringLeaveEscaped("$(([System.DateTime]::Now).ToString(\"MM.dd.yyyy\"))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance); - } - ); + }); } /// /// Expand property function - we don't handle metadata functions @@ -2815,20 +2803,16 @@ public void PropertyFunctionGetFolderPath() [Theory] [InlineData( "$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::Create($([System.Runtime.InteropServices.OSPlatform]::$$platform$$.ToString())))))", - "True" - )] + "True")] [InlineData( @"$([System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform($([System.Runtime.InteropServices.OSPlatform]::$$platform$$)))", - "True" - )] + "True")] [InlineData( "$([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture)", - "$$architecture$$" - )] + "$$architecture$$")] [InlineData( "$([MSBuild]::IsOSPlatform($$platform$$))", - "True" - )] + "True")] public void PropertyFunctionRuntimeInformation(string propertyFunction, string expectedExpansion) { Func formatString = (aString, platform, architecture) => aString @@ -3309,8 +3293,7 @@ public void PropertyFunctionDoesTaskHostExist_Error() // We should have failed before now Assert.True(false); - } - ); + }); } #if FEATURE_APPDOMAIN @@ -3646,8 +3629,8 @@ public void PropertyFunctionHashCodeSameOnlyIfStringSame() "cat1s" }; int[] hashes = stringsToHash.Select(toHash => - (int)expander.ExpandPropertiesLeaveTypedAndEscaped($"$([MSBuild]::StableStringHash('{toHash}'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance) - ).ToArray(); + (int)expander.ExpandPropertiesLeaveTypedAndEscaped($"$([MSBuild]::StableStringHash('{toHash}'))", ExpanderOptions.ExpandProperties, MockElementLocation.Instance)) + .ToArray(); for (int a = 0; a < hashes.Length; a++) { for (int b = a; b < hashes.Length; b++) @@ -3772,7 +3755,7 @@ public void Medley() new string[] {"$([MSBuild]::Escape(';'))", "%3b"}, new string[] {"$([MSBuild]::UnEscape('%3b'))", ";"}, new string[] {"$(e.Substring($(e.Length)))", ""}, - new string[] {"$([System.Int32]::MaxValue)", System.Int32.MaxValue.ToString()}, + new string[] {"$([System.Int32]::MaxValue)", System.Int32.MaxValue.ToString() }, new string[] {"x$()", "x"}, new string[] {"A$(Reg:A)A", "AA"}, new string[] {"A$(Reg:AA)", "A"}, @@ -3972,8 +3955,7 @@ public void Medley() } Assert.True( !success || caughtException, - "FAILURE: Expected '" + errorTests[i] + "' to not parse or not be evaluated but it evaluated to '" + result + "'" - ); + "FAILURE: Expected '" + errorTests[i] + "' to not parse or not be evaluated but it evaluated to '" + result + "'"); } } diff --git a/src/Build.UnitTests/Evaluation/ExpressionShredder_Tests.cs b/src/Build.UnitTests/Evaluation/ExpressionShredder_Tests.cs index 674cf217083..2419fe271db 100644 --- a/src/Build.UnitTests/Evaluation/ExpressionShredder_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ExpressionShredder_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -1158,11 +1158,9 @@ private static Dictionary GetConsumedMetadataReferenc /// /// /// - private static void FindEmbeddedMetadataReferences_OriginalImplementation - ( + private static void FindEmbeddedMetadataReferences_OriginalImplementation( string batchableObjectParameter, - Dictionary consumedMetadataReferences - ) + Dictionary consumedMetadataReferences) { MatchCollection embeddedMetadataReferences = FindEmbeddedMetadataReferenceMatches_OriginalImplementation(batchableObjectParameter); diff --git a/src/Build.UnitTests/Evaluation/ImportFromMSBuildExtensionsPath_Tests.cs b/src/Build.UnitTests/Evaluation/ImportFromMSBuildExtensionsPath_Tests.cs index 21b48075b58..d3bd36d2e35 100644 --- a/src/Build.UnitTests/Evaluation/ImportFromMSBuildExtensionsPath_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ImportFromMSBuildExtensionsPath_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; @@ -21,7 +21,7 @@ namespace Microsoft.Build.UnitTests.Evaluation /// public class ImportFromMSBuildExtensionsPathTests : IDisposable { - string toolsVersionToUse = null; + private string toolsVersionToUse = null; public ImportFromMSBuildExtensionsPathTests() { @@ -844,7 +844,7 @@ public void FallbackImportWithFileNotFoundWhenPropertyNotDefined() } } - void CreateAndBuildProjectForImportFromExtensionsPath(string extnPathPropertyName, Action action) + private void CreateAndBuildProjectForImportFromExtensionsPath(string extnPathPropertyName, Action action) { string extnDir1 = null, extnDir2 = null, mainProjectPath = null; try @@ -877,7 +877,7 @@ void CreateAndBuildProjectForImportFromExtensionsPath(string extnPathPropertyNam } } - void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action setExtensionsPath, + private void CreateAndBuildProjectForImportFromExtensionsPath(string mainProjectPath, string extnPathPropertyName, string[] extnDirs, Action setExtensionsPath, Action action) { try @@ -957,7 +957,7 @@ private ProjectCollection GetProjectCollection(IDictionary globa return projColln; } - string GetNewExtensionsPathAndCreateFile(string extnDirName, string relativeFilePath, string fileContents) + private string GetNewExtensionsPathAndCreateFile(string extnDirName, string relativeFilePath, string fileContents) { var extnDir = Path.Combine(ObjectModelHelpers.TempProjectDir, extnDirName); Directory.CreateDirectory(Path.Combine(extnDir, Path.GetDirectoryName(relativeFilePath))); @@ -966,7 +966,7 @@ string GetNewExtensionsPathAndCreateFile(string extnDirName, string relativeFile return extnDir; } - string GetMainTargetFileContent(string extensionsPathPropertyName = "MSBuildExtensionsPath") + private string GetMainTargetFileContent(string extensionsPathPropertyName = "MSBuildExtensionsPath") { string mainTargetsFileContent = @" @@ -980,7 +980,7 @@ string GetMainTargetFileContent(string extensionsPathPropertyName = "MSBuildExte return String.Format(mainTargetsFileContent, extensionsPathPropertyName); } - string GetExtensionTargetsFileContent1(string extensionsPathPropertyName = "MSBuildExtensionsPath") + private string GetExtensionTargetsFileContent1(string extensionsPathPropertyName = "MSBuildExtensionsPath") { string extnTargetsFileContent1 = @" @@ -998,7 +998,7 @@ string GetExtensionTargetsFileContent1(string extensionsPathPropertyName = "MSBu return String.Format(extnTargetsFileContent1, extensionsPathPropertyName); } - string GetExtensionTargetsFileContent2(string extensionsPathPropertyName = "MSBuildExtensionsPath") + private string GetExtensionTargetsFileContent2(string extensionsPathPropertyName = "MSBuildExtensionsPath") { string extnTargetsFileContent2 = @" diff --git a/src/Build.UnitTests/Evaluation/ItemEvaluation_Tests.cs b/src/Build.UnitTests/Evaluation/ItemEvaluation_Tests.cs index 378c4394b36..c80efa78126 100644 --- a/src/Build.UnitTests/Evaluation/ItemEvaluation_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ItemEvaluation_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -63,7 +63,7 @@ public void IncludeShouldPreserveIntermediaryReferences() }; var itemsForI = items.Where(i => i.ItemType == "i").ToList(); - ObjectModelHelpers.AssertItems(new [] {"a", "b", "c"}, itemsForI, mI2_1); + ObjectModelHelpers.AssertItems(new[] { "a", "b", "c" }, itemsForI, mI2_1); var mI2_2 = new Dictionary { @@ -75,7 +75,7 @@ public void IncludeShouldPreserveIntermediaryReferences() ObjectModelHelpers.AssertItems( new[] { "a", "b", "c", "d", "e", "f", "a", "b", "c" }, itemsForI2, - new [] { mI2_1, mI2_1 , mI2_1, mI2_2, mI2_2, mI2_2, mI2_2, mI2_2, mI2_2 }); + new[] { mI2_1, mI2_1, mI2_1, mI2_2, mI2_2, mI2_2, mI2_2, mI2_2, mI2_2 }); } [Theory] @@ -89,8 +89,7 @@ public void IncludeShouldPreserveIntermediaryReferences() - " - )] + ")] // remove the items via a glob [InlineData( @" @@ -101,8 +100,7 @@ public void IncludeShouldPreserveIntermediaryReferences() - " - )] + ")] public void RemoveShouldPreserveIntermediaryReferences(string content) { IList items = ObjectModelHelpers.GetItemsFromFragment(content, allItems: true); @@ -206,7 +204,7 @@ public void UpdateShouldPreserveIntermediaryReferences() }; var itemsForI = items.Where(i => i.ItemType == "i").ToList(); - ObjectModelHelpers.AssertItems(new[] { "a", "b", "c" }, itemsForI, new [] {a, b, c}); + ObjectModelHelpers.AssertItems(new[] { "a", "b", "c" }, itemsForI, new[] { a, b, c }); var metadataForI2 = new Dictionary { @@ -458,7 +456,7 @@ public void ExcludeSeesIntermediaryState() var items = ObjectModelHelpers.GetItems(projectContent); - ObjectModelHelpers.AssertItems(new []{"2"}, items); + ObjectModelHelpers.AssertItems(new[] { "2" }, items); } [Fact] @@ -586,7 +584,7 @@ public void LazyWildcardExpansionDoesNotEvaluateWildCardsIfNotReferenced() ".Cleanup(); using (var env = TestEnvironment.Create()) { - var projectFiles = env.CreateTestProjectWithFiles(content, new[] {"foo/extra.props", "foo/a.cs", "foo/b.cs", "bar/c.cs", "bar/d.cs"}); + var projectFiles = env.CreateTestProjectWithFiles(content, new[] { "foo/extra.props", "foo/a.cs", "foo/b.cs", "bar/c.cs", "bar/d.cs" }); File.WriteAllText(projectFiles.CreatedFiles[0], import); @@ -650,8 +648,8 @@ public void DifferentExcludesOnSameWildcardProduceDifferentResults(bool cacheFil ObjectModelHelpers.AssertItemEvaluationFromProject( projectContents, - inputFiles: new[] {"a.cs", "b.cs", "c.cs"}, - expectedInclude: new[] {"a.cs", "b.cs", "c.cs", "b.cs", "c.cs", "b.cs"}); + inputFiles: new[] { "a.cs", "b.cs", "c.cs" }, + expectedInclude: new[] { "a.cs", "b.cs", "c.cs", "b.cs", "c.cs", "b.cs" }); } } finally diff --git a/src/Build.UnitTests/Evaluation/ItemSpec_Tests.cs b/src/Build.UnitTests/Evaluation/ItemSpec_Tests.cs index 0923131def0..0ef9b538656 100644 --- a/src/Build.UnitTests/Evaluation/ItemSpec_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ItemSpec_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; @@ -25,7 +25,7 @@ public class ItemSpec_Tests [Fact] public void EachFragmentTypeShouldContributeToItemSpecGlob() { - var itemSpec = CreateItemSpecFrom("a;b*;c*;@(foo)", CreateExpander(new Dictionary {{"foo", new[] {"d", "e"}}})); + var itemSpec = CreateItemSpecFrom("a;b*;c*;@(foo)", CreateExpander(new Dictionary { { "foo", new[] { "d", "e" } } })); var itemSpecGlob = itemSpec.ToMSBuildGlob(); @@ -59,7 +59,7 @@ public void AbsolutePathsShouldMatch() [Fact] public void FragmentGlobsWorkAfterStateIsPartiallyInitializedByOtherOperations() { - var itemSpec = CreateItemSpecFrom("a;b*;c*;@(foo)", CreateExpander(new Dictionary {{"foo", new[] {"d", "e"}}})); + var itemSpec = CreateItemSpecFrom("a;b*;c*;@(foo)", CreateExpander(new Dictionary { { "foo", new[] { "d", "e" } } })); int matches; // cause partial Lazy state to initialize in the ItemExpressionFragment @@ -87,7 +87,7 @@ private ProjectInstanceExpander CreateExpander(Dictionary item { var itemDictionary = ToItemDictionary(items); - return new ProjectInstanceExpander(new PropertyDictionary(), itemDictionary, (IFileSystem) FileSystems.Default); + return new ProjectInstanceExpander(new PropertyDictionary(), itemDictionary, (IFileSystem)FileSystems.Default); } private static ItemDictionary ToItemDictionary(Dictionary itemTypes) diff --git a/src/Build.UnitTests/Evaluation/Preprocessor_Tests.cs b/src/Build.UnitTests/Evaluation/Preprocessor_Tests.cs index c8999cb6d79..c743a3a02da 100644 --- a/src/Build.UnitTests/Evaluation/Preprocessor_Tests.cs +++ b/src/Build.UnitTests/Evaluation/Preprocessor_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; @@ -954,12 +954,11 @@ public void SdkResolverItemsAndPropertiesAreInPreprocessedOutput() var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver(new SdkUtilities.ConfigurableMockSdkResolver( new Build.BackEnd.SdkResolution.SdkResult( new SdkReference("TestPropsAndItemsFromResolverSdk", null, null), - new [] { testDirectory}, + new[] { testDirectory }, version: null, propertiesToAdd, itemsToAdd, - warnings: null - ))); + warnings: null))); string content = @" diff --git a/src/Build.UnitTests/Evaluation/ProjectCollection_Tests.cs b/src/Build.UnitTests/Evaluation/ProjectCollection_Tests.cs index 280ca20b09b..b128559201e 100644 --- a/src/Build.UnitTests/Evaluation/ProjectCollection_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ProjectCollection_Tests.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Evaluation; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Evaluation; using Shouldly; using Xunit; diff --git a/src/Build.UnitTests/Evaluation/ProjectRootElementCache_Tests.cs b/src/Build.UnitTests/Evaluation/ProjectRootElementCache_Tests.cs index 32b32efdea2..b39f50cd243 100644 --- a/src/Build.UnitTests/Evaluation/ProjectRootElementCache_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ProjectRootElementCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System; @@ -50,8 +50,7 @@ public void AddNull() Assert.Throws(() => { ProjectCollection.GlobalProjectCollection.ProjectRootElementCache.Get("c:\\foo", (p, c) => null, true, false); - } - ); + }); } /// /// Verifies that the delegate cannot return a project with a different path @@ -62,8 +61,7 @@ public void AddUnsavedProject() Assert.Throws(() => { ProjectCollection.GlobalProjectCollection.ProjectRootElementCache.Get("c:\\foo", (p, c) => ProjectRootElement.Create("c:\\bar"), true, false); - } - ); + }); } /// /// Tests that an entry added to the cache can be retrieved. diff --git a/src/Build.UnitTests/Evaluation/ProjectSdkImplicitImport_Tests.cs b/src/Build.UnitTests/Evaluation/ProjectSdkImplicitImport_Tests.cs index 59b589aa3d8..1a1918ead7e 100644 --- a/src/Build.UnitTests/Evaluation/ProjectSdkImplicitImport_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ProjectSdkImplicitImport_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -589,18 +589,30 @@ public override string ToString() { var result = new StringBuilder(256); if (Mode.HasValue) + { result.Append(Mode); + } else + { result.Append($"{nameof(Mode)}: "); + } result.Append($", {Template}, {nameof(TemplateName)}: {TemplateName}, {nameof(TemplateVersion)}: {TemplateVersion}"); if (SetNameProperty) + { result.Append(", SetName"); + } + if (SetVersionProperty) + { result.Append(", SetVersion"); + } + if (ExpectedSuccess) + { result.Append(", ExpectedSuccess"); + } return result.ToString(); } @@ -621,26 +633,30 @@ internal void SdkPropertiesAreExpanded(SdkPropertiesAreExpandedCase data) data.TemplateName, _projectInnerContents, data.TemplateVersion, - null - ); + null); var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver( - new MockExpandedSdkResolver(_testSdkDirectory) - ); + new MockExpandedSdkResolver(_testSdkDirectory)); void AddProperty(string name, string value) => (projectOptions.GlobalProperties ??= new Dictionary()).Add(name, value); if (data.SetNameProperty) + { AddProperty(SdkNamePropertyName, SdkName); + } if (data.SetVersionProperty) + { AddProperty(SdkVersionPropertyName, SdkExpectedVersion); + } using var xmlReader = XmlReader.Create(new StringReader(projectContents)); if (!data.ExpectedSuccess) + { projectOptions.LoadSettings |= ProjectLoadSettings.IgnoreMissingImports; + } var project = Project.FromXmlReader(xmlReader, projectOptions); @@ -654,14 +670,12 @@ void AddProperty(string name, string value) => var expectedSdkReferenceRaw = new SdkReference( data.TemplateName, data.TemplateVersion, - data.Template.ExpectedMinimumVersion - ); + data.Template.ExpectedMinimumVersion); var expectedSdkReference = new SdkReference( SdkName, SdkExpectedVersion, - data.Template.ExpectedMinimumVersion - ); + data.Template.ExpectedMinimumVersion); project.Imports.Count.ShouldBe(2); @@ -698,14 +712,11 @@ public static IEnumerable SdkPropertiesAreExpandedData var templates = new[] { new SdkPropertiesAreExpandedDataTemplate( - ProjectTemplateSdkAsAttributeWithVersion, true - ), + ProjectTemplateSdkAsAttributeWithVersion, true), new SdkPropertiesAreExpandedDataTemplate( - ProjectTemplateSdkAsElementWithVersion, false - ), + ProjectTemplateSdkAsElementWithVersion, false), new SdkPropertiesAreExpandedDataTemplate( - ProjectTemplateSdkAsExplicitImportWithVersion, false - ) + ProjectTemplateSdkAsExplicitImportWithVersion, false) }; foreach (var template in templates) @@ -731,8 +742,7 @@ public static IEnumerable SdkPropertiesAreExpandedData yield return new object[] { new SdkPropertiesAreExpandedCase( - mode, template, setName, setVersion, shouldExpand && setName - ) + mode, template, setName, setVersion, shouldExpand && setName) { TemplateName = SdkNameProperty } @@ -741,8 +751,7 @@ public static IEnumerable SdkPropertiesAreExpandedData yield return new object[] { new SdkPropertiesAreExpandedCase( - mode, template, setName, setVersion, shouldExpand && setVersion - ) + mode, template, setName, setVersion, shouldExpand && setVersion) { TemplateVersion = SdkVersionProperty } @@ -751,8 +760,7 @@ public static IEnumerable SdkPropertiesAreExpandedData yield return new object[] { new SdkPropertiesAreExpandedCase( - mode, template, setName, setVersion, shouldExpand && setName && setVersion - ) + mode, template, setName, setVersion, shouldExpand && setName && setVersion) { TemplateName = SdkNameProperty, TemplateVersion = SdkVersionProperty @@ -787,8 +795,8 @@ public override SdkResult Resolve(SdkReference sdk, SdkResolverContext resolverC { SdkName when sdk.Version == SdkExpectedVersion => factory.IndicateSuccess(ResolvedPath, SdkExpectedVersion), - SdkName => factory.IndicateFailure(new[] {ErrorVersion}), - _ => factory.IndicateFailure(new[] {ErrorName}) + SdkName => factory.IndicateFailure(new[] { ErrorVersion }), + _ => factory.IndicateFailure(new[] { ErrorName }) }; } } diff --git a/src/Build.UnitTests/Evaluation/ProjectStringCache_Tests.cs b/src/Build.UnitTests/Evaluation/ProjectStringCache_Tests.cs index ab6af32e07f..6268fee61ea 100644 --- a/src/Build.UnitTests/Evaluation/ProjectStringCache_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ProjectStringCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Text; diff --git a/src/Build.UnitTests/Evaluation/SdkResultEvaluation_Tests.cs b/src/Build.UnitTests/Evaluation/SdkResultEvaluation_Tests.cs index 3584cd1a2b2..4258549fe70 100644 --- a/src/Build.UnitTests/Evaluation/SdkResultEvaluation_Tests.cs +++ b/src/Build.UnitTests/Evaluation/SdkResultEvaluation_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Definition; @@ -31,7 +31,7 @@ public class SdkResultEvaluation_Tests : IDisposable public SdkResultEvaluation_Tests(ITestOutputHelper log) { _log = log; - + _env = TestEnvironment.Create(); _originalWarnOnUnitializedProperty = BuildParameters.WarnOnUninitializedProperty; @@ -119,9 +119,7 @@ public void SdkResolverCanReturnNoPaths(bool includePropertiesAndItems) version: null, propertiesToAdd, itemsToAdd, - warnings: null - )) - ); + warnings: null))); string projectContent = @" @@ -258,9 +256,7 @@ public void SdkResolverCanReturnMultiplePaths(bool includePropertiesAndItems) version: null, propertiesToAdd, itemsToAdd, - warnings: null - )) - ); + warnings: null))); string projectContent = @" @@ -359,9 +355,7 @@ public void SdkResolverCanReturnTheSamePropertiesAndItemsMultipleTimes() version: null, propertiesToAdd, itemsToAdd, - warnings: null - )) - ); + warnings: null))); string projectContent = @" @@ -443,9 +437,7 @@ public void SdkResolverCanReturnSpecialCharacters() version: null, propertiesToAdd, itemsToAdd, - warnings: null - )) - ); + warnings: null))); string projectContent = @" diff --git a/src/Build.UnitTests/Evaluation/SemiColonTokenizer_Tests.cs b/src/Build.UnitTests/Evaluation/SemiColonTokenizer_Tests.cs index 18442c49de2..505b4e12f5b 100644 --- a/src/Build.UnitTests/Evaluation/SemiColonTokenizer_Tests.cs +++ b/src/Build.UnitTests/Evaluation/SemiColonTokenizer_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; diff --git a/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs b/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs index 05ee16eecac..e082039d337 100644 --- a/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs +++ b/src/Build.UnitTests/Evaluation/SimpleProjectRootElementCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Construction; diff --git a/src/Build.UnitTests/Evaluation/SimpleVersion_Tests.cs b/src/Build.UnitTests/Evaluation/SimpleVersion_Tests.cs index 3bb784def3e..cfb3c3ad477 100644 --- a/src/Build.UnitTests/Evaluation/SimpleVersion_Tests.cs +++ b/src/Build.UnitTests/Evaluation/SimpleVersion_Tests.cs @@ -1,8 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. using Microsoft.Build.Utilities; using System; @@ -241,7 +238,7 @@ public static IEnumerable Parse_Invalid_TestData() yield return new object[] { "1,2,3,4", typeof(FormatException) }; // Input contains invalid separator yield return new object[] { "1.2.3.4.5", typeof(FormatException) }; // Input has more than 4 version components - yield return new object[] { "1." , typeof(FormatException) }; // Input contains empty component + yield return new object[] { "1.", typeof(FormatException) }; // Input contains empty component yield return new object[] { "1.2,", typeof(FormatException) }; // Input contains empty component yield return new object[] { "1.2.3.", typeof(FormatException) }; // Input contains empty component yield return new object[] { "1.2.3.4.", typeof(FormatException) }; // Input contains empty component @@ -285,7 +282,7 @@ public static void Parse_InvalidInput_ThrowsException(string input, Type excepti public static IEnumerable ToString_TestData() { - yield return new object[] { new SimpleVersion(1), "1.0.0.0"}; + yield return new object[] { new SimpleVersion(1), "1.0.0.0" }; yield return new object[] { new SimpleVersion(1, 2), "1.2.0.0" }; yield return new object[] { new SimpleVersion(1, 2, 3), "1.2.3.0" }; yield return new object[] { new SimpleVersion(1, 2, 3, 4), "1.2.3.4" }; diff --git a/src/Build.UnitTests/Evaluation/ToolsetConfigurationNet5_Tests.cs b/src/Build.UnitTests/Evaluation/ToolsetConfigurationNet5_Tests.cs index 8c0126af739..30f95c0e0bb 100644 --- a/src/Build.UnitTests/Evaluation/ToolsetConfigurationNet5_Tests.cs +++ b/src/Build.UnitTests/Evaluation/ToolsetConfigurationNet5_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if !FEATURE_SYSTEM_CONFIGURATION /* This test is designed especially to test Configuration parsing in net5.0 diff --git a/src/Build.UnitTests/EvaluationProfiler_Tests.cs b/src/Build.UnitTests/EvaluationProfiler_Tests.cs index 68be0395890..27438bec72e 100644 --- a/src/Build.UnitTests/EvaluationProfiler_Tests.cs +++ b/src/Build.UnitTests/EvaluationProfiler_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Immutable; diff --git a/src/Build.UnitTests/EventArgsFormatting_Tests.cs b/src/Build.UnitTests/EventArgsFormatting_Tests.cs index 6ab17518cfc..0faede8a251 100644 --- a/src/Build.UnitTests/EventArgsFormatting_Tests.cs +++ b/src/Build.UnitTests/EventArgsFormatting_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Build.UnitTests/ExpressionTreeExpression_Tests.cs b/src/Build.UnitTests/ExpressionTreeExpression_Tests.cs index a065e5de133..bd9f5ac973b 100644 --- a/src/Build.UnitTests/ExpressionTreeExpression_Tests.cs +++ b/src/Build.UnitTests/ExpressionTreeExpression_Tests.cs @@ -1,3 +1,6 @@ +// 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.Collections.Generic; using System.IO; @@ -24,7 +27,7 @@ public class ExpressionTest : IDisposable private readonly Expander _expander; - public static readonly IEnumerable TrueTests = new [] + public static readonly IEnumerable TrueTests = new[] { "true or (SHOULDNOTEVALTHIS)", // short circuit "(true and false) or true", @@ -160,9 +163,9 @@ public class ExpressionTest : IDisposable "'59264.59264' == '59264.59264'", "1" + new String('0', 500) + "==" + "1" + new String('0', 500), /* too big for double, eval as string */ "'1" + new String('0', 500) + "'=='" + "1" + new String('0', 500) + "'" /* too big for double, eval as string */ - }.Select(s => new[] {s}); + }.Select(s => new[] { s }); - public static readonly IEnumerable FalseTests = new [] { + public static readonly IEnumerable FalseTests = new[] { "false and SHOULDNOTEVALTHIS", // short circuit "$(a)!=no", "$(b)==1.1", @@ -219,7 +222,7 @@ public class ExpressionTest : IDisposable "'1" + new String('0', 500) + "'=='01" + new String('0', 500) + "'" /* too big for double, eval as string */ }.Select(s => new[] { s }); - public static readonly IEnumerable ErrorTests = new [] { + public static readonly IEnumerable ErrorTests = new[] { "$", "$(", "$()", @@ -413,7 +416,10 @@ public void Dispose() { foreach (string file in FilesWithExistenceChecks) { - if (File.Exists(file)) File.Delete(file); + if (File.Exists(file)) + { + File.Delete(file); + } } } @@ -429,16 +435,14 @@ public void EvaluateAVarietyOfTrueExpressions(string expression) Parser p = new Parser(); GenericExpressionNode tree = p.Parse(expression, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = - new ConditionEvaluator.ConditionEvaluationState - ( + new ConditionEvaluator.ConditionEvaluationState( expression, _expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); Assert.True(tree.Evaluate(state), "expected true from '" + expression + "'"); } @@ -455,16 +459,14 @@ public void EvaluateAVarietyOfFalseExpressions(string expression) Parser p = new Parser(); GenericExpressionNode tree = p.Parse(expression, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = - new ConditionEvaluator.ConditionEvaluationState - ( + new ConditionEvaluator.ConditionEvaluationState( expression, _expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); Assert.False(tree.Evaluate(state), "expected false from '" + expression + "' and got true"); } @@ -489,16 +491,14 @@ public void EvaluateAVarietyOfErrorExpressions(string expression) var tree = p.Parse(expression, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = - new ConditionEvaluator.ConditionEvaluationState - ( + new ConditionEvaluator.ConditionEvaluationState( expression, _expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); tree.Evaluate(state); } diff --git a/src/Build.UnitTests/ExpressionTree_Tests.cs b/src/Build.UnitTests/ExpressionTree_Tests.cs index 4601c894936..70ce8bb76d5 100644 --- a/src/Build.UnitTests/ExpressionTree_Tests.cs +++ b/src/Build.UnitTests/ExpressionTree_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -109,16 +109,14 @@ public void FunctionTests() tree = p.Parse(command, ParserOptions.AllowAll, ElementLocation.EmptyLocation); ConditionEvaluator.IConditionEvaluationState state = - new ConditionEvaluator.ConditionEvaluationState - ( + new ConditionEvaluator.ConditionEvaluationState( command, expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); value = tree.Evaluate(state); Assert.True(value); @@ -334,16 +332,14 @@ public void ConditionedPropertyUpdateTests() Expander expander = new Expander(new PropertyDictionary(), itemBag, FileSystems.Default); Dictionary> conditionedProperties = new Dictionary>(); ConditionEvaluator.IConditionEvaluationState state = - new ConditionEvaluator.ConditionEvaluationState - ( + new ConditionEvaluator.ConditionEvaluationState( String.Empty, expander, ExpanderOptions.ExpandAll, conditionedProperties, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); AssertParseEvaluate(p, "'0' == '1'", expander, false, state); Assert.Empty(conditionedProperties); @@ -445,16 +441,14 @@ private void AssertParseEvaluate(Parser p, string expression, Expander - ( + new ConditionEvaluator.ConditionEvaluationState( String.Empty, expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); } bool result = tree.Evaluate(state); @@ -483,16 +477,14 @@ private void AssertParseEvaluateThrow(Parser p, string expression, Expander - ( + new ConditionEvaluator.ConditionEvaluationState( String.Empty, expander, ExpanderOptions.ExpandAll, null, Directory.GetCurrentDirectory(), ElementLocation.EmptyLocation, - FileSystems.Default - ); + FileSystems.Default); } tree.Evaluate(state); } diff --git a/src/Build.UnitTests/FileLogger_Tests.cs b/src/Build.UnitTests/FileLogger_Tests.cs index e7e6db9e2fe..729864e9b1c 100644 --- a/src/Build.UnitTests/FileLogger_Tests.cs +++ b/src/Build.UnitTests/FileLogger_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 436 @@ -67,7 +67,10 @@ public void BasicNoExistingFile() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } } @@ -90,10 +93,12 @@ public void InvalidFile() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } - } - ); + }); } /// /// Specific verbosity overrides global verbosity @@ -119,7 +124,10 @@ public void SpecificVerbosity() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } } @@ -169,8 +177,7 @@ public void InvalidVerbosity() fl.Parameters = "verbosity=CookiesAndCream"; EventSourceSink es = new EventSourceSink(); fl.Initialize(es); - } - ); + }); } /// /// Invalid encoding setting @@ -192,10 +199,12 @@ public void InvalidEncoding() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } - } - ); + }); } /// @@ -218,7 +227,10 @@ public void ValidEncoding() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } } @@ -243,7 +255,10 @@ public void ValidEncoding2() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } } @@ -285,7 +300,10 @@ public void BasicExistingFileNoAppend() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } } @@ -306,7 +324,10 @@ public void BasicExistingFileAppend() } finally { - if (log != null) File.Delete(log); + if (log != null) + { + File.Delete(log); + } } } @@ -344,7 +365,7 @@ public void EmptyErrorLogUsingWarningsErrorsOnly(string loggerOption) // Note: Only the ParallelConsoleLogger supports this scenario (log file empty on no error/warn). We // need to explicitly enable it here with the 'ENABLEMPLOGGING' flag. - FileLogger fileLogger = new FileLogger {Parameters = $"{loggerOption};logfile={logFile};ENABLEMPLOGGING" }; + FileLogger fileLogger = new FileLogger { Parameters = $"{loggerOption};logfile={logFile};ENABLEMPLOGGING" }; Project project = ObjectModelHelpers.CreateInMemoryProject(@" @@ -519,8 +540,7 @@ public void DistributedLoggerNullEmpty() fileLogger.Parameters = "logfile="; fileLogger.Initialize(new EventSourceSink()); Assert.True(false); - } - ); + }); } #endregion diff --git a/src/Build.UnitTests/FileUtilitiesRegex_Tests.cs b/src/Build.UnitTests/FileUtilitiesRegex_Tests.cs index 463d10fb622..0a0b99e5b37 100644 --- a/src/Build.UnitTests/FileUtilitiesRegex_Tests.cs +++ b/src/Build.UnitTests/FileUtilitiesRegex_Tests.cs @@ -1,4 +1,7 @@ -using Xunit; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; using Shouldly; using Microsoft.Build.Shared; using System.Text.RegularExpressions; diff --git a/src/Build.UnitTests/FixPathOnUnix_Tests.cs b/src/Build.UnitTests/FixPathOnUnix_Tests.cs index 01b2865b81e..e74cfd7b14e 100644 --- a/src/Build.UnitTests/FixPathOnUnix_Tests.cs +++ b/src/Build.UnitTests/FixPathOnUnix_Tests.cs @@ -1,4 +1,7 @@ -using System.IO; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.IO; using Microsoft.Build.Evaluation; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Build.UnitTests/Globbing/CompositeGlob_Tests.cs b/src/Build.UnitTests/Globbing/CompositeGlob_Tests.cs index c97598d2dcd..50ef83fdbda 100644 --- a/src/Build.UnitTests/Globbing/CompositeGlob_Tests.cs +++ b/src/Build.UnitTests/Globbing/CompositeGlob_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -126,10 +126,7 @@ public void MSBuildGlobVisitorShouldFindAllLeaves() new CompositeGlob( new MSBuildGlobWithGaps(g3, MSBuildGlob.Parse("x*")), new CompositeGlob( - g4 - ) - ) - ); + g4))); var leafGlobs = composite.GetParsedGlobs().ToArray(); diff --git a/src/Build.UnitTests/Globbing/MSBuildGlobWithGaps_Tests.cs b/src/Build.UnitTests/Globbing/MSBuildGlobWithGaps_Tests.cs index d943538c805..2180eb1a5d9 100644 --- a/src/Build.UnitTests/Globbing/MSBuildGlobWithGaps_Tests.cs +++ b/src/Build.UnitTests/Globbing/MSBuildGlobWithGaps_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Linq; diff --git a/src/Build.UnitTests/Globbing/MSBuildGlob_Tests.cs b/src/Build.UnitTests/Globbing/MSBuildGlob_Tests.cs index 5cae35dbd70..cc551762e11 100644 --- a/src/Build.UnitTests/Globbing/MSBuildGlob_Tests.cs +++ b/src/Build.UnitTests/Globbing/MSBuildGlob_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -80,18 +80,15 @@ public void GlobFromRootWithInvalidPathThrows() [InlineData( "a/b/c", "**", - "a/b/c" - )] + "a/b/c")] [InlineData( "a/b/c", "../../**", - "a" - )] + "a")] [InlineData( "a/b/c", "../d/e/**", - "a/b/d/e" - )] + "a/b/d/e")] public void GlobWithRelativeFixedDirectoryPartShouldMismatchTheGlobRoot(string globRoot, string filespec, string expectedFixedDirectoryPart) { var glob = MSBuildGlob.Parse(globRoot, filespec); diff --git a/src/Build.UnitTests/Graph/GetCompatiblePlatformGraph_Tests.cs b/src/Build.UnitTests/Graph/GetCompatiblePlatformGraph_Tests.cs index f198b324c2c..fdce69b8b3b 100644 --- a/src/Build.UnitTests/Graph/GetCompatiblePlatformGraph_Tests.cs +++ b/src/Build.UnitTests/Graph/GetCompatiblePlatformGraph_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -137,7 +137,7 @@ public void ResolvesViaPlatformLookupTable() x64;x86;AnyCPU "); - + ProjectGraph graph = new ProjectGraph(entryProject.Path); GetFirstNodeWithProjectNumber(graph, 2).ProjectInstance.GlobalProperties["Platform"].ShouldBe("x64"); } @@ -165,7 +165,7 @@ public void ResolvesViaProjectReferencesPlatformLookupTable() win32=x86 "); - + ProjectGraph graph = new ProjectGraph(entryProject.Path); GetFirstNodeWithProjectNumber(graph, 2).ProjectInstance.GlobalProperties["Platform"].ShouldBe("x86"); } @@ -220,7 +220,7 @@ public void ResolvesViaSamePlatform() x86;x64;AnyCPU "); - + ProjectGraph graph = new ProjectGraph(entryProject.Path); GetFirstNodeWithProjectNumber(graph, 2).ProjectInstance.GlobalProperties["Platform"].ShouldBe("x86"); } @@ -247,7 +247,7 @@ public void FailsToResolve() x64 "); - + ProjectGraph graph = new ProjectGraph(entryProject.Path); // Here we are checking if platform is defined. in this case it should not be since Platorm would be set to the value this project defaults as // in order to avoid dual build errors we remove platform in order to avoid the edge case where a project has global platform set and does not have global platform set @@ -277,7 +277,7 @@ public void PlatformIsChosenAsDefault() x86;AnyCPU "); - + ProjectGraph graph = new ProjectGraph(entryProject.Path); GetFirstNodeWithProjectNumber(graph, 2).ProjectInstance.GetPropertyValue("Platform").ShouldBe(GetFirstNodeWithProjectNumber(graph, 1).ProjectInstance.GetPropertyValue("Platform")); } diff --git a/src/Build.UnitTests/Graph/GraphLoadedFromSolution_tests.cs b/src/Build.UnitTests/Graph/GraphLoadedFromSolution_tests.cs index 4d28600f8a1..3bc916aa4bb 100644 --- a/src/Build.UnitTests/Graph/GraphLoadedFromSolution_tests.cs +++ b/src/Build.UnitTests/Graph/GraphLoadedFromSolution_tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -175,7 +175,7 @@ public static IEnumerable GraphsWithUniformSolutionConfigurations foreach (var graph in Graphs) { foreach ( - var currentSolutionConfigurationPlatform in SolutionFileBuilder.SolutionConfigurationPlatformsDefaults.Concat(new SolutionConfigurationInSolution[] {null})) + var currentSolutionConfigurationPlatform in SolutionFileBuilder.SolutionConfigurationPlatformsDefaults.Concat(new SolutionConfigurationInSolution[] { null })) { yield return new[] { @@ -228,7 +228,7 @@ public void SolutionParserIgnoresProjectConfigurationsThatDoNotFullyMatchAnySolu { {"1", _env.CreateFile("1.csproj", string.Empty).Path} }, - SolutionConfigurationPlatforms = new[] {new SolutionConfigurationInSolution("Foo", "Bar")}, + SolutionConfigurationPlatforms = new[] { new SolutionConfigurationInSolution("Foo", "Bar") }, ProjectConfigurations = new Dictionary> { { @@ -265,7 +265,7 @@ public static IEnumerable SolutionOnlyDependenciesData {1, null}, {2, null} }, - new[] {(1, 2)}, // solution only edges + new[] {(1, 2) }, // solution only edges false, // is there a cycle false // solution edges overlap with graph edges }; @@ -277,7 +277,7 @@ public static IEnumerable SolutionOnlyDependenciesData {1, null}, {2, null} }, - new[] {(1, 2), (2, 1)}, + new[] {(1, 2), (2, 1) }, true, false }; @@ -292,7 +292,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, null}, {5, null} }, - new[] {(1, 2), (1, 3), (2, 4), (3,4), (4, 5)}, + new[] {(1, 2), (1, 3), (2, 4), (3,4), (4, 5) }, false, false }; @@ -307,7 +307,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, null}, {5, null} }, - new[] {(1, 2), (1, 3), (2, 4), (3, 4), (4, 5), (2, 3)}, + new[] {(1, 2), (1, 3), (2, 4), (3, 4), (4, 5), (2, 3) }, false, false }; @@ -322,7 +322,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, null}, {5, null} }, - new[] {(1, 3), (2, 3), (3, 4), (3, 5), (5, 4), (2, 1)}, + new[] {(1, 3), (2, 3), (3, 4), (3, 5), (5, 4), (2, 1) }, false, false }; @@ -333,7 +333,7 @@ public static IEnumerable SolutionOnlyDependenciesData { {1, new []{2}}, }, - new[] {(1, 2)}, + new[] {(1, 2) }, false, true }; @@ -344,7 +344,7 @@ public static IEnumerable SolutionOnlyDependenciesData { {1, new []{2}}, }, - new[] {(1, 2), (1, 2)}, + new[] {(1, 2), (1, 2) }, false, true }; @@ -355,7 +355,7 @@ public static IEnumerable SolutionOnlyDependenciesData { {1, new []{2}}, }, - new[] {(2, 1)}, + new[] {(2, 1) }, true, false }; @@ -370,7 +370,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, new []{5}}, {5, null} }, - new[] {(3, 2)}, + new[] {(3, 2) }, false, false }; @@ -385,7 +385,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, new []{5}}, {5, null} }, - new[] {(1, 2), (1, 3), (3, 2), (1, 5)}, + new[] {(1, 2), (1, 3), (3, 2), (1, 5) }, false, true }; @@ -400,7 +400,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, new []{5}}, {5, null} }, - new[] {(3, 2), (5, 3)}, + new[] {(3, 2), (5, 3) }, true, false }; @@ -415,7 +415,7 @@ public static IEnumerable SolutionOnlyDependenciesData {4, new []{5}}, {5, null} }, - new[] {(5, 3)}, + new[] {(5, 3) }, true, false }; @@ -428,7 +428,7 @@ public static IEnumerable SolutionOnlyDependenciesData {2, new[] {3}}, {3, new[] {4}}, }, - new[] {(1,3), (2, 4)}, + new[] {(1,3), (2, 4) }, false, false }; @@ -441,7 +441,7 @@ public static IEnumerable SolutionOnlyDependenciesData {2, new[] {3}}, {3, new[] {4}}, }, - new[] {(1,3), (2, 4), (1, 2), (2, 3), (3, 4)}, + new[] {(1,3), (2, 4), (1, 2), (2, 3), (3, 4) }, false, true }; @@ -454,7 +454,7 @@ public static IEnumerable SolutionOnlyDependenciesData {3, null}, {4, null} }, - new[] {(3, 2), (2, 4)}, + new[] {(3, 2), (2, 4) }, false, false }; @@ -467,7 +467,7 @@ public static IEnumerable SolutionOnlyDependenciesData {3, null}, {4, null} }, - new[] {(3, 2), (2, 4), (4, 1)}, + new[] {(3, 2), (2, 4), (4, 1) }, true, false }; @@ -579,7 +579,7 @@ public void SolutionEdgesShouldNotOverwriteMultitargetingEdges() {"3", GraphTestingUtilities.CreateProjectFile(_env, 3, new[] {4}, extraContent: MultitargetingSpecificationPropertyGroup).Path}, {"4", GraphTestingUtilities.CreateProjectFile(_env, 4).Path} }, - SolutionDependencies = new[] {("1", "2"), ("3", "4")} + SolutionDependencies = new[] { ("1", "2"), ("3", "4") } }.BuildSolution(); var graph = new ProjectGraph(_env.CreateFile("solution.sln", solutionContents).Path); @@ -617,8 +617,8 @@ public void GraphConstructionShouldThrowOnMissingSolutionDependencies() { var solutionContents = SolutionFileBuilder.FromGraphEdges( _env, - new Dictionary {{1, null}, {2, null}}, - new[] {("1", new[] {Guid.NewGuid().ToString("B")})}).BuildSolution(); + new Dictionary { { 1, null }, { 2, null } }, + new[] { ("1", new[] { Guid.NewGuid().ToString("B") }) }).BuildSolution(); var solutionFile = _env.CreateFile( "solution.sln", diff --git a/src/Build.UnitTests/Graph/GraphTestingUtilities.cs b/src/Build.UnitTests/Graph/GraphTestingUtilities.cs index fd6e5a951c3..6b415681733 100644 --- a/src/Build.UnitTests/Graph/GraphTestingUtilities.cs +++ b/src/Build.UnitTests/Graph/GraphTestingUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Collections.Immutable; @@ -17,7 +17,7 @@ namespace Microsoft.Build.Graph.UnitTests { internal static class GraphTestingUtilities { - public static readonly ImmutableDictionary EmptyGlobalProperties = new Dictionary {{PropertyNames.IsGraphBuild, "true"}}.ToImmutableDictionary(); + public static readonly ImmutableDictionary EmptyGlobalProperties = new Dictionary { { PropertyNames.IsGraphBuild, "true" } }.ToImmutableDictionary(); public const string InnerBuildPropertyName = "InnerBuild"; public const string InnerBuildPropertiesName = "InnerBuildProperties"; @@ -216,8 +216,7 @@ internal static TransientTestFile CreateProjectFile( int[] projectReferences = null, Dictionary projectReferenceTargets = null, string defaultTargets = null, - string extraContent = null - ) + string extraContent = null) { return Helpers.CreateProjectFile( env, diff --git a/src/Build.UnitTests/Graph/IsolateProjects_Tests.cs b/src/Build.UnitTests/Graph/IsolateProjects_Tests.cs index dbd8b9edae1..78e73980389 100644 --- a/src/Build.UnitTests/Graph/IsolateProjects_Tests.cs +++ b/src/Build.UnitTests/Graph/IsolateProjects_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -156,11 +156,11 @@ public void Dispose() _env.Dispose(); } - + [Theory] [InlineData(BuildResultCode.Success, new string[] { })] - [InlineData(BuildResultCode.Success, new[] {"BuildSelf"})] + [InlineData(BuildResultCode.Success, new[] { "BuildSelf" })] public void CacheAndUndeclaredReferenceEnforcementShouldAcceptSelfReferences(BuildResultCode expectedBuildResult, string[] targets) { AssertBuild(targets, @@ -175,7 +175,7 @@ public void CacheAndUndeclaredReferenceEnforcementShouldAcceptSelfReferences(Bui [Fact] public void CacheAndUndeclaredReferenceEnforcementShouldAcceptCallTarget() { - AssertBuild(new []{"CallTarget"}, + AssertBuild(new[] { "CallTarget" }, (result, logger) => { result.OverallResult.ShouldBe(BuildResultCode.Success); @@ -199,7 +199,7 @@ public void CacheEnforcementShouldFailWhenReferenceWasNotPreviouslyBuiltWithoutC private void CacheEnforcementImpl(bool addContinueOnError) { AssertBuild( - new[] {"BuildDeclaredReference"}, + new[] { "BuildDeclaredReference" }, (result, logger) => { result.OverallResult.ShouldBe(BuildResultCode.Failure); @@ -272,7 +272,7 @@ public void EnforcementsCanBeSkipped(string targetName) [InlineData("BuildDeclaredReferenceViaTask")] public void CacheEnforcementShouldAcceptPreviouslyBuiltReferences(string targetName) { - AssertBuild(new []{ targetName }, + AssertBuild(new[] { targetName }, (result, logger) => { result.OverallResult.ShouldBe(BuildResultCode.Success); @@ -284,9 +284,9 @@ public void CacheEnforcementShouldAcceptPreviouslyBuiltReferences(string targetN [Theory] [InlineData(false, "BuildUndeclaredReference")] -// [InlineData(false, "BuildUndeclaredReferenceViaTask")] https://github.com/dotnet/msbuild/issues/4385 + // [InlineData(false, "BuildUndeclaredReferenceViaTask")] https://github.com/dotnet/msbuild/issues/4385 [InlineData(true, "BuildUndeclaredReference")] -// [InlineData(true, "BuildUndeclaredReferenceViaTask")] https://github.com/dotnet/msbuild/issues/4385 + // [InlineData(true, "BuildUndeclaredReferenceViaTask")] https://github.com/dotnet/msbuild/issues/4385 public void UndeclaredReferenceEnforcementShouldFailOnUndeclaredReference(bool addContinueOnError, string targetName) { AssertBuild(new[] { targetName }, @@ -303,7 +303,7 @@ public void UndeclaredReferenceEnforcementShouldFailOnUndeclaredReference(bool a [Theory] [InlineData("BuildUndeclaredReference")] -// [InlineData("BuildUndeclaredReferenceViaTask")] https://github.com/dotnet/msbuild/issues/4385 + // [InlineData("BuildUndeclaredReferenceViaTask")] https://github.com/dotnet/msbuild/issues/4385 public void UndeclaredReferenceEnforcementShouldFailOnPreviouslyBuiltButUndeclaredReferences(string targetName) { AssertBuild(new[] { targetName }, @@ -338,9 +338,9 @@ public static IEnumerable UndeclaredReferenceEnforcementShouldNormaliz Func ToDuplicateSlashes = path => path.Replace("/", "//").Replace(@"\", @"\\"); - var targetNames = new []{"BuildDeclaredReference", /*"BuildDeclaredReferenceViaTask"*/}; + var targetNames = new[] { "BuildDeclaredReference", /*"BuildDeclaredReferenceViaTask"*/}; - var functions = new[] {Preserve, FullToRelative, ToForwardSlash, ToBackSlash, ToDuplicateSlashes}; + var functions = new[] { Preserve, FullToRelative, ToForwardSlash, ToBackSlash, ToDuplicateSlashes }; foreach (var projectReferenceModifier in functions) { @@ -364,7 +364,7 @@ public static IEnumerable UndeclaredReferenceEnforcementShouldNormaliz [MemberData(nameof(UndeclaredReferenceEnforcementShouldNormalizeFilePathsTestData))] public void UndeclaredReferenceEnforcementShouldNormalizeFilePaths(Func projectReferenceModifier, Func msbuildProjectModifier, string targetName) { - AssertBuild(new []{targetName}, + AssertBuild(new[] { targetName }, (result, logger) => { result.OverallResult.ShouldBe(BuildResultCode.Success); @@ -417,13 +417,13 @@ private void AssertBuild( { if (buildDeclaredReference) { - buildManagerSession.BuildProjectFile(declaredReferenceFile, new[] {"DeclaredReferenceTarget"}) + buildManagerSession.BuildProjectFile(declaredReferenceFile, new[] { "DeclaredReferenceTarget" }) .OverallResult.ShouldBe(BuildResultCode.Success); } if (buildUndeclaredReference) { - buildManagerSession.BuildProjectFile(undeclaredReferenceFile, new[] {"UndeclaredReferenceTarget"}) + buildManagerSession.BuildProjectFile(undeclaredReferenceFile, new[] { "UndeclaredReferenceTarget" }) .OverallResult.ShouldBe(BuildResultCode.Success); } @@ -481,7 +481,7 @@ public void SkippedTargetsShouldNotTriggerCacheMissEnforcement() { // seed caches with results from the reference buildManagerSession.BuildProjectFile(referenceFile).OverallResult.ShouldBe(BuildResultCode.Success); - buildManagerSession.BuildProjectFile(referenceFile, new []{"A"}).OverallResult.ShouldBe(BuildResultCode.Success); + buildManagerSession.BuildProjectFile(referenceFile, new[] { "A" }).OverallResult.ShouldBe(BuildResultCode.Success); buildManagerSession.BuildProjectFile(projectFile).OverallResult.ShouldBe(BuildResultCode.Success); diff --git a/src/Build.UnitTests/Graph/ParallelWorkSet_Tests.cs b/src/Build.UnitTests/Graph/ParallelWorkSet_Tests.cs index 26575faf9aa..95538f1b5ac 100644 --- a/src/Build.UnitTests/Graph/ParallelWorkSet_Tests.cs +++ b/src/Build.UnitTests/Graph/ParallelWorkSet_Tests.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Threading; using Microsoft.Build.UnitTests; @@ -267,7 +270,7 @@ private void TestParallelWorkSet(ParallelWorkSetTestCase tt) _workSet.WaitForAllWorkAndComplete(); _workSet.IsCompleted.ShouldBeTrue(); - _workSet.CompletedWork.ShouldBeSameIgnoringOrder((IReadOnlyCollection>) tt.ExpectedCompletedWork); + _workSet.CompletedWork.ShouldBeSameIgnoringOrder((IReadOnlyCollection>)tt.ExpectedCompletedWork); } } } diff --git a/src/Build.UnitTests/Graph/ProjectGraph_Tests.cs b/src/Build.UnitTests/Graph/ProjectGraph_Tests.cs index 273d6d4a7eb..841a48e4e64 100644 --- a/src/Build.UnitTests/Graph/ProjectGraph_Tests.cs +++ b/src/Build.UnitTests/Graph/ProjectGraph_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -32,8 +32,8 @@ public class ProjectGraphTests : IDisposable "; - private static string[] NonOuterBuildTargets = {"AHelperOuter", "AHelperInner", "A"}; - private static string[] OuterBuildTargets = {"AHelperOuter"}; + private static string[] NonOuterBuildTargets = { "AHelperOuter", "AHelperInner", "A" }; + private static string[] OuterBuildTargets = { "AHelperOuter" }; private const string OuterBuildSpecificationWithProjectReferenceTargets = MultitargetingSpecificationPropertyGroup + ProjectReferenceTargetsWithMultitargeting; @@ -51,7 +51,7 @@ public void ConstructWithNoNodes() projectGraph.EntryPointNodes.ShouldBeEmpty(); projectGraph.GraphRoots.ShouldBeEmpty(); projectGraph.ProjectNodesTopologicallySorted.ShouldBeEmpty(); - projectGraph.GetTargetLists(new []{"restore", "build"}).ShouldBeEmpty(); + projectGraph.GetTargetLists(new[] { "restore", "build" }).ShouldBeEmpty(); } [Fact] @@ -141,13 +141,13 @@ public void UpdatingReferencesIsBidirectional() node.AddProjectReference(reference1, referenceItem1, edges); node.AddProjectReference(reference2, referenceItem2, edges); - node.ProjectReferences.ShouldBeSameIgnoringOrder(new []{reference1, reference2}); + node.ProjectReferences.ShouldBeSameIgnoringOrder(new[] { reference1, reference2 }); node.ReferencingProjects.ShouldBeEmpty(); - reference1.ReferencingProjects.ShouldBeSameIgnoringOrder(new[] {node}); + reference1.ReferencingProjects.ShouldBeSameIgnoringOrder(new[] { node }); reference1.ProjectReferences.ShouldBeEmpty(); - reference2.ReferencingProjects.ShouldBeSameIgnoringOrder(new[] {node}); + reference2.ReferencingProjects.ShouldBeSameIgnoringOrder(new[] { node }); reference2.ProjectReferences.ShouldBeEmpty(); edges[(node, reference1)].ShouldBe(referenceItem1); @@ -302,7 +302,7 @@ public void ConstructWithCycle() TransientTestFile entryProject = CreateProjectFile(env, 1, new[] { 2 }); var proj2 = CreateProjectFile(env, 2, new[] { 3 }); var proj3 = CreateProjectFile(env, 3, new[] { 1 }); - var projectsInCycle = new List {entryProject.Path, proj3.Path, proj2.Path, entryProject.Path}; + var projectsInCycle = new List { entryProject.Path, proj3.Path, proj2.Path, entryProject.Path }; string expectedErrorMessage = GraphBuilder.FormatCircularDependencyError(projectsInCycle); Should.Throw(() => new ProjectGraph(entryProject.Path)).Message.ShouldContain(expectedErrorMessage); } @@ -326,17 +326,17 @@ public void ConstructBigGraphWithCycle() { using (var env = TestEnvironment.Create()) { - TransientTestFile entryProject = CreateProjectFile(env, 1, new[] {2,3,4}); - var proj2 = CreateProjectFile(env, 2, new[] {5, 6}); - var proj3 = CreateProjectFile(env, 3, new[] {2, 8}); + TransientTestFile entryProject = CreateProjectFile(env, 1, new[] { 2, 3, 4 }); + var proj2 = CreateProjectFile(env, 2, new[] { 5, 6 }); + var proj3 = CreateProjectFile(env, 3, new[] { 2, 8 }); CreateProjectFile(env, 4); - CreateProjectFile(env, 5, new []{9, 10}); - var proj6 = CreateProjectFile(env, 6, new[] { 7}); + CreateProjectFile(env, 5, new[] { 9, 10 }); + var proj6 = CreateProjectFile(env, 6, new[] { 7 }); var proj7 = CreateProjectFile(env, 7, new[] { 3 }); CreateProjectFile(env, 8); CreateProjectFile(env, 9); CreateProjectFile(env, 10); - var projectsInCycle = new List {proj2.Path, proj3.Path, proj7.Path, proj6.Path, proj2.Path }; + var projectsInCycle = new List { proj2.Path, proj3.Path, proj7.Path, proj6.Path, proj2.Path }; var errorMessage = GraphBuilder.FormatCircularDependencyError(projectsInCycle); Should.Throw(() => new ProjectGraph(entryProject.Path)).Message.ShouldContain(errorMessage); } @@ -346,12 +346,12 @@ public void ConstructBigGraphWithCycle() public void ProjectCollectionShouldNotInfluenceGlobalProperties() { var entryFile1 = CreateProjectFile(_env, 1, new[] { 3, 4 }); - var entryFile2 = CreateProjectFile(_env, 2, new []{ 4, 5 }); + var entryFile2 = CreateProjectFile(_env, 2, new[] { 4, 5 }); CreateProjectFile(_env, 3); CreateProjectFile(_env, 4); CreateProjectFile(_env, 5); - var entryPoint1 = new ProjectGraphEntryPoint(entryFile1.Path, new Dictionary {["B"] = "EntryPointB", ["C"] = "EntryPointC"}); + var entryPoint1 = new ProjectGraphEntryPoint(entryFile1.Path, new Dictionary { ["B"] = "EntryPointB", ["C"] = "EntryPointC" }); var entryPoint2 = new ProjectGraphEntryPoint(entryFile2.Path, null); var collection = _env.CreateProjectCollection().Collection; @@ -572,7 +572,7 @@ public void ConstructWithMultipleEntryPoints() TransientTestFile entryProject1 = CreateProjectFile(env, 1, new[] { 3 }); TransientTestFile entryProject2 = CreateProjectFile(env, 2, new[] { 3 }); CreateProjectFile(env, 3); - var projectGraph = new ProjectGraph(new [] { entryProject1.Path, entryProject2.Path }); + var projectGraph = new ProjectGraph(new[] { entryProject1.Path, entryProject2.Path }); projectGraph.ProjectNodes.Count.ShouldBe(3); var node1 = GetFirstNodeWithProjectNumber(projectGraph, 1); @@ -659,7 +659,7 @@ public void ConstructWithMultipleEntryPointsWithDifferentGlobalPropertiesConverg [Fact] public void ConstructGraphWithDifferentEntryPointsAndGraphRoots() { - using(var env = TestEnvironment.Create()) + using (var env = TestEnvironment.Create()) { TransientTestFile entryProject1 = CreateProjectFile(env, 1, new[] { 4 }); TransientTestFile entryProject2 = CreateProjectFile(env, 2, new[] { 4, 5 }); @@ -780,15 +780,15 @@ public void GetTargetsListReturnsEmptyTargetsForNodeIfNoTargetsPropagatedToIt() { using (var env = TestEnvironment.Create()) { - TransientTestFile entryProject = CreateProjectFile(env: env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: new Dictionary { { "A", new []{ "B" }} }, defaultTargets: "A"); + TransientTestFile entryProject = CreateProjectFile(env: env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: new Dictionary { { "A", new[] { "B" } } }, defaultTargets: "A"); CreateProjectFile(env: env, projectNumber: 2); var projectGraph = new ProjectGraph(entryProject.Path); projectGraph.ProjectNodes.Count.ShouldBe(2); - IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new []{ "Foo" }); + IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new[] { "Foo" }); targetLists.Count.ShouldBe(projectGraph.ProjectNodes.Count); - targetLists[GetFirstNodeWithProjectNumber(projectGraph, 1)].ShouldBe(new []{ "Foo" }); + targetLists[GetFirstNodeWithProjectNumber(projectGraph, 1)].ShouldBe(new[] { "Foo" }); targetLists[GetFirstNodeWithProjectNumber(projectGraph, 2)].ShouldBeEmpty(); } } @@ -800,7 +800,7 @@ public void GetTargetListsReturnsEmptyTargetsForAllNodesWhenDefaultTargetsAreReq { // Root project has no default targets. // The project file does not contain any targets - TransientTestFile entryProject = CreateProjectFile(env: env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: new Dictionary { { "A", new[] { "B" } }}, defaultTargets: string.Empty); + TransientTestFile entryProject = CreateProjectFile(env: env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: new Dictionary { { "A", new[] { "B" } } }, defaultTargets: string.Empty); // Dependency has default targets. Even though it gets called with empty targets, B will not get called, // because target propagation only equates empty targets to default targets for the root nodes. @@ -823,7 +823,7 @@ public void GetTargetListsDoesNotPropagateEmptyTargets() { // Target protocol produces empty target // The project file also does not contain any targets - TransientTestFile entryProject = CreateProjectFile(env: env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: new Dictionary { { "A", new[] { " ; ; " } }}, defaultTargets: string.Empty); + TransientTestFile entryProject = CreateProjectFile(env: env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: new Dictionary { { "A", new[] { " ; ; " } } }, defaultTargets: string.Empty); // Dependency has default targets. Even though it gets called with empty targets, B will not get called, // because target propagation only equates empty targets to default targets for the root nodes. @@ -832,9 +832,9 @@ public void GetTargetListsDoesNotPropagateEmptyTargets() var projectGraph = new ProjectGraph(entryProject.Path); projectGraph.ProjectNodes.Count.ShouldBe(2); - IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new []{ "A" }); + IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new[] { "A" }); targetLists.Count.ShouldBe(projectGraph.ProjectNodes.Count); - targetLists[GetFirstNodeWithProjectNumber(projectGraph, 1)].ShouldBe(new []{ "A" }); + targetLists[GetFirstNodeWithProjectNumber(projectGraph, 1)].ShouldBe(new[] { "A" }); targetLists[GetFirstNodeWithProjectNumber(projectGraph, 2)].ShouldBeEmpty(); } } @@ -849,7 +849,7 @@ public void GetTargetListsThrowsOnInvalidTargetNames() var projectGraph = new ProjectGraph(entryProject.Path); projectGraph.ProjectNodes.Count.ShouldBe(1); - Should.Throw(() => projectGraph.GetTargetLists(new []{ " " })); + Should.Throw(() => projectGraph.GetTargetLists(new[] { " " })); } } @@ -862,7 +862,7 @@ public void GetTargetListsUsesAllTargetsForNonMultitargetingNodes() var root1 = CreateProjectFile( env: env, projectNumber: 1, - projectReferences: new[] {2}, + projectReferences: new[] { 2 }, projectReferenceTargets: null, defaultTargets: null, extraContent: ProjectReferenceTargetsWithMultitargeting) @@ -875,7 +875,7 @@ public void GetTargetListsUsesAllTargetsForNonMultitargetingNodes() projectGraph.ProjectNodes.Count.ShouldBe(2); - IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List {"A"}); + IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List { "A" }); targetLists.Count.ShouldBe(projectGraph.ProjectNodes.Count); targetLists[GetFirstNodeWithProjectNumber(projectGraph, 1)].ShouldBe(new[] { "A" }); @@ -893,10 +893,10 @@ public void GetTargetsListInnerBuildToInnerBuild() <{InnerBuildPropertyName}>a "; - var root1 =CreateProjectFile( + var root1 = CreateProjectFile( env: env, projectNumber: 1, - projectReferences: new[] {2}, + projectReferences: new[] { 2 }, projectReferenceTargets: null, defaultTargets: null, extraContent: singleTargetedSpec) @@ -916,7 +916,7 @@ public void GetTargetsListInnerBuildToInnerBuild() projectGraph.ProjectNodes.Count.ShouldBe(2); - IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List {"A"}); + IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List { "A" }); targetLists.Count.ShouldBe(projectGraph.ProjectNodes.Count); targetLists[GetFirstNodeWithProjectNumber(projectGraph, 1)].ShouldBe(new[] { "A" }); @@ -950,7 +950,7 @@ public void GetTargetListsFiltersTargetsForOuterAndInnerBuilds() projectGraph.ProjectNodes.Count.ShouldBe(4); - IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List {"A"}); + IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List { "A" }); targetLists.Count.ShouldBe(projectGraph.ProjectNodes.Count); var root = GetFirstNodeWithProjectNumber(projectGraph, 1); @@ -989,8 +989,8 @@ public void GetTargetListsDoesNotUseTargetsMetadataOnInnerBuildsFromRootOuterBui -" - ).Path; +") + .Path; CreateProjectFile( env: _env, projectNumber: 2, @@ -1086,7 +1086,7 @@ public void GetTargetListsForComplexMultitargetingGraph() CreateProjectFile( env: env, projectNumber: 4, - projectReferences: new []{6}, + projectReferences: new[] { 6 }, projectReferenceTargets: null, defaultTargets: null, extraContent: ProjectReferenceTargetsWithMultitargeting); @@ -1116,21 +1116,21 @@ public void GetTargetListsForComplexMultitargetingGraph() defaultTargets: null, extraContent: OuterBuildSpecificationWithProjectReferenceTargets); - var projectGraph = new ProjectGraph(new[] {root1, root2}); + var projectGraph = new ProjectGraph(new[] { root1, root2 }); var dot = projectGraph.ToDot(); projectGraph.ProjectNodes.Count.ShouldBe(12); - IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List {"A"}); + IReadOnlyDictionary> targetLists = projectGraph.GetTargetLists(new List { "A" }); targetLists.Count.ShouldBe(projectGraph.ProjectNodes.Count); - AssertMultitargetingNode(1, projectGraph, targetLists, new []{"A"}, NonOuterBuildTargets); + AssertMultitargetingNode(1, projectGraph, targetLists, new[] { "A" }, NonOuterBuildTargets); AssertMultitargetingNode(3, projectGraph, targetLists, OuterBuildTargets, NonOuterBuildTargets); AssertMultitargetingNode(6, projectGraph, targetLists, OuterBuildTargets, NonOuterBuildTargets); - targetLists[GetFirstNodeWithProjectNumber(projectGraph, 2)].ShouldBe(new []{"A"}); + targetLists[GetFirstNodeWithProjectNumber(projectGraph, 2)].ShouldBe(new[] { "A" }); targetLists[GetFirstNodeWithProjectNumber(projectGraph, 4)].ShouldBe(NonOuterBuildTargets); targetLists[GetFirstNodeWithProjectNumber(projectGraph, 5)].ShouldBe(NonOuterBuildTargets); } @@ -1236,14 +1236,14 @@ public void GetTargetsListProjectReferenceTargetsOrDefaultComplexPropagation() var entryProject = CreateProjectFile( env: env, projectNumber: 1, - projectReferences: new[] {2, 3, 4}, - projectReferenceTargets: new Dictionary {{"Build", new[] {"Build"}}}); + projectReferences: new[] { 2, 3, 4 }, + projectReferenceTargets: new Dictionary { { "Build", new[] { "Build" } } }); CreateProjectFile( env: env, projectNumber: 2, projectReferences: null, projectReferenceTargets: - new Dictionary {{"Build", new[] {MSBuildConstants.ProjectReferenceTargetsOrDefaultTargetsMarker, "T2"}}}, + new Dictionary { { "Build", new[] { MSBuildConstants.ProjectReferenceTargetsOrDefaultTargetsMarker, "T2" } } }, defaultTargets: null, extraContent: referenceItem.Format("5", "T51")); CreateProjectFile( @@ -1251,7 +1251,7 @@ public void GetTargetsListProjectReferenceTargetsOrDefaultComplexPropagation() projectNumber: 3, projectReferences: null, projectReferenceTargets: - new Dictionary {{"Build", new[] {MSBuildConstants.ProjectReferenceTargetsOrDefaultTargetsMarker, "T3"}}}, + new Dictionary { { "Build", new[] { MSBuildConstants.ProjectReferenceTargetsOrDefaultTargetsMarker, "T3" } } }, defaultTargets: null, extraContent: referenceItem.Format("5", "T51;T53;T54")); CreateProjectFile( @@ -1259,7 +1259,7 @@ public void GetTargetsListProjectReferenceTargetsOrDefaultComplexPropagation() projectNumber: 4, projectReferences: null, projectReferenceTargets: - new Dictionary {{"Build", new[] {MSBuildConstants.ProjectReferenceTargetsOrDefaultTargetsMarker, "T4"}}}, + new Dictionary { { "Build", new[] { MSBuildConstants.ProjectReferenceTargetsOrDefaultTargetsMarker, "T4" } } }, defaultTargets: null, extraContent: referenceItem.Format("5", "")); CreateProjectFile(env: env, projectNumber: 5, projectReferences: null, projectReferenceTargets: null, defaultTargets: "D51;D52"); @@ -1487,7 +1487,7 @@ public void DotNotationShouldRepresentGraph(Dictionary edges) var graph = Helpers.CreateProjectGraph( _env, edges, - globalProperties: new Dictionary {{"a", "b"}}, + globalProperties: new Dictionary { { "a", "b" } }, createProjectFile: (env, projectId, references, _, _, _) => Helpers.CreateProjectFile( env, projectId, @@ -1497,7 +1497,7 @@ public void DotNotationShouldRepresentGraph(Dictionary edges) {"Build", new[] {$"TargetFrom{projectId}", "Build"}} })); - var targetsPerNode = graph.GetTargetLists(new []{ "Build" }); + var targetsPerNode = graph.GetTargetLists(new[] { "Build" }); Func nodeIdProvider = GetProjectFileName; @@ -1525,10 +1525,10 @@ public void DotNotationShouldRepresentGraph(Dictionary edges) } // edge count - Regex.Matches(dot,"->").Count.ShouldBe(edgeCount); + Regex.Matches(dot, "->").Count.ShouldBe(edgeCount); // node count - Regex.Matches(dot,"label").Count.ShouldBe(graph.ProjectNodes.Count); + Regex.Matches(dot, "label").Count.ShouldBe(graph.ProjectNodes.Count); } [Fact] @@ -1586,8 +1586,8 @@ public void InnerBuildsFromNonRootOuterBuildInheritEdgesToOuterBuild() extraContent: @" -" - ).Path; +") + .Path; CreateProjectFile( env: _env, projectNumber: 2, @@ -1646,7 +1646,7 @@ public void DuplicatedInnerBuildMonikersShouldGetDeduplicated() [Fact] public void ReferenceOfMultitargetingProjectShouldNotInheritInnerBuildSpecificGlobalProperties() { - var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] {2}, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path; + var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path; CreateProjectFile(env: _env, projectNumber: 2); var graph = new ProjectGraph(root); @@ -1670,7 +1670,7 @@ public void InnerBuildAsRootViaLocalPropertyShouldNotPropagateInnerBuildProperty var root = CreateProjectFile( env: _env, projectNumber: 1, - projectReferences: new[] {2}, + projectReferences: new[] { 2 }, projectReferenceTargets: null, defaultTargets: null, extraContent: innerBuildViaLocalProperty).Path; @@ -1693,10 +1693,10 @@ public void InnerBuildAsRootViaLocalPropertyShouldNotPropagateInnerBuildProperty [Fact] public void InnerBuildAsRootViaGlobalPropertyShouldNotPropagateInnerBuildPropertyToReference() { - var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] {2}, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path; + var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] { 2 }, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path; CreateProjectFile(env: _env, projectNumber: 2); - var graph = new ProjectGraph(root, new Dictionary {{InnerBuildPropertyName, "foo"}}); + var graph = new ProjectGraph(root, new Dictionary { { InnerBuildPropertyName, "foo" } }); var dot = graph.ToDot(); @@ -1712,9 +1712,9 @@ public void InnerBuildAsRootViaGlobalPropertyShouldNotPropagateInnerBuildPropert [Fact] public void NonMultitargetingProjectsAreCompatibleWithMultitargetingProjects() { - var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] {2, 3}, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path; - CreateProjectFile(env: _env, projectNumber: 2, projectReferences: new[] {4}); - CreateProjectFile(env: _env, projectNumber: 3, projectReferences: new[] {4}); + var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] { 2, 3 }, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path; + CreateProjectFile(env: _env, projectNumber: 2, projectReferences: new[] { 4 }); + CreateProjectFile(env: _env, projectNumber: 3, projectReferences: new[] { 4 }); CreateProjectFile(env: _env, projectNumber: 4, projectReferences: null, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup); var graph = new ProjectGraph(root); @@ -1738,7 +1738,7 @@ public void InnerBuildsCanHaveSeparateReferences() ".Cleanup(); - var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] {2, 3}, projectReferenceTargets: null, defaultTargets: null, extraContent: extraInnerBuildReferenceSpec).Path; + var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: new[] { 2, 3 }, projectReferenceTargets: null, defaultTargets: null, extraContent: extraInnerBuildReferenceSpec).Path; CreateProjectFile(env: _env, projectNumber: 2, projectReferences: null, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup); CreateProjectFile(env: _env, projectNumber: 3); CreateProjectFile(env: _env, projectNumber: 4, projectReferences: null, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup); @@ -1761,13 +1761,13 @@ public void InnerBuildsCanHaveSeparateReferences() innerBuildWithCommonReferences.ProjectReferences.Count.ShouldBe(4); var referenceNumbersSet = innerBuildWithCommonReferences.ProjectReferences.Select(r => Path.GetFileNameWithoutExtension(r.ProjectInstance.FullPath)).ToHashSet(); - referenceNumbersSet.ShouldBeSameIgnoringOrder(new HashSet {"2", "3"}); + referenceNumbersSet.ShouldBeSameIgnoringOrder(new HashSet { "2", "3" }); var innerBuildWithAdditionalReferences = GetNodesWithProjectNumber(graph, 1).First(n => n.ProjectInstance.GlobalProperties.TryGetValue(InnerBuildPropertyName, out string p) && p == "b"); innerBuildWithAdditionalReferences.ProjectReferences.Count.ShouldBe(8); referenceNumbersSet = innerBuildWithAdditionalReferences.ProjectReferences.Select(r => Path.GetFileNameWithoutExtension(r.ProjectInstance.FullPath)).ToHashSet(); - referenceNumbersSet.ShouldBeSameIgnoringOrder(new HashSet {"2", "3", "4", "5"}); + referenceNumbersSet.ShouldBeSameIgnoringOrder(new HashSet { "2", "3", "4", "5" }); } [Fact] @@ -1777,9 +1777,9 @@ public void InnerBuildProducedByOuterBuildCanBeReferencedByAnotherNode() "; - var additionalGlobalProperties = new Dictionary {{"x", "y"}}; + var additionalGlobalProperties = new Dictionary { { "x", "y" } }; - var graph = new ProjectGraph(new [] + var graph = new ProjectGraph(new[] { CreateProjectFile(env: _env, projectNumber: 1, projectReferences: null, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup).Path, CreateProjectFile(env: _env, projectNumber: 2, projectReferences: null, projectReferenceTargets: null, defaultTargets: null, extraContent: referenceToInnerBuild).Path @@ -1802,7 +1802,7 @@ public void InnerBuildProducedByOuterBuildCanBeReferencedByAnotherNode() two.ProjectReferences.ShouldHaveSingleItem(); two.ProjectReferences.First().ShouldBe(referencedInnerBuild); - referencedInnerBuild.ReferencingProjects.ShouldBeSameIgnoringOrder(new []{two, outerBuild}); + referencedInnerBuild.ReferencingProjects.ShouldBeSameIgnoringOrder(new[] { two, outerBuild }); } [Fact] @@ -1813,10 +1813,10 @@ public void StandaloneInnerBuildsCanBeReferencedWithoutOuterBuilds() "; var root = CreateProjectFile(env: _env, projectNumber: 1, projectReferences: null, projectReferenceTargets: null, defaultTargets: null, extraContent: referenceToInnerBuild).Path; - CreateProjectFile(env: _env, projectNumber: 2, projectReferences: new []{3}, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup + $"<{InnerBuildPropertyName}>a"); + CreateProjectFile(env: _env, projectNumber: 2, projectReferences: new[] { 3 }, projectReferenceTargets: null, defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup + $"<{InnerBuildPropertyName}>a"); CreateProjectFile(env: _env, projectNumber: 3); - var additionalGlobalProperties = new Dictionary {{"x", "y"}}; + var additionalGlobalProperties = new Dictionary { { "x", "y" } }; var graph = new ProjectGraph(root, additionalGlobalProperties); @@ -1843,7 +1843,7 @@ public void InnerBuildsProducedByOuterBuildsCanBeReferencedByOtherInnerBuilds() ".Cleanup(); - var additionalGlobalProperties = new Dictionary {{"x", "y"}}; + var additionalGlobalProperties = new Dictionary { { "x", "y" } }; var root = CreateProjectFile( env: _env, @@ -1862,7 +1862,7 @@ public void InnerBuildsProducedByOuterBuildsCanBeReferencedByOtherInnerBuilds() defaultTargets: null, extraContent: MultitargetingSpecificationPropertyGroup); - var graph = new ProjectGraph(new [] { root }, additionalGlobalProperties); + var graph = new ProjectGraph(new[] { root }, additionalGlobalProperties); var dot = graph.ToDot(); @@ -1887,7 +1887,7 @@ public void InnerBuildsProducedByOuterBuildsCanBeReferencedByOtherInnerBuilds() // the outer build is necessary as the referencing inner build can still call targets on it GetNodesWithProjectNumber(graph, 2).Count().ShouldBe(2); - innerBuild1WithReferenceToInnerBuild2.ProjectReferences.ShouldBeSameIgnoringOrder(new []{outerBuild2, innerBuild2}); + innerBuild1WithReferenceToInnerBuild2.ProjectReferences.ShouldBeSameIgnoringOrder(new[] { outerBuild2, innerBuild2 }); } public static IEnumerable AllNodesShouldHaveGraphBuildGlobalPropertyData @@ -2000,8 +2000,8 @@ public void UserValuesForIsGraphBuildGlobalPropertyShouldBePreserved() { var projectGraph = Helpers.CreateProjectGraph( env, - new Dictionary {{1, null}}, - new Dictionary {{PropertyNames.IsGraphBuild, "xyz"}}); + new Dictionary { { 1, null } }, + new Dictionary { { PropertyNames.IsGraphBuild, "xyz" } }); projectGraph.ProjectNodes.First().ProjectInstance.GlobalProperties[PropertyNames.IsGraphBuild].ShouldBe("xyz"); } @@ -2014,8 +2014,7 @@ public void GraphShouldSupportTransitiveReferences(Dictionary edges) var graph = Helpers.CreateProjectGraph( env: _env, dependencyEdges: edges, - extraContentForAllNodes: EnableTransitiveProjectReferencesPropertyGroup - ); + extraContentForAllNodes: EnableTransitiveProjectReferencesPropertyGroup); foreach (var node in graph.ProjectNodes) { @@ -2062,7 +2061,7 @@ public static IEnumerable TransitiveReferencesAreDefinedPerProjectTest {1, new[] {2, 3, 4}}, {2, new[] {3}}, {3, new[] {4}}, - {4, Array.Empty()} + {4, Array.Empty() } } }; @@ -2127,7 +2126,7 @@ public static IEnumerable TransitiveReferencesAreDefinedPerProjectTest {3, new[] {4, 5, 6}}, {4, new[] {5}}, {5, new[] {6}}, - {6, Array.Empty()}, + {6, Array.Empty() }, } }; } @@ -2138,14 +2137,12 @@ public static IEnumerable TransitiveReferencesAreDefinedPerProjectTest public void TransitiveReferencesAreDefinedPerProject( Dictionary edges, Dictionary extraContentPerProjectNumber, - Dictionary expectedReferences - ) + Dictionary expectedReferences) { var graph = Helpers.CreateProjectGraph( env: _env, dependencyEdges: edges, - extraContentPerProjectNumber: extraContentPerProjectNumber - ); + extraContentPerProjectNumber: extraContentPerProjectNumber); graph.AssertReferencesIgnoringOrder(expectedReferences); } @@ -2188,17 +2185,16 @@ public void TransitiveReferencesShouldNotBeAddedToOuterBuilds() 6, MultitargetingSpecificationPropertyGroup } - } - ); + }); - GetOuterBuild(graph, 1).AssertReferencesIgnoringOrder(new []{1, 1}); + GetOuterBuild(graph, 1).AssertReferencesIgnoringOrder(new[] { 1, 1 }); var innerBuilds1 = GetInnerBuilds(graph, 1); innerBuilds1.Count.ShouldBe(2); foreach (var innerBuild in innerBuilds1) { - innerBuild.AssertReferencesIgnoringOrder(new []{3, 4, 4, 4, 5, 6, 6, 6}); + innerBuild.AssertReferencesIgnoringOrder(new[] { 3, 4, 4, 4, 5, 6, 6, 6 }); } GetFirstNodeWithProjectNumber(graph, 2).AssertReferencesIgnoringOrder(new[] { 3, 4, 4, 4, 5, 6, 6, 6 }); @@ -2210,7 +2206,7 @@ public void TransitiveReferencesShouldNotBeAddedToOuterBuilds() foreach (var innerBuild in innerBuilds4) { - innerBuild.AssertReferencesIgnoringOrder(new []{5, 6, 6, 6}); + innerBuild.AssertReferencesIgnoringOrder(new[] { 5, 6, 6, 6 }); } } @@ -2273,10 +2269,10 @@ public void TransitiveReferencesShouldNotOverwriteMultitargetingEdges() "); - var targetLists = graph.GetTargetLists(new[] {"Build"}); + var targetLists = graph.GetTargetLists(new[] { "Build" }); var outerBuild1 = GetOuterBuild(graph, 1); - targetLists[outerBuild1].ShouldBe(new[] {"Build"}); + targetLists[outerBuild1].ShouldBe(new[] { "Build" }); AssertOuterBuild(outerBuild1, graph, expectedInnerBuildCount: 2); @@ -2286,11 +2282,11 @@ public void TransitiveReferencesShouldNotOverwriteMultitargetingEdges() foreach (var inner1 in innerBuildsFor1) { // Outer build targets are added to inner builds because - targetLists[inner1].ShouldBe(new[] {"BuildForOuterBuild", "Build"}); + targetLists[inner1].ShouldBe(new[] { "BuildForOuterBuild", "Build" }); } var outerBuild2 = GetOuterBuild(graph, 2); - targetLists[outerBuild2].ShouldBe(new[] {"BuildForOuterBuild"}); + targetLists[outerBuild2].ShouldBe(new[] { "BuildForOuterBuild" }); AssertOuterBuild(outerBuild2, graph, expectedInnerBuildCount: 2); var innerBuildsFor2 = GetInnerBuilds(graph, 2); @@ -2298,7 +2294,7 @@ public void TransitiveReferencesShouldNotOverwriteMultitargetingEdges() foreach (var inner2 in innerBuildsFor2) { - targetLists[inner2].ShouldBe(new[] {"BuildForOuterBuild", "Build", "1ATarget", "1BTarget"}); + targetLists[inner2].ShouldBe(new[] { "BuildForOuterBuild", "Build", "1ATarget", "1BTarget" }); } var outerBuild3 = GetOuterBuild(graph, 3); diff --git a/src/Build.UnitTests/Graph/ResultCacheBasedBuilds_Tests.cs b/src/Build.UnitTests/Graph/ResultCacheBasedBuilds_Tests.cs index cb40be2fbad..59309f030e8 100644 --- a/src/Build.UnitTests/Graph/ResultCacheBasedBuilds_Tests.cs +++ b/src/Build.UnitTests/Graph/ResultCacheBasedBuilds_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -44,11 +44,11 @@ public void Dispose() private readonly MockLogger _logger; [Theory] - [InlineData(new byte[] {})] - [InlineData(new byte[] {1})] - [InlineData(new byte[] {0})] - [InlineData(new byte[] {1, 1})] - [InlineData(new byte[] {1, 1, 90, 23})] + [InlineData(new byte[] { })] + [InlineData(new byte[] { 1 })] + [InlineData(new byte[] { 0 })] + [InlineData(new byte[] { 1, 1 })] + [InlineData(new byte[] { 1, 1, 90, 23 })] public void InvalidCacheFilesShouldLogError(byte[] cacheContents) { var project = CreateProjectFileWithBuildTargetAndItems(_env, 1).Path; @@ -63,7 +63,7 @@ public void InvalidCacheFilesShouldLogError(byte[] cacheContents) _logger, new BuildParameters { - InputResultsCacheFiles = new[] {existingFile} + InputResultsCacheFiles = new[] { existingFile } }); result.OverallResult.ShouldBe(BuildResultCode.Failure); @@ -102,9 +102,9 @@ public void CachesGetLogged() { buildManager.BeginBuild(new BuildParameters { - InputResultsCacheFiles = new []{"a", "b"}, + InputResultsCacheFiles = new[] { "a", "b" }, OutputResultsCacheFile = "c", - Loggers = new []{_logger} + Loggers = new[] { _logger } }); buildManager.EndBuild(); @@ -164,7 +164,7 @@ public void RebuildSingleProjectFromCache(string defaultTargets, string explicit _logger, new BuildParameters { - InputResultsCacheFiles = new[] {outputCache} + InputResultsCacheFiles = new[] { outputCache } }); resultFromCachedBuild.OverallResult.ShouldBe(BuildResultCode.Success); @@ -456,7 +456,7 @@ public void MissingResultFromCacheShouldErrorDueToIsolatedBuildCacheEnforcement( var logger = new MockLogger(); - buildParameters.Loggers = new[] {logger}; + buildParameters.Loggers = new[] { logger }; var result = BuildProjectFileUsingBuildManager( node.ProjectInstance.FullPath, @@ -509,8 +509,7 @@ internal static TransientTestFile CreateProjectFileWithBuildTargetAndItems( int projectNumber, int[] projectReferences = null, string defaultTargets = null, - string explicitTargets = null - ) + string explicitTargets = null) { var sb = new StringBuilder(); @@ -538,8 +537,7 @@ internal static TransientTestFile CreateProjectFileWithBuildTargetAndItems( projectReferences, null, defaultTargets, - sb.ToString() - ); + sb.ToString()); } [Fact] @@ -553,7 +551,7 @@ public void NonExistingInputResultsCacheShouldLogError() _logger, new BuildParameters { - InputResultsCacheFiles = new[] {"FileDoesNotExist1", existingFile, "FileDoesNotExist2"} + InputResultsCacheFiles = new[] { "FileDoesNotExist1", existingFile, "FileDoesNotExist2" } }); result.OverallResult.ShouldBe(BuildResultCode.Failure); diff --git a/src/Build.UnitTests/HashTableUtility_Tests.cs b/src/Build.UnitTests/HashTableUtility_Tests.cs index 78bd02da31d..ddc0973b246 100644 --- a/src/Build.UnitTests/HashTableUtility_Tests.cs +++ b/src/Build.UnitTests/HashTableUtility_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build.UnitTests/Instance/HostServices_Tests.cs b/src/Build.UnitTests/Instance/HostServices_Tests.cs index f13eb9b32ab..3a9ebdb07c2 100644 --- a/src/Build.UnitTests/Instance/HostServices_Tests.cs +++ b/src/Build.UnitTests/Instance/HostServices_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -61,8 +61,7 @@ public void TestInvalidHostObjectRegistration_NullProject() HostServices hostServices = new HostServices(); TestHostObject hostObject = new TestHostObject(); hostServices.RegisterHostObject(null, "target", "task", hostObject); - } - ); + }); } /// /// Test ensuring a null target for host object registration throws. @@ -75,8 +74,7 @@ public void TestInvalidHostObjectRegistration_NullTarget() HostServices hostServices = new HostServices(); TestHostObject hostObject = new TestHostObject(); hostServices.RegisterHostObject("project", null, "task", hostObject); - } - ); + }); } /// /// Test ensuring a null task for host object registration throws. @@ -89,8 +87,7 @@ public void TestInvalidHostObjectRegistration_NullTask() HostServices hostServices = new HostServices(); TestHostObject hostObject = new TestHostObject(); hostServices.RegisterHostObject("project", "target", null, hostObject); - } - ); + }); } /// /// Test which verifies host object unregistration. @@ -223,8 +220,7 @@ public void TestContradictoryAffinityCausesException_OutOfProc() hostServices.RegisterHostObject("project", "target", "task", hostObject); Assert.Equal(NodeAffinity.InProc, hostServices.GetNodeAffinity("project")); hostServices.SetNodeAffinity("project", NodeAffinity.OutOfProc); - } - ); + }); } /// /// Test which ensures that setting an Any affinity for a project with a host object throws. @@ -239,8 +235,7 @@ public void TestContradictoryAffinityCausesException_Any() hostServices.RegisterHostObject("project", "target", "task", hostObject); Assert.Equal(NodeAffinity.InProc, hostServices.GetNodeAffinity("project")); hostServices.SetNodeAffinity("project", NodeAffinity.Any); - } - ); + }); } /// @@ -282,8 +277,7 @@ public void TestContraditcoryHostObjectCausesException_OutOfProc() TestHostObject hostObject = new TestHostObject(); hostServices.SetNodeAffinity("project", NodeAffinity.OutOfProc); hostServices.RegisterHostObject("project", "target", "task", hostObject); - } - ); + }); } /// /// Test which ensures the host object can be set for a project which has the Any affinity specifically set. diff --git a/src/Build.UnitTests/Instance/ProjectInstance_Internal_Tests.cs b/src/Build.UnitTests/Instance/ProjectInstance_Internal_Tests.cs index 49c9d3a4db5..a12c2382a58 100644 --- a/src/Build.UnitTests/Instance/ProjectInstance_Internal_Tests.cs +++ b/src/Build.UnitTests/Instance/ProjectInstance_Internal_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -283,8 +283,7 @@ public void UsingExplicitToolsVersionShouldBeFalseWhenNoToolsetIsReferencedInPro { var projectInstance = new ProjectInstance( new ProjectRootElement( - XmlReader.Create(new StringReader("")), ProjectCollection.GlobalProjectCollection.ProjectRootElementCache, false, false) - ); + XmlReader.Create(new StringReader("")), ProjectCollection.GlobalProjectCollection.ProjectRootElementCache, false, false)); projectInstance.UsingDifferentToolsVersionFromProjectFile.ShouldBeFalse(); } @@ -738,7 +737,7 @@ public static IEnumerable ProjectInstanceHasEvaluationIdTestData() pi.AddItem("foo", "bar"); pi.TranslateEntireState = true; - ((ITranslatable) pi).Translate(TranslationHelpers.GetWriteTranslator()); + ((ITranslatable)pi).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); return copy; diff --git a/src/Build.UnitTests/Instance/ProjectItemGroupTaskItemInstance_Internal_Tests.cs b/src/Build.UnitTests/Instance/ProjectItemGroupTaskItemInstance_Internal_Tests.cs index 2ce98e6f74d..4a31c0c9a53 100644 --- a/src/Build.UnitTests/Instance/ProjectItemGroupTaskItemInstance_Internal_Tests.cs +++ b/src/Build.UnitTests/Instance/ProjectItemGroupTaskItemInstance_Internal_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.BackEnd; @@ -42,7 +42,7 @@ public void ProjectItemGroupTaskItemInstanceCanSerializeViaTranslator(List TargetChildrenTestData CreateTargetItemGroup(), CreateTargetOnError(), CreateTargetTask() - } - ), - new ReadOnlyCollection(new[] {CreateTargetOnError()}) + }), + new ReadOnlyCollection(new[] {CreateTargetOnError() }) }; yield return new object[] @@ -59,8 +58,7 @@ public static IEnumerable TargetChildrenTestData CreateTargetTask(), CreateTargetOnError(), CreateTargetTask() - } - ), + }), new ReadOnlyCollection(new[] { CreateTargetOnError(), @@ -78,7 +76,7 @@ public void ProjectTargetInstanceCanSerializeViaTranslator( { var original = CreateTarget(null, children, errorChildren); - ((ITranslatable) original).Translate(TranslationHelpers.GetWriteTranslator()); + ((ITranslatable)original).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectTargetInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(original, copy, new TargetComparer()); diff --git a/src/Build.UnitTests/Instance/ProjectTaskInstance_Internal_Tests.cs b/src/Build.UnitTests/Instance/ProjectTaskInstance_Internal_Tests.cs index 0c32202a0a8..48cfaef14c7 100644 --- a/src/Build.UnitTests/Instance/ProjectTaskInstance_Internal_Tests.cs +++ b/src/Build.UnitTests/Instance/ProjectTaskInstance_Internal_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.BackEnd; @@ -37,7 +37,7 @@ public static IEnumerable TestData { new Dictionary { - {"p1", ("v1", new MockElementLocation("p1"))} + {"p1", ("v1", new MockElementLocation("p1")) } }, new List { @@ -49,8 +49,8 @@ public static IEnumerable TestData { new Dictionary { - {"p1", ("v1", new MockElementLocation("p1"))}, - {"p2", ("v2", new MockElementLocation("p2"))} + {"p1", ("v1", new MockElementLocation("p1")) }, + {"p2", ("v2", new MockElementLocation("p2")) } }, new List { @@ -77,7 +77,7 @@ public void ProjectTaskInstanceCanSerializeViaTranslator( var original = CreateTargetTask(null, parametersCopy, outputs); - ((ITranslatable) original).Translate(TranslationHelpers.GetWriteTranslator()); + ((ITranslatable)original).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectTaskInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(original, copy, new TargetTaskComparer()); diff --git a/src/Build.UnitTests/Instance/TaskItem_Tests.cs b/src/Build.UnitTests/Instance/TaskItem_Tests.cs index 0920d71c8df..b3f48f86480 100644 --- a/src/Build.UnitTests/Instance/TaskItem_Tests.cs +++ b/src/Build.UnitTests/Instance/TaskItem_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Shared; diff --git a/src/Build.UnitTests/InternalEngineHelpers.cs b/src/Build.UnitTests/InternalEngineHelpers.cs index 92a24a8f03d..8ba8868dbd1 100644 --- a/src/Build.UnitTests/InternalEngineHelpers.cs +++ b/src/Build.UnitTests/InternalEngineHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Build.UnitTests/InvalidProjectFileException_Tests.cs b/src/Build.UnitTests/InvalidProjectFileException_Tests.cs index a5b3fd5652c..499927b7c47 100644 --- a/src/Build.UnitTests/InvalidProjectFileException_Tests.cs +++ b/src/Build.UnitTests/InvalidProjectFileException_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.UnitTests/LogFormatter_Tests.cs b/src/Build.UnitTests/LogFormatter_Tests.cs index 612088969b8..972239729b9 100644 --- a/src/Build.UnitTests/LogFormatter_Tests.cs +++ b/src/Build.UnitTests/LogFormatter_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd.Logging; diff --git a/src/Build.UnitTests/LoggerDescription_Tests.cs b/src/Build.UnitTests/LoggerDescription_Tests.cs index 864522ae43c..f65fcbbdb01 100644 --- a/src/Build.UnitTests/LoggerDescription_Tests.cs +++ b/src/Build.UnitTests/LoggerDescription_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.UnitTests/LoggerException_Tests.cs b/src/Build.UnitTests/LoggerException_Tests.cs index 1e66dff1800..4fb900a4cce 100644 --- a/src/Build.UnitTests/LoggerException_Tests.cs +++ b/src/Build.UnitTests/LoggerException_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build.UnitTests/MockElementLocation.cs b/src/Build.UnitTests/MockElementLocation.cs index 313a245c4c8..333a9e36670 100644 --- a/src/Build.UnitTests/MockElementLocation.cs +++ b/src/Build.UnitTests/MockElementLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build.UnitTests/MockLoggingContext.cs b/src/Build.UnitTests/MockLoggingContext.cs index 17fb2a448d4..44edbc48ce0 100644 --- a/src/Build.UnitTests/MockLoggingContext.cs +++ b/src/Build.UnitTests/MockLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Framework; diff --git a/src/Build.UnitTests/MockTask.cs b/src/Build.UnitTests/MockTask.cs index b09930be051..ffaa49409d5 100644 --- a/src/Build.UnitTests/MockTask.cs +++ b/src/Build.UnitTests/MockTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -377,7 +377,7 @@ public TaskItem[] TaskItemArrayOutputParameter /// /// A simple mock task for use with Unit Testing. /// - sealed internal class MockTask : MockTaskBase, ITask + internal sealed class MockTask : MockTaskBase, ITask { private IBuildEngine _e = null; diff --git a/src/Build.UnitTests/Parser_Tests.cs b/src/Build.UnitTests/Parser_Tests.cs index 28691332f75..60dd1139123 100644 --- a/src/Build.UnitTests/Parser_Tests.cs +++ b/src/Build.UnitTests/Parser_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Linq; diff --git a/src/Build.UnitTests/ProjectCache/ProjectCacheTests.cs b/src/Build.UnitTests/ProjectCache/ProjectCacheTests.cs index 405f2716d21..6debe82528e 100644 --- a/src/Build.UnitTests/ProjectCache/ProjectCacheTests.cs +++ b/src/Build.UnitTests/ProjectCache/ProjectCacheTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -138,8 +138,7 @@ public static CacheResult SuccessfulTargetResult(int projectNumber, string proje {CacheHitByTargetResult, "true"} }) }, - BuildResultCode.Success - ) + BuildResultCode.Success) }); } @@ -186,7 +185,7 @@ char Chr(int projectNumber) CacheResultType.CacheNotApplicable => 'N', CacheResultType.None => 'E', _ => throw new ArgumentOutOfRangeException() - }; + }; } } } @@ -347,7 +346,7 @@ public static IEnumerable SuccessfulGraphs }, new Dictionary { - {1, GraphCacheResponse.SuccessfulProxyTargetResult()} + {1, GraphCacheResponse.SuccessfulProxyTargetResult() } }); yield return new GraphCacheResponse( @@ -357,7 +356,7 @@ public static IEnumerable SuccessfulGraphs }, new Dictionary { - {1, GraphCacheResponse.SuccessfulTargetResult(1, "1.proj")} + {1, GraphCacheResponse.SuccessfulTargetResult(1, "1.proj") } }); yield return new GraphCacheResponse( @@ -373,7 +372,7 @@ public static IEnumerable SuccessfulGraphs }, new Dictionary { - {2, GraphCacheResponse.SuccessfulProxyTargetResult()} + {2, GraphCacheResponse.SuccessfulProxyTargetResult() } }); yield return new GraphCacheResponse( @@ -383,7 +382,7 @@ public static IEnumerable SuccessfulGraphs }, new Dictionary { - {2, GraphCacheResponse.SuccessfulTargetResult(2, "2.proj")} + {2, GraphCacheResponse.SuccessfulTargetResult(2, "2.proj") } }); yield return new GraphCacheResponse( @@ -393,8 +392,8 @@ public static IEnumerable SuccessfulGraphs }, new Dictionary { - {1, GraphCacheResponse.SuccessfulProxyTargetResult()}, - {2, GraphCacheResponse.SuccessfulTargetResult(2, "2.proj")} + {1, GraphCacheResponse.SuccessfulProxyTargetResult() }, + {2, GraphCacheResponse.SuccessfulTargetResult(2, "2.proj") } }); yield return new GraphCacheResponse( @@ -543,8 +542,7 @@ public void ProjectCacheByVsScenarioIgnoresSlnDisabledProjects() private (MockLogger logger, ProjectGraph projectGraph, Dictionary nodesToBuildResults) BuildGraphVsScenario( GraphCacheResponse testData, BuildParameters? buildParameters = null, - bool assertBuildResults = true - ) + bool assertBuildResults = true) { var nodesToBuildResults = new Dictionary(); MockLogger logger; @@ -733,8 +731,8 @@ public void RunningProxyBuildsOnOutOfProcNodesShouldIssueWarning(bool disableInp }, new Dictionary { - {1, GraphCacheResponse.SuccessfulProxyTargetResult()}, - {2, GraphCacheResponse.SuccessfulProxyTargetResult()} + {1, GraphCacheResponse.SuccessfulProxyTargetResult() }, + {2, GraphCacheResponse.SuccessfulProxyTargetResult() } }); var graph = testData.CreateGraph(_env); @@ -910,8 +908,7 @@ public void CacheViaBuildParametersCanDiscoverAndLoadPluginFromAssembly() new Dictionary { {1, new[] {2, 3}} - } - ); + }); var graph = testData.CreateGraph(_env); @@ -942,8 +939,7 @@ public void GraphBuildCanDiscoverAndLoadPluginFromAssembly() new Dictionary { {1, new[] {2, 3}} - } - ); + }); var graph = testData.CreateGraph(_env); @@ -985,12 +981,10 @@ public void BuildFailsWhenCacheBuildResultIsWrong() {"File", "Invalid file"} }) }, - BuildResultCode.Success - ) + BuildResultCode.Success) }) } - } - ); + }); var graph = testData.CreateGraph(_env); var mockCache = new InstanceMockCache(testData); @@ -1243,8 +1237,7 @@ public void EngineShouldHandleExceptionsFromCachePluginViaGraphBuild(ErrorLocati -" - ); +"); var buildSession = new Helpers.BuildManagerSession( _env, @@ -1360,15 +1353,14 @@ public void EndBuildShouldGetCalledOnceWhenItThrowsExceptionsFromGraphBuilds() [InlineData(true, true)] public void CacheShouldBeQueriedInParallelDuringGraphBuilds(bool useSynchronousLogging, bool disableInprocNode) { - var referenceNumbers = new []{2, 3, 4}; + var referenceNumbers = new[] { 2, 3, 4 }; var testData = new GraphCacheResponse( new Dictionary { {1, referenceNumbers} }, - referenceNumbers.ToDictionary(k => k, k => GraphCacheResponse.SuccessfulProxyTargetResult()) - ); + referenceNumbers.ToDictionary(k => k, k => GraphCacheResponse.SuccessfulProxyTargetResult())); var graph = testData.CreateGraph(_env); @@ -1460,8 +1452,7 @@ public void ParallelStressTestForVsScenario(bool useSynchronousLogging, bool dis { {1, referenceNumbers} }, - referenceNumbers.ToDictionary(k => k, k => GraphCacheResponse.SuccessfulProxyTargetResult()) - ); + referenceNumbers.ToDictionary(k => k, k => GraphCacheResponse.SuccessfulProxyTargetResult())); var graph = testData.CreateGraph(_env); @@ -1524,8 +1515,7 @@ public void ParallelStressTest(bool useSynchronousLogging, bool disableInprocNod { {1, referenceNumbers} }, - referenceNumbers.ToDictionary(k => k, k => GraphCacheResponse.SuccessfulProxyTargetResult()) - ); + referenceNumbers.ToDictionary(k => k, k => GraphCacheResponse.SuccessfulProxyTargetResult())); var graph = testData.CreateGraph(_env); var cache = new InstanceMockCache(testData, TimeSpan.FromMilliseconds(50)); @@ -1608,7 +1598,7 @@ public void ProxyCacheHitsOnPreviousCacheMissesShouldWork() Interlocked.Increment(ref cacheHitCount); return Task.FromResult( CacheResult.IndicateCacheHit( - new ProxyTargets(new Dictionary {{proxyTarget, cacheHitTarget}}))); + new ProxyTargets(new Dictionary { { proxyTarget, cacheHitTarget } }))); } } }), @@ -1653,7 +1643,7 @@ private void SetEnvironmentForErrorLocations(ErrorLocations errorLocations, Erro { foreach (var enumValue in Enum.GetValues(typeof(ErrorLocations))) { - var typedValue = (ErrorLocations) enumValue; + var typedValue = (ErrorLocations)enumValue; if (errorLocations.HasFlag(typedValue)) { var exceptionLocation = typedValue.ToString(); diff --git a/src/Build.UnitTests/ProjectEvaluationFinishedEventArgs_Tests.cs b/src/Build.UnitTests/ProjectEvaluationFinishedEventArgs_Tests.cs index 7a3b0875d84..66ef134bbe3 100644 --- a/src/Build.UnitTests/ProjectEvaluationFinishedEventArgs_Tests.cs +++ b/src/Build.UnitTests/ProjectEvaluationFinishedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -45,9 +45,9 @@ public static IEnumerable GetProfilerResults() yield return new object[] { new ProfilerResult(new Dictionary { - {new EvaluationLocation(0, null, EvaluationPass.TotalEvaluation, "1", "myFile", 42, "elementName", "description", EvaluationLocationKind.Condition), new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2)}, - {new EvaluationLocation(1, 0, EvaluationPass.Targets, "1", null, null, null, null, EvaluationLocationKind.Glob), new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2)}, - {new EvaluationLocation(2, 0, EvaluationPass.LazyItems, "2", null, null, null, null, EvaluationLocationKind.Element), new ProfiledLocation(TimeSpan.Zero, TimeSpan.Zero, 0)} + {new EvaluationLocation(0, null, EvaluationPass.TotalEvaluation, "1", "myFile", 42, "elementName", "description", EvaluationLocationKind.Condition), new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2) }, + {new EvaluationLocation(1, 0, EvaluationPass.Targets, "1", null, null, null, null, EvaluationLocationKind.Glob), new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2) }, + {new EvaluationLocation(2, 0, EvaluationPass.LazyItems, "2", null, null, null, null, EvaluationLocationKind.Element), new ProfiledLocation(TimeSpan.Zero, TimeSpan.Zero, 0) } }) }; var element = new ProjectRootElement( @@ -57,11 +57,11 @@ public static IEnumerable GetProfilerResults() yield return new object[] { new ProfilerResult(new Dictionary { - {EvaluationLocation.CreateLocationForCondition(null, EvaluationPass.UsingTasks, "1", "myFile", 42, "conditionCase"), new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2)}, + {EvaluationLocation.CreateLocationForCondition(null, EvaluationPass.UsingTasks, "1", "myFile", 42, "conditionCase"), new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2) }, {EvaluationLocation.CreateLocationForProject(null, EvaluationPass.InitialProperties, "1", "myFile", 42, element), - new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2)}, + new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2) }, {EvaluationLocation.CreateLocationForGlob(null, EvaluationPass.InitialProperties, "1", "myFile", 42, "glob description"), - new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2)} + new ProfiledLocation(TimeSpan.MaxValue, TimeSpan.MinValue, 2) } }) }; } } diff --git a/src/Build.UnitTests/Scanner_Tests.cs b/src/Build.UnitTests/Scanner_Tests.cs index ae6880ac5bd..97d786fd815 100644 --- a/src/Build.UnitTests/Scanner_Tests.cs +++ b/src/Build.UnitTests/Scanner_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -72,7 +72,10 @@ public void ErrorPosition() /// private void AdvanceToScannerError(Scanner lexer) { - while (lexer.Advance() && !lexer.IsNext(Token.TokenType.EndOfInput)); + while (lexer.Advance() && !lexer.IsNext(Token.TokenType.EndOfInput)) + { + ; + } } /// diff --git a/src/Build.UnitTests/SolutionFileBuilder.cs b/src/Build.UnitTests/SolutionFileBuilder.cs index 19f04cfe9c3..9c2a4823123 100644 --- a/src/Build.UnitTests/SolutionFileBuilder.cs +++ b/src/Build.UnitTests/SolutionFileBuilder.cs @@ -1,8 +1,5 @@ -// -------------------------------------------------------------------- -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// -------------------------------------------------------------------- +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // -------------------------------------------------------------------- // @@ -95,7 +92,7 @@ public static SolutionFileBuilder FromGraph( return new SolutionFileBuilder { Projects = graph.ProjectNodes.ToDictionary( - n => GraphTestingUtilities.GetProjectNumber((ProjectGraphNode) n).ToString(), + n => GraphTestingUtilities.GetProjectNumber((ProjectGraphNode)n).ToString(), n => n.ProjectInstance.FullPath), ProjectConfigurations = projectConfigurations, SolutionDependencies = solutionDependencies, @@ -121,7 +118,7 @@ public string BuildSolution() projectInfos.ShouldContainKey(parent); projectInfos.ShouldContainKey(dependency); - projectInfos[parent].AddDependency(projectInfos[dependency]); + projectInfos[parent].AddDependency(projectInfos[dependency]); } } @@ -141,9 +138,7 @@ public string BuildSolution() sc => new ProjectConfigurationInSolution( sc.ConfigurationName, sc.PlatformName, - true) - ) - ); + true))); var sb = new StringBuilder(); diff --git a/src/Build.UnitTests/TargetsFile_Test.cs b/src/Build.UnitTests/TargetsFile_Test.cs index ea6002e5bcb..3012894b25c 100644 --- a/src/Build.UnitTests/TargetsFile_Test.cs +++ b/src/Build.UnitTests/TargetsFile_Test.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -15,7 +15,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests from Orcas /// - sealed public class TargetsFile_Test + public sealed class TargetsFile_Test { #if FEATURE_COMPILE_IN_TESTS /// @@ -50,8 +50,7 @@ public void TargetARM() ", - logger - ); + logger); project.Build(); @@ -102,8 +101,7 @@ public void AnyCPULibraryProjectIsNot32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -153,8 +151,7 @@ public void ExplicitAnyCPULibraryProjectIsNot32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -209,8 +206,7 @@ we need to be .NET 4.5 or greater --> ", - logger - ); + logger); project.Build(); @@ -266,8 +262,7 @@ we need to be .NET 4.5 or greater --> ", - logger - ); + logger); project.Build(); @@ -316,8 +311,7 @@ public void AnyCPUExeProjectIs32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -367,8 +361,7 @@ public void ExplicitAnyCPUExeProjectIs32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -417,8 +410,7 @@ public void AnyCPU40ExeProjectIsNot32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -468,8 +460,7 @@ public void ExplicitAnyCPUExeProjectIsNot32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -524,8 +515,7 @@ public void AnyCPUAppContainerExeProjectIs32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -581,8 +571,7 @@ we need to be .NET 4.5 or greater --> ", - logger - ); + logger); project.Build(); @@ -633,8 +622,7 @@ public void AnyCPULibraryProjectIs32BitPreferredIfPrefer32BitSet() ", - logger - ); + logger); project.Build(); @@ -683,8 +671,7 @@ public void AnyCPUProjectWithNoExplicitOutputTypeIs32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -735,8 +722,7 @@ public void AnyCPUJupiterProjectWithNoExplicitOutputTypeIs32BitPreferred() ", - logger - ); + logger); project.Build(); @@ -773,8 +759,7 @@ public void TestGetFrameworkPaths() ", - logger - ); + logger); project.Build(); @@ -808,12 +793,10 @@ public void TestTargetFrameworkPaths() DependsOnTargets='GetFrameworkPaths'> -" - ); +"); Project project = ObjectModelHelpers.CreateInMemoryProject( projString, - logger - ); + logger); project.SetProperty("TargetFrameworkVersion", version); project.Build(); @@ -861,7 +844,7 @@ public void TestTargetFrameworkPaths() public void NoLinkMetadataSynthesisWhenDefinedInProject() { string[] files = null; - string outputPath = Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); + string outputPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); try { @@ -893,8 +876,7 @@ public void NoLinkMetadataSynthesisWhenDefinedInProject() ", - logger - ); + logger); project.Build(); @@ -974,8 +956,7 @@ public void SynthesizeLinkMetadataForItemsOnWhitelist() ", - logger - ); + logger); project.Build(); @@ -1052,8 +1033,7 @@ public void DontSynthesizeLinkMetadataIfPropertyNotSet() ", - logger - ); + logger); project.Build(); diff --git a/src/Build.UnitTests/TestComparers/ProjectInstanceModelTestComparers.cs b/src/Build.UnitTests/TestComparers/ProjectInstanceModelTestComparers.cs index ef9e52db8b9..b7fd3234b21 100644 --- a/src/Build.UnitTests/TestComparers/ProjectInstanceModelTestComparers.cs +++ b/src/Build.UnitTests/TestComparers/ProjectInstanceModelTestComparers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -27,7 +27,7 @@ public bool Equals(ProjectInstance x, ProjectInstance y) Assert.Equal(x.Properties, y.Properties, EqualityComparer.Default); Assert.Equal(x.TestEnvironmentalProperties, y.TestEnvironmentalProperties, EqualityComparer.Default); Helpers.AssertDictionariesEqual(x.GlobalProperties, y.GlobalProperties); - Assert.Equal(((EvaluatorData) x).GlobalPropertiesToTreatAsLocal, ((EvaluatorData) y).GlobalPropertiesToTreatAsLocal); + Assert.Equal(((EvaluatorData)x).GlobalPropertiesToTreatAsLocal, ((EvaluatorData)y).GlobalPropertiesToTreatAsLocal); Assert.Equal(x.Items.ToArray(), y.Items.ToArray(), ProjectItemInstance.ProjectItemInstanceEqualityComparer.Default); @@ -119,22 +119,22 @@ public bool Equals(ProjectTargetInstanceChild x, ProjectTargetInstanceChild y) { if (x is ProjectItemGroupTaskInstance) { - return new TargetItemGroupComparer().Equals((ProjectItemGroupTaskInstance) x, (ProjectItemGroupTaskInstance) y); + return new TargetItemGroupComparer().Equals((ProjectItemGroupTaskInstance)x, (ProjectItemGroupTaskInstance)y); } if (x is ProjectPropertyGroupTaskInstance) { - return new TargetPropertyGroupComparer().Equals((ProjectPropertyGroupTaskInstance) x, (ProjectPropertyGroupTaskInstance) y); + return new TargetPropertyGroupComparer().Equals((ProjectPropertyGroupTaskInstance)x, (ProjectPropertyGroupTaskInstance)y); } if (x is ProjectOnErrorInstance) { - return new TargetOnErrorComparer().Equals((ProjectOnErrorInstance) x, (ProjectOnErrorInstance) y); + return new TargetOnErrorComparer().Equals((ProjectOnErrorInstance)x, (ProjectOnErrorInstance)y); } if (x is ProjectTaskInstance) { - return new TargetTaskComparer().Equals((ProjectTaskInstance) x, (ProjectTaskInstance) y); + return new TargetTaskComparer().Equals((ProjectTaskInstance)x, (ProjectTaskInstance)y); } throw new NotImplementedException(); @@ -359,11 +359,11 @@ public bool Equals(ProjectTaskInstanceChild x, ProjectTaskInstanceChild y) { if (x is ProjectTaskOutputItemInstance) { - return new ProjectTaskOutputItemComparer().Equals((ProjectTaskOutputItemInstance) x, (ProjectTaskOutputItemInstance) y); + return new ProjectTaskOutputItemComparer().Equals((ProjectTaskOutputItemInstance)x, (ProjectTaskOutputItemInstance)y); } if (x is ProjectTaskOutputPropertyInstance) { - return new ProjectTaskOutputPropertyComparer().Equals((ProjectTaskOutputPropertyInstance) x, (ProjectTaskOutputPropertyInstance) y); + return new ProjectTaskOutputPropertyComparer().Equals((ProjectTaskOutputPropertyInstance)x, (ProjectTaskOutputPropertyInstance)y); } throw new NotImplementedException(); diff --git a/src/Build.UnitTests/TestComparers/TaskItemComparer.cs b/src/Build.UnitTests/TestComparers/TaskItemComparer.cs index 36b1da60309..b5e5d766b5b 100644 --- a/src/Build.UnitTests/TestComparers/TaskItemComparer.cs +++ b/src/Build.UnitTests/TestComparers/TaskItemComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Framework; diff --git a/src/Build.UnitTests/TestComparers/TaskRegistryComparers.cs b/src/Build.UnitTests/TestComparers/TaskRegistryComparers.cs index 73492a83c4f..e09aba6d6c1 100644 --- a/src/Build.UnitTests/TestComparers/TaskRegistryComparers.cs +++ b/src/Build.UnitTests/TestComparers/TaskRegistryComparers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -28,8 +28,7 @@ public bool Equals(TaskRegistry x, TaskRegistry y) { Assert.Equal(xp.Key, yp.Key, TaskRegistry.RegisteredTaskIdentity.RegisteredTaskIdentityComparer.Exact); Assert.Equal(xp.Value, yp.Value, new RegisteredTaskRecordComparer()); - } - ); + }); return true; } diff --git a/src/Build.UnitTests/TestData/ProjectInstanceTestObjects.cs b/src/Build.UnitTests/TestData/ProjectInstanceTestObjects.cs index 9f7435a781b..160f119a1a3 100644 --- a/src/Build.UnitTests/TestData/ProjectInstanceTestObjects.cs +++ b/src/Build.UnitTests/TestData/ProjectInstanceTestObjects.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Collections; @@ -51,8 +51,7 @@ public static ProjectItemGroupTaskItemInstance CreateTargetItem(int? counter = n removeMetadataLocation: new MockElementLocation($"rm{stringCounter}"), keepDuplicatesLocation: new MockElementLocation($"kd{stringCounter}"), conditionLocation: new MockElementLocation($"cl{stringCounter}"), - metadata: metadata - ); + metadata: metadata); } public static ProjectItemGroupTaskMetadataInstance CreateTargetItemMetadata(int? counter = null) @@ -64,8 +63,7 @@ public static ProjectItemGroupTaskMetadataInstance CreateTargetItemMetadata(int? $"v{stringCounter}", $"c{stringCounter}", new MockElementLocation($"location{stringCounter}"), - new MockElementLocation($"condition{stringCounter}") - ); + new MockElementLocation($"condition{stringCounter}")); } public static ProjectPropertyGroupTaskInstance CreateTargetPropertyGroup( @@ -79,8 +77,7 @@ public static ProjectPropertyGroupTaskInstance CreateTargetPropertyGroup( $"c{stringCounter}", new MockElementLocation($"location{stringCounter}"), new MockElementLocation($"conditionLocation{stringCounter}"), - properties - ); + properties); } public static ProjectPropertyGroupTaskPropertyInstance CreateTargetProperty(int? counter = null) @@ -92,8 +89,7 @@ public static ProjectPropertyGroupTaskPropertyInstance CreateTargetProperty(int? $"v{stringCounter}", $"c{stringCounter}", new MockElementLocation($"location{stringCounter}"), - new MockElementLocation($"conditionLocation{stringCounter}") - ); + new MockElementLocation($"conditionLocation{stringCounter}")); } public static ProjectOnErrorInstance CreateTargetOnError(int? counter = null) @@ -133,8 +129,7 @@ public static ProjectTaskInstance CreateTargetTask( new MockElementLocation($"conditionLocation{stringCounter}"), new MockElementLocation($"coeLocation{stringCounter}"), new MockElementLocation($"msbrLocation{stringCounter}"), - new MockElementLocation($"msbaLocation{stringCounter}") - ); + new MockElementLocation($"msbaLocation{stringCounter}")); } public static ProjectTaskOutputPropertyInstance CreateTaskPropertyOutput(int? counter = null) @@ -148,8 +143,7 @@ public static ProjectTaskOutputPropertyInstance CreateTaskPropertyOutput(int? co new MockElementLocation($"location{stringCounter}"), new MockElementLocation($"propertyLocation{stringCounter}"), new MockElementLocation($"taskParamLocation{stringCounter}"), - new MockElementLocation($"conditionLocation{stringCounter}") - ); + new MockElementLocation($"conditionLocation{stringCounter}")); } public static ProjectTaskOutputItemInstance CreateTaskItemyOutput(int? counter = null) @@ -163,8 +157,7 @@ public static ProjectTaskOutputItemInstance CreateTaskItemyOutput(int? counter = new MockElementLocation($"location{stringCounter}"), new MockElementLocation($"itemLocation{stringCounter}"), new MockElementLocation($"taskParamLocation{stringCounter}"), - new MockElementLocation($"conditionLocation{stringCounter}") - ); + new MockElementLocation($"conditionLocation{stringCounter}")); } public static ProjectTargetInstance CreateTarget( @@ -197,8 +190,7 @@ public static ProjectTargetInstance CreateTarget( new MockElementLocation($"atLocation{stringCounter}"), children, errorChildren, - true - ); + true); } private static string CounterToString(int? counter) diff --git a/src/Build.UnitTests/Utilities_Tests.cs b/src/Build.UnitTests/Utilities_Tests.cs index 6159f3af2c1..00162f01816 100644 --- a/src/Build.UnitTests/Utilities_Tests.cs +++ b/src/Build.UnitTests/Utilities_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -165,8 +165,7 @@ public void IllegalConditionOnProjectExtensions() "); - } - ); + }); } /// /// Verify ProjectExtensions cannot exist twice @@ -183,8 +182,7 @@ public void RepeatedProjectExtensions() "); - } - ); + }); } /// /// Tests that we can correctly pass a CDATA tag containing less-than signs into a property value. diff --git a/src/Build.UnitTests/WarningsAsMessagesAndErrors_Tests.cs b/src/Build.UnitTests/WarningsAsMessagesAndErrors_Tests.cs index ed6ef8fd68a..dc353692197 100644 --- a/src/Build.UnitTests/WarningsAsMessagesAndErrors_Tests.cs +++ b/src/Build.UnitTests/WarningsAsMessagesAndErrors_Tests.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Linq; using Microsoft.Build.Framework; @@ -15,8 +18,7 @@ public sealed class WarningsAsMessagesAndErrorsTests { private const string ExpectedEventMessage = "03767942CDB147B98D0ECDBDE1436DA3"; private const string ExpectedEventCode = "0BF68998"; - - ITestOutputHelper _output; + private ITestOutputHelper _output; public WarningsAsMessagesAndErrorsTests(ITestOutputHelper output) { @@ -170,9 +172,7 @@ public void TreatWarningsAsMessagesWhenSpecifiedIndirectly() { {"Foo", ExpectedEventCode}, }, - warningsAsMessages: "$(Foo)" - ) - ); + warningsAsMessages: "$(Foo)")); VerifyBuildMessageEvent(logger); } @@ -213,8 +213,7 @@ public void TreatWarningAsMessageOverridesTreatingItAsError() MockLogger logger = ObjectModelHelpers.BuildProjectExpectSuccess( GetTestProject( warningsAsMessages: ExpectedEventCode, - warningsAsErrors: ExpectedEventCode - )); + warningsAsErrors: ExpectedEventCode)); VerifyBuildMessageEvent(logger); } @@ -275,7 +274,7 @@ private string GetTestProject(bool? treatAllWarningsAsErrors = null, string warn } [Theory] - + [InlineData("MSB1235", "MSB1234", "MSB1234", "MSB1234", false)] // Log MSB1234, treat as error via MSBuildWarningsAsErrors [InlineData("MSB1235", "", "MSB1234", "MSB1234", true)] // Log MSB1234, expect MSB1234 as error via MSBuildTreatWarningsAsErrors [InlineData("MSB1234", "MSB1234", "MSB1234", "MSB4181", true)]// Log MSB1234, MSBuildWarningsAsMessages takes priority diff --git a/src/Build/AssemblyInfo.cs b/src/Build/AssemblyInfo.cs index 7462770fbd9..40a6964c0e5 100644 --- a/src/Build/AssemblyInfo.cs +++ b/src/Build/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Build/BackEnd/BuildManager/BuildManager.cs b/src/Build/BackEnd/BuildManager/BuildManager.cs index 12a3d83376e..532f9b3e778 100644 --- a/src/Build/BackEnd/BuildManager/BuildManager.cs +++ b/src/Build/BackEnd/BuildManager/BuildManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -49,7 +49,7 @@ public class BuildManager : INodePacketHandler, IBuildComponentHost, IDisposable // TODO: Figure out a more elegant way to do this. // The rationale for this is that we can detect during design-time builds in the Evaluator (which populates this) that the project cache will be used so that we don't // need to evaluate the project at build time just to figure that out, which would regress perf for scenarios which don't use the project cache. - internal static ConcurrentDictionary ProjectCacheDescriptors { get; } = new (ProjectCacheDescriptorEqualityComparer.Instance); + internal static ConcurrentDictionary ProjectCacheDescriptors { get; } = new(ProjectCacheDescriptorEqualityComparer.Instance); /// /// The object used for thread-safe synchronization of static members. @@ -1386,7 +1386,7 @@ private void LoadSolutionIntoConfiguration(BuildRequestConfiguration config, Bui config.GlobalProperties, config.ExplicitToolsVersionSpecified ? config.ToolsVersion : null, _buildParameters, - ((IBuildComponentHost) this).LoggingService, + ((IBuildComponentHost)this).LoggingService, request.BuildEventContext, false /* loaded by solution parser*/, config.TargetNames, @@ -1404,7 +1404,8 @@ private void LoadSolutionIntoConfiguration(BuildRequestConfiguration config, Bui // metaproject as well. var newConfig = new BuildRequestConfiguration( GetNewConfigurationId(), - instances[i]) { ExplicitlyLoaded = config.ExplicitlyLoaded }; + instances[i]) + { ExplicitlyLoaded = config.ExplicitlyLoaded }; if (_configCache.GetMatchingConfiguration(newConfig) == null) { _configCache.AddConfiguration(newConfig); @@ -1623,7 +1624,7 @@ private void WaitForAllLoggingServiceEventsToBeProcessed() // this has to be called out of the lock (_syncLock) // because processing events can callback to 'this' instance and cause deadlock Debug.Assert(!Monitor.IsEntered(_syncLock)); - ((LoggingService) ((IBuildComponentHost) this).LoggingService).WaitForLoggingToProcessEvents(); + ((LoggingService)((IBuildComponentHost)this).LoggingService).WaitForLoggingToProcessEvents(); } /// @@ -1759,7 +1760,7 @@ void IssueBuildSubmissionToSchedulerImpl(BuildSubmission submission, bool allowM } } - BuildRequestBlocker blocker = new BuildRequestBlocker(-1, Array.Empty(), new[] {submission.BuildRequest}); + BuildRequestBlocker blocker = new BuildRequestBlocker(-1, Array.Empty(), new[] { submission.BuildRequest }); HandleNewRequest(Scheduler.VirtualNode, blocker); } @@ -1904,8 +1905,7 @@ static void DumpGraph(ProjectGraph graph, IReadOnlyDictionary BuildGraph( ProjectGraph projectGraph, IReadOnlyDictionary> targetsPerNode, - GraphBuildRequestData graphBuildRequestData - ) + GraphBuildRequestData graphBuildRequestData) { var waitHandle = new AutoResetEvent(true); var graphBuildStateLock = new object(); @@ -2674,8 +2674,7 @@ private NodeConfiguration GetNodeConfiguration() ILoggingService loggingService = ((IBuildComponentHost)this).GetComponent(BuildComponentType.LoggingService) as ILoggingService; var remoteLoggers = new List(loggingService.LoggerDescriptions); - _nodeConfiguration = new NodeConfiguration - ( + _nodeConfiguration = new NodeConfiguration( -1, /* must be assigned by the NodeManager */ _buildParameters, remoteLoggers.ToArray() @@ -2686,8 +2685,7 @@ private NodeConfiguration GetNodeConfiguration() loggingService.IncludeEvaluationMetaprojects, loggingService.IncludeEvaluationProfile, loggingService.IncludeEvaluationPropertiesAndItems, - loggingService.IncludeTaskInputs) - ); + loggingService.IncludeTaskInputs)); } return _nodeConfiguration; @@ -3096,7 +3094,7 @@ public LoggerVerbosity Verbosity public string Parameters { get => String.Empty; - set{ } + set { } } /// diff --git a/src/Build/BackEnd/BuildManager/BuildParameters.cs b/src/Build/BackEnd/BuildManager/BuildParameters.cs index 5bc3111c107..a91ec457ef8 100644 --- a/src/Build/BackEnd/BuildManager/BuildParameters.cs +++ b/src/Build/BackEnd/BuildManager/BuildParameters.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -413,7 +413,7 @@ public IDictionary EnvironmentProperties get { return new ReadOnlyConvertingDictionary(_environmentProperties, - instance => ((IProperty) instance).EvaluatedValueEscaped); + instance => ((IProperty)instance).EvaluatedValueEscaped); } } @@ -448,7 +448,7 @@ public IDictionary GlobalProperties get { return new ReadOnlyConvertingDictionary(_globalProperties, - instance => ((IProperty) instance).EvaluatedValueEscaped); + instance => ((IProperty)instance).EvaluatedValueEscaped); } set @@ -859,7 +859,7 @@ void ITranslatable.Translate(ITranslator translator) translator.Translate(ref _shutdownInProcNodeOnBuildFinish); translator.Translate(ref _logTaskInputs); translator.Translate(ref _logInitialPropertiesAndItems); - translator.TranslateEnum(ref _projectLoadSettings, (int) _projectLoadSettings); + translator.TranslateEnum(ref _projectLoadSettings, (int)_projectLoadSettings); translator.Translate(ref _interactive); translator.Translate(ref _isolateProjects); @@ -871,7 +871,7 @@ void ITranslatable.Translate(ITranslator translator) // LowPriority is passed as an argument to new nodes, so it doesn't need to be transmitted here. } -#region INodePacketTranslatable Members + #region INodePacketTranslatable Members /// /// The class factory for deserialization. @@ -881,7 +881,7 @@ internal static BuildParameters FactoryForDeserialization(ITranslator translator return new BuildParameters(translator); } -#endregion + #endregion /// /// Gets the value of a boolean environment setting which is not expected to change. diff --git a/src/Build/BackEnd/BuildManager/BuildRequestData.cs b/src/Build/BackEnd/BuildManager/BuildRequestData.cs index 0f90db80b49..b8ae83411b2 100644 --- a/src/Build/BackEnd/BuildManager/BuildRequestData.cs +++ b/src/Build/BackEnd/BuildManager/BuildRequestData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/BuildManager/BuildSubmission.cs b/src/Build/BackEnd/BuildManager/BuildSubmission.cs index a6ee56f90ba..1a50e0248e0 100644 --- a/src/Build/BackEnd/BuildManager/BuildSubmission.cs +++ b/src/Build/BackEnd/BuildManager/BuildSubmission.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Threading; diff --git a/src/Build/BackEnd/BuildManager/CacheAggregator.cs b/src/Build/BackEnd/BuildManager/CacheAggregator.cs index 104c59fa31b..b6ce5329661 100644 --- a/src/Build/BackEnd/BuildManager/CacheAggregator.cs +++ b/src/Build/BackEnd/BuildManager/CacheAggregator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -94,8 +94,7 @@ private void InsertCaches(IConfigCache configCache, IResultsCache resultsCache) configIdMapping[result.ConfigurationId], BuildRequest.InvalidGlobalRequestId, BuildRequest.InvalidGlobalRequestId, - BuildRequest.InvalidNodeRequestId - )); + BuildRequest.InvalidNodeRequestId)); } } } diff --git a/src/Build/BackEnd/BuildManager/CacheSerialization.cs b/src/Build/BackEnd/BuildManager/CacheSerialization.cs index 950182296ab..d1864fef845 100644 --- a/src/Build/BackEnd/BuildManager/CacheSerialization.cs +++ b/src/Build/BackEnd/BuildManager/CacheSerialization.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs b/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs index cb18ea93bb4..d6454f5c8c5 100644 --- a/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs +++ b/src/Build/BackEnd/BuildManager/LegacyThreadingData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Threading; @@ -88,11 +88,9 @@ internal void RegisterSubmissionForLegacyThread(int submissionId) { ErrorUtilities.VerifyThrow(!_legacyThreadingEventsById.ContainsKey(submissionId), "Submission {0} should not already be registered with LegacyThreadingData", submissionId); - _legacyThreadingEventsById[submissionId] = new Tuple - ( + _legacyThreadingEventsById[submissionId] = new Tuple( new AutoResetEvent(false), - new ManualResetEvent(false) - ); + new ManualResetEvent(false)); } } @@ -151,11 +149,9 @@ internal Task GetLegacyThreadInactiveTask(int submissionId) /// internal void SignalLegacyThreadStart(RequestBuilder instance) { - ErrorUtilities.VerifyThrow - ( + ErrorUtilities.VerifyThrow( instance?.RequestEntry?.Request != null, - "Cannot signal legacy thread start for a RequestBuilder without a request" - ); + "Cannot signal legacy thread start for a RequestBuilder without a request"); int submissionId = instance.RequestEntry.Request.SubmissionId; InstanceForMainThread = instance; diff --git a/src/Build/BackEnd/BuildManager/RequestedProjectState.cs b/src/Build/BackEnd/BuildManager/RequestedProjectState.cs index f1aa79796a3..d195131a51c 100644 --- a/src/Build/BackEnd/BuildManager/RequestedProjectState.cs +++ b/src/Build/BackEnd/BuildManager/RequestedProjectState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Client/MSBuildClient.cs b/src/Build/BackEnd/Client/MSBuildClient.cs index 262b3eedd79..e655c52b8aa 100644 --- a/src/Build/BackEnd/Client/MSBuildClient.cs +++ b/src/Build/BackEnd/Client/MSBuildClient.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -138,11 +138,17 @@ public MSBuildClient( private void CreateNodePipeStream() { - _nodeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + _nodeStream = new NamedPipeClientStream( + serverName: ".", + _pipeName, + PipeDirection.InOut, + PipeOptions.Asynchronous #if FEATURE_PIPEOPTIONS_CURRENTUSERONLY | PipeOptions.CurrentUserOnly #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter _packetPump = new MSBuildClientPacketPump(_nodeStream); } @@ -412,7 +418,7 @@ private void ConfigureAndQueryConsoleProperties() return (acceptAnsiColorCodes: acceptAnsiColorCodes, outputIsScreen: outputIsScreen); } - + private int QueryConsoleBufferWidth() { int consoleBufferWidth = -1; @@ -492,7 +498,7 @@ private bool TryLaunchServer() } catch (IOException ex) when (ex is not PathTooLongException) { - CommunicationsUtilities.Trace("Failed to obtain the current build server state: {0}", ex); + CommunicationsUtilities.Trace("Failed to obtain the current build server state: {0}", ex); CommunicationsUtilities.Trace("HResult: {0}.", ex.HResult); _exitResult.MSBuildClientExitType = MSBuildClientExitType.UnknownServerState; return false; @@ -526,7 +532,7 @@ private bool TryLaunchServer() private bool TrySendShutdownCommand() { _packetPump.ServerWillDisconnect(); - return TrySendPacket(() => new NodeBuildComplete(false /* no node reuse */)); + return TrySendPacket(() => new NodeBuildComplete(false /* no node reuse */)); } private ServerNodeBuildCommand GetServerNodeBuildCommand() diff --git a/src/Build/BackEnd/Client/MSBuildClientExitResult.cs b/src/Build/BackEnd/Client/MSBuildClientExitResult.cs index 8cb466741fa..ef58bba7517 100644 --- a/src/Build/BackEnd/Client/MSBuildClientExitResult.cs +++ b/src/Build/BackEnd/Client/MSBuildClientExitResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.Experimental { diff --git a/src/Build/BackEnd/Client/MSBuildClientExitType.cs b/src/Build/BackEnd/Client/MSBuildClientExitType.cs index 9ac0d49652a..84e999c433c 100644 --- a/src/Build/BackEnd/Client/MSBuildClientExitType.cs +++ b/src/Build/BackEnd/Client/MSBuildClientExitType.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + namespace Microsoft.Build.Experimental { public enum MSBuildClientExitType diff --git a/src/Build/BackEnd/Client/MSBuildClientPacketPump.cs b/src/Build/BackEnd/Client/MSBuildClientPacketPump.cs index 351f922451c..784116cf854 100644 --- a/src/Build/BackEnd/Client/MSBuildClientPacketPump.cs +++ b/src/Build/BackEnd/Client/MSBuildClientPacketPump.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Buffers.Binary; @@ -64,7 +64,7 @@ internal sealed class MSBuildClientPacketPump : INodePacketHandler, INodePacketF /// /// The binary translator for reading packets. /// - readonly ITranslator _binaryReadTranslator; + private readonly ITranslator _binaryReadTranslator; /// /// True if this side is gracefully disconnecting. @@ -262,7 +262,7 @@ private void RunReadLoop(Stream localStream, ManualResetEvent localPacketPumpShu while (packetBytesRead < packetLength) { - int bytesRead = localStream.Read(packetData, packetBytesRead, packetLength-packetBytesRead); + int bytesRead = localStream.Read(packetData, packetBytesRead, packetLength - packetBytesRead); if (bytesRead == 0) { // Incomplete read. Abort. @@ -271,7 +271,7 @@ private void RunReadLoop(Stream localStream, ManualResetEvent localPacketPumpShu packetBytesRead += bytesRead; } - + try { _packetFactory.DeserializeAndRoutePacket(0, packetType, _binaryReadTranslator); diff --git a/src/Build/BackEnd/Components/BuildComponentFactoryCollection.cs b/src/Build/BackEnd/Components/BuildComponentFactoryCollection.cs index 0bf9cfd50e0..5ea3ee2bde1 100644 --- a/src/Build/BackEnd/Components/BuildComponentFactoryCollection.cs +++ b/src/Build/BackEnd/Components/BuildComponentFactoryCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.BackEnd.Components.Caching; diff --git a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestConfigurationResponse.cs b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestConfigurationResponse.cs index 73596f26127..d8e39c9351a 100644 --- a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestConfigurationResponse.cs +++ b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestConfigurationResponse.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEngine.cs b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEngine.cs index 6618dc945c8..99fff072659 100644 --- a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEngine.cs +++ b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs index 5de7e1ed874..6ac44d35291 100644 --- a/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs +++ b/src/Build/BackEnd/Components/BuildRequestEngine/BuildRequestEntry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build/BackEnd/Components/BuildRequestEngine/FullyQualifiedBuildRequest.cs b/src/Build/BackEnd/Components/BuildRequestEngine/FullyQualifiedBuildRequest.cs index b415350f1e6..f096ca4d52e 100644 --- a/src/Build/BackEnd/Components/BuildRequestEngine/FullyQualifiedBuildRequest.cs +++ b/src/Build/BackEnd/Components/BuildRequestEngine/FullyQualifiedBuildRequest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Execution; using Microsoft.Build.Shared; @@ -33,8 +33,7 @@ public FullyQualifiedBuildRequest( string[] targets, bool resultsNeeded, bool skipStaticGraphIsolationConstraints = false, - BuildRequestDataFlags flags = BuildRequestDataFlags.None - ) + BuildRequestDataFlags flags = BuildRequestDataFlags.None) { ErrorUtilities.VerifyThrowArgumentNull(config, nameof(config)); ErrorUtilities.VerifyThrowArgumentNull(targets, nameof(targets)); @@ -116,7 +115,7 @@ public override bool Equals(object obj) return false; } - return GetType() == obj.GetType() && InternalEquals((FullyQualifiedBuildRequest) obj); + return GetType() == obj.GetType() && InternalEquals((FullyQualifiedBuildRequest)obj); } /// diff --git a/src/Build/BackEnd/Components/BuildRequestEngine/IBuildRequestEngine.cs b/src/Build/BackEnd/Components/BuildRequestEngine/IBuildRequestEngine.cs index 439c175fbb8..8d7d6cac205 100644 --- a/src/Build/BackEnd/Components/BuildRequestEngine/IBuildRequestEngine.cs +++ b/src/Build/BackEnd/Components/BuildRequestEngine/IBuildRequestEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 NodeLoggingContext = Microsoft.Build.BackEnd.Logging.NodeLoggingContext; diff --git a/src/Build/BackEnd/Components/Caching/ConfigCache.cs b/src/Build/BackEnd/Components/Caching/ConfigCache.cs index f2eac09484f..15d06a15c93 100644 --- a/src/Build/BackEnd/Components/Caching/ConfigCache.cs +++ b/src/Build/BackEnd/Components/Caching/ConfigCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -215,7 +215,7 @@ public int GetSmallestConfigId() return _configurations.OrderBy(kvp => kvp.Key).First().Key; } } - + /// /// Clears configurations from the configuration cache which have not been explicitly loaded. /// @@ -386,7 +386,7 @@ public void Translate(ITranslator translator) /// /// Factory for component creation. /// - static internal IBuildComponent CreateComponent(BuildComponentType componentType) + internal static IBuildComponent CreateComponent(BuildComponentType componentType) { ErrorUtilities.VerifyThrow(componentType == BuildComponentType.ConfigCache, "Cannot create components of type {0}", componentType); return new ConfigCache(); diff --git a/src/Build/BackEnd/Components/Caching/ConfigCacheWithOverride.cs b/src/Build/BackEnd/Components/Caching/ConfigCacheWithOverride.cs index 4660a22db52..ce4d7e531a0 100644 --- a/src/Build/BackEnd/Components/Caching/ConfigCacheWithOverride.cs +++ b/src/Build/BackEnd/Components/Caching/ConfigCacheWithOverride.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Caching/IConfigCache.cs b/src/Build/BackEnd/Components/Caching/IConfigCache.cs index 581474b8e12..c0bfc8b5461 100644 --- a/src/Build/BackEnd/Components/Caching/IConfigCache.cs +++ b/src/Build/BackEnd/Components/Caching/IConfigCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Caching/IPropertyCache.cs b/src/Build/BackEnd/Components/Caching/IPropertyCache.cs index 054467b6782..78c898b93d7 100644 --- a/src/Build/BackEnd/Components/Caching/IPropertyCache.cs +++ b/src/Build/BackEnd/Components/Caching/IPropertyCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/BackEnd/Components/Caching/IRegisteredTaskObjectCache.cs b/src/Build/BackEnd/Components/Caching/IRegisteredTaskObjectCache.cs index 4bf05c0688c..37683785d4d 100644 --- a/src/Build/BackEnd/Components/Caching/IRegisteredTaskObjectCache.cs +++ b/src/Build/BackEnd/Components/Caching/IRegisteredTaskObjectCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/Caching/IResultsCache.cs b/src/Build/BackEnd/Components/Caching/IResultsCache.cs index 033ec80bed0..c1786e8dbb2 100644 --- a/src/Build/BackEnd/Components/Caching/IResultsCache.cs +++ b/src/Build/BackEnd/Components/Caching/IResultsCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Caching/RegisteredTaskObjectCache.cs b/src/Build/BackEnd/Components/Caching/RegisteredTaskObjectCache.cs index f005944f766..843dfe14dff 100644 --- a/src/Build/BackEnd/Components/Caching/RegisteredTaskObjectCache.cs +++ b/src/Build/BackEnd/Components/Caching/RegisteredTaskObjectCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/Caching/ResultsCache.cs b/src/Build/BackEnd/Components/Caching/ResultsCache.cs index f932844178b..fd85472b1be 100644 --- a/src/Build/BackEnd/Components/Caching/ResultsCache.cs +++ b/src/Build/BackEnd/Components/Caching/ResultsCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -242,7 +242,7 @@ public void Translate(ITranslator translator) if (translator.Mode == TranslationDirection.ReadFromStream) { - _resultsByConfiguration = (ConcurrentDictionary) localReference; + _resultsByConfiguration = (ConcurrentDictionary)localReference; } } diff --git a/src/Build/BackEnd/Components/Caching/ResultsCacheResponse.cs b/src/Build/BackEnd/Components/Caching/ResultsCacheResponse.cs index 63302b46b01..0b9971a8b99 100644 --- a/src/Build/BackEnd/Components/Caching/ResultsCacheResponse.cs +++ b/src/Build/BackEnd/Components/Caching/ResultsCacheResponse.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Caching/ResultsCacheWithOverride.cs b/src/Build/BackEnd/Components/Caching/ResultsCacheWithOverride.cs index 68e56285f86..f5beb3e2031 100644 --- a/src/Build/BackEnd/Components/Caching/ResultsCacheWithOverride.cs +++ b/src/Build/BackEnd/Components/Caching/ResultsCacheWithOverride.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Communications/CurrentHost.cs b/src/Build/BackEnd/Components/Communications/CurrentHost.cs index 5eec58d2d0b..97855dfd97f 100644 --- a/src/Build/BackEnd/Components/Communications/CurrentHost.cs +++ b/src/Build/BackEnd/Components/Communications/CurrentHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if RUNTIME_TYPE_NETCORE || MONO using System.Diagnostics; diff --git a/src/Build/BackEnd/Components/Communications/INodeManager.cs b/src/Build/BackEnd/Components/Communications/INodeManager.cs index f35f8cba087..f5b79fa0ba7 100644 --- a/src/Build/BackEnd/Components/Communications/INodeManager.cs +++ b/src/Build/BackEnd/Components/Communications/INodeManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Build/BackEnd/Components/Communications/INodeProvider.cs b/src/Build/BackEnd/Components/Communications/INodeProvider.cs index 810dc4d9011..2cb875e0764 100644 --- a/src/Build/BackEnd/Components/Communications/INodeProvider.cs +++ b/src/Build/BackEnd/Components/Communications/INodeProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/BackEnd/Components/Communications/LogMessagePacket.cs b/src/Build/BackEnd/Components/Communications/LogMessagePacket.cs index 31591eb8c6d..c3b525eec89 100644 --- a/src/Build/BackEnd/Components/Communications/LogMessagePacket.cs +++ b/src/Build/BackEnd/Components/Communications/LogMessagePacket.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -38,7 +38,7 @@ private LogMessagePacket(ITranslator translator) /// /// Factory for serialization /// - static internal INodePacket FactoryForDeserialization(ITranslator translator) + internal static INodePacket FactoryForDeserialization(ITranslator translator) { return new LogMessagePacket(translator); } diff --git a/src/Build/BackEnd/Components/Communications/NodeEndpointInProc.cs b/src/Build/BackEnd/Components/Communications/NodeEndpointInProc.cs index 35dcda21565..4c7c7fbd385 100644 --- a/src/Build/BackEnd/Components/Communications/NodeEndpointInProc.cs +++ b/src/Build/BackEnd/Components/Communications/NodeEndpointInProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Build/BackEnd/Components/Communications/NodeEndpointOutOfProc.cs b/src/Build/BackEnd/Components/Communications/NodeEndpointOutOfProc.cs index dc312773b45..2a7f57ece4e 100644 --- a/src/Build/BackEnd/Components/Communications/NodeEndpointOutOfProc.cs +++ b/src/Build/BackEnd/Components/Communications/NodeEndpointOutOfProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Internal; using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/Communications/NodeFailedToLaunchException.cs b/src/Build/BackEnd/Components/Communications/NodeFailedToLaunchException.cs index 237b58a810b..657bfc4b4fb 100644 --- a/src/Build/BackEnd/Components/Communications/NodeFailedToLaunchException.cs +++ b/src/Build/BackEnd/Components/Communications/NodeFailedToLaunchException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -78,7 +78,7 @@ public string ErrorDescription #if FEATURE_SECURITY_PERMISSIONS [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] #endif - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); diff --git a/src/Build/BackEnd/Components/Communications/NodeInfo.cs b/src/Build/BackEnd/Components/Communications/NodeInfo.cs index fbdf2efd3b7..c8f61343369 100644 --- a/src/Build/BackEnd/Components/Communications/NodeInfo.cs +++ b/src/Build/BackEnd/Components/Communications/NodeInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Communications/NodeLauncher.cs b/src/Build/BackEnd/Components/Communications/NodeLauncher.cs index b39bcc78b9e..611c4ca68c9 100644 --- a/src/Build/BackEnd/Components/Communications/NodeLauncher.cs +++ b/src/Build/BackEnd/Components/Communications/NodeLauncher.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -112,13 +112,11 @@ private Process StartInternal(string msbuildLocation, string commandLineArgs) } catch (Exception ex) { - CommunicationsUtilities.Trace - ( + CommunicationsUtilities.Trace( "Failed to launch node from {0}. CommandLine: {1}" + Environment.NewLine + "{2}", msbuildLocation, commandLineArgs, - ex.ToString() - ); + ex.ToString()); throw new NodeFailedToLaunchException(ex); } @@ -139,8 +137,7 @@ private Process StartInternal(string msbuildLocation, string commandLineArgs) processSecurityAttributes.nLength = Marshal.SizeOf(); threadSecurityAttributes.nLength = Marshal.SizeOf(); - bool result = BackendNativeMethods.CreateProcess - ( + bool result = BackendNativeMethods.CreateProcess( exeName, commandLineArgs, ref processSecurityAttributes, @@ -150,22 +147,19 @@ private Process StartInternal(string msbuildLocation, string commandLineArgs) BackendNativeMethods.NullPtr, null, ref startInfo, - out processInfo - ); + out processInfo); if (!result) { // Creating an instance of this exception calls GetLastWin32Error and also converts it to a user-friendly string. System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(); - CommunicationsUtilities.Trace - ( + CommunicationsUtilities.Trace( "Failed to launch node from {0}. System32 Error code {1}. Description {2}. CommandLine: {2}", msbuildLocation, e.NativeErrorCode.ToString(CultureInfo.InvariantCulture), e.Message, - commandLineArgs - ); + commandLineArgs); throw new NodeFailedToLaunchException(e.NativeErrorCode.ToString(CultureInfo.InvariantCulture), e.Message); } diff --git a/src/Build/BackEnd/Components/Communications/NodeManager.cs b/src/Build/BackEnd/Components/Communications/NodeManager.cs index 6d9f73590eb..ed7bcc24057 100644 --- a/src/Build/BackEnd/Components/Communications/NodeManager.cs +++ b/src/Build/BackEnd/Components/Communications/NodeManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -275,7 +275,7 @@ public void RoutePacket(int nodeId, INodePacket packet) /// /// Factory for component creation. /// - static internal IBuildComponent CreateComponent(BuildComponentType type) + internal static IBuildComponent CreateComponent(BuildComponentType type) { ErrorUtilities.VerifyThrow(type == BuildComponentType.NodeManager, "Cannot create component of type {0}", type); return new NodeManager(); diff --git a/src/Build/BackEnd/Components/Communications/NodeProviderInProc.cs b/src/Build/BackEnd/Components/Communications/NodeProviderInProc.cs index 337cbd76f03..26cf8ed28f3 100644 --- a/src/Build/BackEnd/Components/Communications/NodeProviderInProc.cs +++ b/src/Build/BackEnd/Components/Communications/NodeProviderInProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -347,7 +347,7 @@ public void Dispose() /// /// Factory for component creation. /// - static internal IBuildComponent CreateComponent(BuildComponentType type) + internal static IBuildComponent CreateComponent(BuildComponentType type) { ErrorUtilities.VerifyThrow(type == BuildComponentType.InProcNodeProvider, "Cannot create component of type {0}", type); return new NodeProviderInProc(); @@ -373,14 +373,14 @@ private bool InstantiateNode(INodePacketFactory factory) #if FEATURE_THREAD_CULTURE _inProcNodeThread = new Thread(InProcNodeThreadProc, BuildParameters.ThreadStackSize); #else - CultureInfo culture = _componentHost.BuildParameters.Culture; - CultureInfo uiCulture = _componentHost.BuildParameters.UICulture; - _inProcNodeThread = new Thread(() => - { - CultureInfo.CurrentCulture = culture; - CultureInfo.CurrentUICulture = uiCulture; - InProcNodeThreadProc(); - }); + CultureInfo culture = _componentHost.BuildParameters.Culture; + CultureInfo uiCulture = _componentHost.BuildParameters.UICulture; + _inProcNodeThread = new Thread(() => + { + CultureInfo.CurrentCulture = culture; + CultureInfo.CurrentUICulture = uiCulture; + InProcNodeThreadProc(); + }); #endif _inProcNodeThread.Name = String.Format(CultureInfo.CurrentCulture, "In-proc Node ({0})", _componentHost.Name); _inProcNodeThread.IsBackground = true; diff --git a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProc.cs b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProc.cs index 96ebeef27f9..c587d69211f 100644 --- a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProc.cs +++ b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -192,7 +192,7 @@ public void ShutdownComponent() /// /// Static factory for component creation. /// - static internal IBuildComponent CreateComponent(BuildComponentType componentType) + internal static IBuildComponent CreateComponent(BuildComponentType componentType) { ErrorUtilities.VerifyThrow(componentType == BuildComponentType.OutOfProcNodeProvider, "Factory cannot create components of type {0}", componentType); return new NodeProviderOutOfProc(); diff --git a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcBase.cs b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcBase.cs index 77741a46412..3b88899af8b 100644 --- a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcBase.cs +++ b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Buffers.Binary; @@ -111,7 +111,7 @@ protected void ShutdownConnectedNodes(List contextsToShutDown, bool // We wait for child nodes to exit to avoid them changing the terminal // after this process terminates. - bool waitForExit = !enableReuse && + bool waitForExit = !enableReuse && !Console.IsInputRedirected && Traits.Instance.EscapeHatches.EnsureStdOutForChildNodesIsPrimaryStdout; @@ -316,12 +316,10 @@ bool StartNewNode(int nodeId) { if (FrameworkLocationHelper.GetPathToDotNetFrameworkV35(DotNetFrameworkArchitecture.Current) == null) { - CommunicationsUtilities.Trace - ( + CommunicationsUtilities.Trace( "Failed to launch node from {0}. The required .NET Framework v3.5 is not installed or enabled. CommandLine: {1}", msbuildLocation, - commandLineArgs - ); + commandLineArgs); string nodeFailedToLaunchError = ResourceUtilities.GetResourceString("TaskHostNodeFailedToLaunchErrorCodeNet35NotInstalled"); throw new NodeFailedToLaunchException(null, nodeFailedToLaunchError); @@ -442,11 +440,17 @@ private Stream TryConnectToProcess(int nodeProcessId, int timeout, Handshake han // Try and connect to the process. string pipeName = NamedPipeUtil.GetPlatformSpecificPipeName(nodeProcessId); - NamedPipeClientStream nodeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + NamedPipeClientStream nodeStream = new NamedPipeClientStream( + serverName: ".", + pipeName, + PipeDirection.InOut, + PipeOptions.Asynchronous #if FEATURE_PIPEOPTIONS_CURRENTUSERONLY - | PipeOptions.CurrentUserOnly + | PipeOptions.CurrentUserOnly #endif - ); + ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter CommunicationsUtilities.Trace("Attempting connect to PID {0} with pipe {1} with timeout {2} ms", nodeProcessId, pipeName, timeout); try @@ -519,7 +523,7 @@ internal static void ConnectToPipeStream(NamedPipeClientStream nodeStream, strin /// internal class NodeContext { - enum ExitPacketState + private enum ExitPacketState { None, ExitPacketQueued, diff --git a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs index b9a9d2a2f2f..c892dc79e2e 100644 --- a/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs +++ b/src/Build/BackEnd/Components/Communications/NodeProviderOutOfProcTaskHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -346,7 +346,7 @@ public void PacketReceived(int node, INodePacket packet) /// /// Static factory for component creation. /// - static internal IBuildComponent CreateComponent(BuildComponentType componentType) + internal static IBuildComponent CreateComponent(BuildComponentType componentType) { ErrorUtilities.VerifyThrow(componentType == BuildComponentType.OutOfProcTaskHostNodeProvider, "Factory cannot create components of type {0}", componentType); return new NodeProviderOutOfProcTaskHost(); @@ -376,7 +376,8 @@ internal static void ClearCachedTaskHostPaths() internal static string GetTaskHostNameFromHostContext(HandshakeOptions hostContext) { ErrorUtilities.VerifyThrowInternalErrorUnreachable((hostContext & HandshakeOptions.TaskHost) == HandshakeOptions.TaskHost); - if ((hostContext & HandshakeOptions.CLR2) == HandshakeOptions.CLR2) { + if ((hostContext & HandshakeOptions.CLR2) == HandshakeOptions.CLR2) + { return TaskHostNameForClr2TaskHost; } else diff --git a/src/Build/BackEnd/Components/Communications/ServerNodeEndpointOutOfProc.cs b/src/Build/BackEnd/Components/Communications/ServerNodeEndpointOutOfProc.cs index 9616f90964b..4bd0939f25c 100644 --- a/src/Build/BackEnd/Components/Communications/ServerNodeEndpointOutOfProc.cs +++ b/src/Build/BackEnd/Components/Communications/ServerNodeEndpointOutOfProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Internal; diff --git a/src/Build/BackEnd/Components/Communications/TaskHostNodeManager.cs b/src/Build/BackEnd/Components/Communications/TaskHostNodeManager.cs index 2b2102095b8..914acb1de57 100644 --- a/src/Build/BackEnd/Components/Communications/TaskHostNodeManager.cs +++ b/src/Build/BackEnd/Components/Communications/TaskHostNodeManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; @@ -164,7 +164,7 @@ public void RoutePacket(int nodeId, INodePacket packet) /// /// Factory for component creation. /// - static internal IBuildComponent CreateComponent(BuildComponentType type) + internal static IBuildComponent CreateComponent(BuildComponentType type) { ErrorUtilities.VerifyThrow(type == BuildComponentType.TaskHostNodeManager, "Cannot create component of type {0}", type); return new TaskHostNodeManager(); diff --git a/src/Build/BackEnd/Components/Communications/TranslatorExtensions.cs b/src/Build/BackEnd/Components/Communications/TranslatorExtensions.cs index 11aea7b2c52..6aa644f4227 100644 --- a/src/Build/BackEnd/Components/Communications/TranslatorExtensions.cs +++ b/src/Build/BackEnd/Components/Communications/TranslatorExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -91,11 +91,11 @@ public static T FactoryForDeserializingTypeWithName(this ITranslator translat return constructor; }); - var targetInstanceChild = (ITranslatable) parameterlessConstructor.Invoke(Array.Empty()); + var targetInstanceChild = (ITranslatable)parameterlessConstructor.Invoke(Array.Empty()); targetInstanceChild.Translate(translator); - return (T) targetInstanceChild; + return (T)targetInstanceChild; } public static void TranslateOptionalBuildEventContext(this ITranslator translator, ref BuildEventContext buildEventContext) diff --git a/src/Build/BackEnd/Components/IBuildComponent.cs b/src/Build/BackEnd/Components/IBuildComponent.cs index 6ee30b83ed9..e79f6a24444 100644 --- a/src/Build/BackEnd/Components/IBuildComponent.cs +++ b/src/Build/BackEnd/Components/IBuildComponent.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BackEnd { diff --git a/src/Build/BackEnd/Components/IBuildComponentHost.cs b/src/Build/BackEnd/Components/IBuildComponentHost.cs index 100571a029f..874159feb38 100644 --- a/src/Build/BackEnd/Components/IBuildComponentHost.cs +++ b/src/Build/BackEnd/Components/IBuildComponentHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService; using BuildParameters = Microsoft.Build.Execution.BuildParameters; diff --git a/src/Build/BackEnd/Components/Logging/BuildEventArgTransportSink.cs b/src/Build/BackEnd/Components/Logging/BuildEventArgTransportSink.cs index db701c61150..ccaf8c46ea1 100644 --- a/src/Build/BackEnd/Components/Logging/BuildEventArgTransportSink.cs +++ b/src/Build/BackEnd/Components/Logging/BuildEventArgTransportSink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/Logging/BuildLoggingContext.cs b/src/Build/BackEnd/Components/Logging/BuildLoggingContext.cs index aa2a8a9a3da..415a79fa848 100644 --- a/src/Build/BackEnd/Components/Logging/BuildLoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/BuildLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/BackEnd/Components/Logging/CentralForwardingLogger.cs b/src/Build/BackEnd/Components/Logging/CentralForwardingLogger.cs index 4cd8e3abf0b..eb2fe9a8cee 100644 --- a/src/Build/BackEnd/Components/Logging/CentralForwardingLogger.cs +++ b/src/Build/BackEnd/Components/Logging/CentralForwardingLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/Logging/EvaluationLoggingContext.cs b/src/Build/BackEnd/Components/Logging/EvaluationLoggingContext.cs index 1a4d63c65a9..31223745d8b 100644 --- a/src/Build/BackEnd/Components/Logging/EvaluationLoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/EvaluationLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using Microsoft.Build.BackEnd.Logging; diff --git a/src/Build/BackEnd/Components/Logging/EventRedirectorToSink.cs b/src/Build/BackEnd/Components/Logging/EventRedirectorToSink.cs index 8219327f45b..edf9d9d2f3e 100644 --- a/src/Build/BackEnd/Components/Logging/EventRedirectorToSink.cs +++ b/src/Build/BackEnd/Components/Logging/EventRedirectorToSink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/Logging/EventSourceSink.cs b/src/Build/BackEnd/Components/Logging/EventSourceSink.cs index 5604021e28a..e76797ee3cc 100644 --- a/src/Build/BackEnd/Components/Logging/EventSourceSink.cs +++ b/src/Build/BackEnd/Components/Logging/EventSourceSink.cs @@ -1,7 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// -// Sink which will take in a build event and raise it on its internal event source +// 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 Microsoft.Build.Framework; @@ -95,7 +93,7 @@ internal sealed class EventSourceSink : /// occurred. It is raised on every event. /// public event AnyEventHandler AnyEventRaised; - + /// /// This event is raised to log telemetry. /// diff --git a/src/Build/BackEnd/Components/Logging/ForwardingLoggerRecord.cs b/src/Build/BackEnd/Components/Logging/ForwardingLoggerRecord.cs index d2b9738db36..4b7a6beffe9 100644 --- a/src/Build/BackEnd/Components/Logging/ForwardingLoggerRecord.cs +++ b/src/Build/BackEnd/Components/Logging/ForwardingLoggerRecord.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/Logging/ILoggingService.cs b/src/Build/BackEnd/Components/Logging/ILoggingService.cs index d5ceccb6dfc..0906d1eaae4 100644 --- a/src/Build/BackEnd/Components/Logging/ILoggingService.cs +++ b/src/Build/BackEnd/Components/Logging/ILoggingService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/BackEnd/Components/Logging/LoggingContext.cs b/src/Build/BackEnd/Components/Logging/LoggingContext.cs index c8018767633..3f7a58fdd83 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingContext.cs @@ -1,3 +1,6 @@ +// 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.Diagnostics; using Microsoft.Build.Exceptions; @@ -275,7 +278,7 @@ internal void LogFatalBuildError(Exception exception, BuildEventFileInfo file) /// /// Path to response file internal void LogIncludeFile(string filePath) - { + { ErrorUtilities.VerifyThrow(IsValid, "must be valid"); _loggingService.LogIncludeFile(BuildEventContext, filePath); } diff --git a/src/Build/BackEnd/Components/Logging/LoggingService.cs b/src/Build/BackEnd/Components/Logging/LoggingService.cs index b10bd378e32..1998da2733d 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingService.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -932,14 +932,12 @@ public bool RegisterLogger(ILogger logger) Assembly engineAssembly = typeof(LoggingService).GetTypeInfo().Assembly; string loggerClassName = "Microsoft.Build.BackEnd.Logging.CentralForwardingLogger"; string loggerAssemblyName = engineAssembly.GetName().FullName; - LoggerDescription centralForwardingLoggerDescription = new LoggerDescription - ( + LoggerDescription centralForwardingLoggerDescription = new LoggerDescription( loggerClassName, loggerAssemblyName, null /*Not needed as we are loading from current assembly*/, string.Empty /*No parameters needed as we are forwarding all events*/, - LoggerVerbosity.Diagnostic /*Not used, but the spirit of the logger is to forward everything so this is the most appropriate verbosity */ - ); + LoggerVerbosity.Diagnostic); /*Not used, but the spirit of the logger is to forward everything so this is the most appropriate verbosity */ // Registering a distributed logger will initialize the logger, and create and initialize the forwarding logger. // In addition it will register the logging description so that it can be instantiated on a node. @@ -1151,8 +1149,7 @@ public void LogBuildEvent(BuildEventArgs buildEvent) (warningEvent != null) || (errorEvent != null) || (buildEvent is CustomBuildEventArgs) - || (buildEvent is CriticalBuildMessageEventArgs) - ) + || (buildEvent is CriticalBuildMessageEventArgs)) { ProcessLoggingEvent(buildEvent); } diff --git a/src/Build/BackEnd/Components/Logging/LoggingServiceFactory.cs b/src/Build/BackEnd/Components/Logging/LoggingServiceFactory.cs index d75e7a12a6a..c034b47ce8e 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingServiceFactory.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingServiceFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs b/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs index e9c1cde6045..33c747f9eb0 100644 --- a/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs +++ b/src/Build/BackEnd/Components/Logging/LoggingServiceLogMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -72,15 +72,13 @@ public void LogCommentFromText(BuildEventContext buildEventContext, MessageImpor ErrorUtilities.VerifyThrow(buildEventContext != null, "buildEventContext was null"); ErrorUtilities.VerifyThrow(message != null, "message was null"); - BuildMessageEventArgs buildEvent = new BuildMessageEventArgs - ( + BuildMessageEventArgs buildEvent = new BuildMessageEventArgs( message, helpKeyword: null, senderName: "MSBuild", importance, DateTime.UtcNow, - messageArgs - ); + messageArgs); buildEvent.BuildEventContext = buildEventContext; ProcessLoggingEvent(buildEvent); } @@ -150,8 +148,7 @@ public void LogErrorFromText(BuildEventContext buildEventContext, string subcate } BuildErrorEventArgs buildEvent = - new BuildErrorEventArgs - ( + new BuildErrorEventArgs( subcategory, errorCode, file.File, @@ -161,8 +158,7 @@ public void LogErrorFromText(BuildEventContext buildEventContext, string subcate file.EndColumn, message, helpKeyword, - "MSBuild" - ); + "MSBuild"); buildEvent.BuildEventContext = buildEventContext; if (buildEvent.ProjectFile == null && buildEventContext.ProjectContextId != BuildEventContext.InvalidProjectContextId) @@ -193,8 +189,7 @@ public void LogInvalidProjectFileError(BuildEventContext buildEventContext, Inva if (!invalidProjectFileException.HasBeenLogged) { BuildErrorEventArgs buildEvent = - new BuildErrorEventArgs - ( + new BuildErrorEventArgs( invalidProjectFileException.ErrorSubcategory, invalidProjectFileException.ErrorCode, invalidProjectFileException.ProjectFile, @@ -204,8 +199,7 @@ public void LogInvalidProjectFileError(BuildEventContext buildEventContext, Inva invalidProjectFileException.EndColumnNumber, invalidProjectFileException.BaseMessage, invalidProjectFileException.HelpKeyword, - "MSBuild" - ); + "MSBuild"); buildEvent.BuildEventContext = buildEventContext; if (buildEvent.ProjectFile == null && buildEventContext.ProjectContextId != BuildEventContext.InvalidProjectContextId) { @@ -346,8 +340,7 @@ public void LogWarningFromText(BuildEventContext buildEventContext, string subca subcategory = AssemblyResources.GetString(subcategoryResourceName); } - BuildWarningEventArgs buildEvent = new BuildWarningEventArgs - ( + BuildWarningEventArgs buildEvent = new BuildWarningEventArgs( subcategory, warningCode, file.File, @@ -357,8 +350,7 @@ public void LogWarningFromText(BuildEventContext buildEventContext, string subca file.EndColumn, message, helpKeyword, - "MSBuild" - ); + "MSBuild"); buildEvent.BuildEventContext = buildEventContext; if (buildEvent.ProjectFile == null && buildEventContext.ProjectContextId != BuildEventContext.InvalidProjectContextId) @@ -568,8 +560,7 @@ public BuildEventContext LogProjectStarted( // See https://github.com/dotnet/msbuild/issues/6341 for details IDictionary globalProperties = buildRequestConfiguration.GlobalProperties.ToDictionary(); - var buildEvent = new ProjectStartedEventArgs - ( + var buildEvent = new ProjectStartedEventArgs( configurationId, message: null, helpKeyword: null, @@ -579,8 +570,7 @@ public BuildEventContext LogProjectStarted( items, parentBuildEventContext, globalProperties, - buildRequestConfiguration.ToolsVersion - ); + buildRequestConfiguration.ToolsVersion); buildEvent.BuildEventContext = projectBuildEventContext; ProcessLoggingEvent(buildEvent); @@ -599,13 +589,11 @@ public void LogProjectFinished(BuildEventContext projectBuildEventContext, strin { ErrorUtilities.VerifyThrow(projectBuildEventContext != null, "projectBuildEventContext"); - ProjectFinishedEventArgs buildEvent = new ProjectFinishedEventArgs - ( + ProjectFinishedEventArgs buildEvent = new ProjectFinishedEventArgs( message: null, helpKeyword: null, projectFile, - success - ); + success); buildEvent.BuildEventContext = projectBuildEventContext; ProcessLoggingEvent(buildEvent); @@ -630,20 +618,17 @@ public void LogProjectFinished(BuildEventContext projectBuildEventContext, strin public BuildEventContext LogTargetStarted(BuildEventContext projectBuildEventContext, string targetName, string projectFile, string projectFileOfTargetElement, string parentTargetName, TargetBuiltReason buildReason) { ErrorUtilities.VerifyThrow(projectBuildEventContext != null, "projectBuildEventContext is null"); - BuildEventContext targetBuildEventContext = new BuildEventContext - ( + BuildEventContext targetBuildEventContext = new BuildEventContext( projectBuildEventContext.SubmissionId, projectBuildEventContext.NodeId, projectBuildEventContext.ProjectInstanceId, projectBuildEventContext.ProjectContextId, NextTargetId, - BuildEventContext.InvalidTaskId - ); + BuildEventContext.InvalidTaskId); if (!OnlyLogCriticalEvents) { - TargetStartedEventArgs buildEvent = new TargetStartedEventArgs - ( + TargetStartedEventArgs buildEvent = new TargetStartedEventArgs( message: null, helpKeyword: null, targetName, @@ -651,8 +636,7 @@ public BuildEventContext LogTargetStarted(BuildEventContext projectBuildEventCon projectFileOfTargetElement, parentTargetName, buildReason, - DateTime.UtcNow - ); + DateTime.UtcNow); buildEvent.BuildEventContext = targetBuildEventContext; ProcessLoggingEvent(buildEvent); } @@ -676,16 +660,14 @@ public void LogTargetFinished(BuildEventContext targetBuildEventContext, string { ErrorUtilities.VerifyThrow(targetBuildEventContext != null, "targetBuildEventContext is null"); - TargetFinishedEventArgs buildEvent = new TargetFinishedEventArgs - ( + TargetFinishedEventArgs buildEvent = new TargetFinishedEventArgs( message: null, helpKeyword: null, targetName, projectFile, projectFileOfTargetElement, success, - targetOutputs - ); + targetOutputs); buildEvent.BuildEventContext = targetBuildEventContext; ProcessLoggingEvent(buildEvent); @@ -705,14 +687,12 @@ public void LogTaskStarted(BuildEventContext taskBuildEventContext, string taskN ErrorUtilities.VerifyThrow(taskBuildEventContext != null, "targetBuildEventContext is null"); if (!OnlyLogCriticalEvents) { - TaskStartedEventArgs buildEvent = new TaskStartedEventArgs - ( + TaskStartedEventArgs buildEvent = new TaskStartedEventArgs( message: null, helpKeyword: null, projectFile, projectFileOfTaskNode, - taskName - ); + taskName); buildEvent.BuildEventContext = taskBuildEventContext; ProcessLoggingEvent(buildEvent); } @@ -732,26 +712,22 @@ public void LogTaskStarted(BuildEventContext taskBuildEventContext, string taskN public BuildEventContext LogTaskStarted2(BuildEventContext targetBuildEventContext, string taskName, string projectFile, string projectFileOfTaskNode, int line, int column) { ErrorUtilities.VerifyThrow(targetBuildEventContext != null, "targetBuildEventContext is null"); - BuildEventContext taskBuildEventContext = new BuildEventContext - ( + BuildEventContext taskBuildEventContext = new BuildEventContext( targetBuildEventContext.SubmissionId, targetBuildEventContext.NodeId, targetBuildEventContext.ProjectInstanceId, targetBuildEventContext.ProjectContextId, targetBuildEventContext.TargetId, - NextTaskId - ); + NextTaskId); if (!OnlyLogCriticalEvents) { - TaskStartedEventArgs buildEvent = new TaskStartedEventArgs - ( + TaskStartedEventArgs buildEvent = new TaskStartedEventArgs( message: null, helpKeyword: null, projectFile, projectFileOfTaskNode, - taskName - ); + taskName); buildEvent.BuildEventContext = taskBuildEventContext; buildEvent.LineNumber = line; buildEvent.ColumnNumber = column; @@ -776,15 +752,13 @@ public void LogTaskFinished(BuildEventContext taskBuildEventContext, string task { ErrorUtilities.VerifyThrow(taskBuildEventContext != null, "taskBuildEventContext is null"); - TaskFinishedEventArgs buildEvent = new TaskFinishedEventArgs - ( + TaskFinishedEventArgs buildEvent = new TaskFinishedEventArgs( message: null, helpKeyword: null, projectFile, projectFileOfTaskNode, taskName, - success - ); + success); buildEvent.BuildEventContext = taskBuildEventContext; ProcessLoggingEvent(buildEvent); } diff --git a/src/Build/BackEnd/Components/Logging/NodeLoggingContext.cs b/src/Build/BackEnd/Components/Logging/NodeLoggingContext.cs index 019090a8efd..d3b442b7dea 100644 --- a/src/Build/BackEnd/Components/Logging/NodeLoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/NodeLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Execution; diff --git a/src/Build/BackEnd/Components/Logging/ProjectLoggingContext.cs b/src/Build/BackEnd/Components/Logging/ProjectLoggingContext.cs index 2a9a83b0135..1058ee7f8b1 100644 --- a/src/Build/BackEnd/Components/Logging/ProjectLoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/ProjectLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; @@ -41,8 +41,7 @@ internal ProjectLoggingContext(NodeLoggingContext nodeLoggingContext, BuildReque requestEntry.RequestConfiguration.Project.ItemsToBuildWith, requestEntry.Request.ParentBuildEventContext, requestEntry.RequestConfiguration.Project.EvaluationId, - requestEntry.Request.ProjectContextId - ) + requestEntry.Request.ProjectContextId) { } @@ -67,8 +66,7 @@ internal ProjectLoggingContext( projectItems: null, request.ParentBuildEventContext, evaluationId, - request.ProjectContextId - ) + request.ProjectContextId) { } @@ -137,8 +135,7 @@ private ProjectLoggingContext( properties = projectPropertiesToSerialize.Select((ProjectPropertyInstance property) => new DictionaryEntry(property.Name, property.EvaluatedValue)); } - this.BuildEventContext = LoggingService.LogProjectStarted - ( + this.BuildEventContext = LoggingService.LogProjectStarted( nodeLoggingContext.BuildEventContext, submissionId, configurationId, @@ -148,8 +145,7 @@ private ProjectLoggingContext( properties, items, evaluationId, - projectContextId - ); + projectContextId); // No need to log a redundant message in the common case if (toolsVersion != "Current") diff --git a/src/Build/BackEnd/Components/Logging/TargetLoggingContext.cs b/src/Build/BackEnd/Components/Logging/TargetLoggingContext.cs index 8e434303492..8b2b9694b85 100644 --- a/src/Build/BackEnd/Components/Logging/TargetLoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/TargetLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Logging/TaskLoggingContext.cs b/src/Build/BackEnd/Components/Logging/TaskLoggingContext.cs index 5b8955d74b0..576827e292f 100644 --- a/src/Build/BackEnd/Components/Logging/TaskLoggingContext.cs +++ b/src/Build/BackEnd/Components/Logging/TaskLoggingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -66,15 +66,13 @@ internal TaskLoggingContext(TargetLoggingContext targetLoggingContext, string pr } } - this.BuildEventContext = LoggingService.LogTaskStarted2 - ( + this.BuildEventContext = LoggingService.LogTaskStarted2( targetLoggingContext.BuildEventContext, _taskName, projectFullPath, task.Location.File, task.Location.Line, - task.Location.Column - ); + task.Location.Column); this.IsValid = true; } @@ -127,14 +125,12 @@ internal void LogTaskBatchFinished(string projectFullPath, bool success) { ErrorUtilities.VerifyThrow(this.IsValid, "invalid"); - LoggingService.LogTaskFinished - ( + LoggingService.LogTaskFinished( BuildEventContext, _taskName, projectFullPath, _task.Location.File, - success - ); + success); this.IsValid = false; } diff --git a/src/Build/BackEnd/Components/ProjectCache/CacheContext.cs b/src/Build/BackEnd/Components/ProjectCache/CacheContext.cs index eaa9d5e05ce..256102d0d86 100644 --- a/src/Build/BackEnd/Components/ProjectCache/CacheContext.cs +++ b/src/Build/BackEnd/Components/ProjectCache/CacheContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.FileSystem; diff --git a/src/Build/BackEnd/Components/ProjectCache/CacheResult.cs b/src/Build/BackEnd/Components/ProjectCache/CacheResult.cs index 48a847b60ce..35ea1c27fca 100644 --- a/src/Build/BackEnd/Components/ProjectCache/CacheResult.cs +++ b/src/Build/BackEnd/Components/ProjectCache/CacheResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/ProjectCache/PluginLoggerBase.cs b/src/Build/BackEnd/Components/ProjectCache/PluginLoggerBase.cs index a9a13d0dc6e..a6115a12e86 100644 --- a/src/Build/BackEnd/Components/ProjectCache/PluginLoggerBase.cs +++ b/src/Build/BackEnd/Components/ProjectCache/PluginLoggerBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/ProjectCache/PluginTargetResult.cs b/src/Build/BackEnd/Components/ProjectCache/PluginTargetResult.cs index 7e1801e783a..50b15018ced 100644 --- a/src/Build/BackEnd/Components/ProjectCache/PluginTargetResult.cs +++ b/src/Build/BackEnd/Components/ProjectCache/PluginTargetResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Execution; diff --git a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptor.cs b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptor.cs index c5751c5875e..52507f3c0ed 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptor.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptor.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptorEqualityComparer.cs b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptorEqualityComparer.cs index 9f51cf9e10a..4406f78498c 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptorEqualityComparer.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheDescriptorEqualityComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheException.cs b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheException.cs index 1ae508340be..3b1a9bb3dca 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheException.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; @@ -23,8 +23,7 @@ private ProjectCacheException( string message, Exception innerException, bool hasBeenLoggedByProjectCache, - string errorCode - ) + string errorCode) : base(message, innerException) { ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(message), "Need error message."); @@ -46,12 +45,10 @@ string errorCode /// The error code string. public string ErrorCode { get; } - internal static void ThrowAsUnhandledException - ( + internal static void ThrowAsUnhandledException( Exception innerException, string messageResourceName, - params string[] messageArgs - ) + params string[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need error message."); @@ -60,11 +57,9 @@ params string[] messageArgs throw new ProjectCacheException(message, innerException, hasBeenLoggedByProjectCache: false, errorCode); } - internal static void ThrowForErrorLoggedInsideTheProjectCache - ( + internal static void ThrowForErrorLoggedInsideTheProjectCache( string messageResourceName, - params string[] messageArgs - ) + params string[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need error message."); @@ -73,11 +68,9 @@ params string[] messageArgs throw new ProjectCacheException(message: message, innerException: null, hasBeenLoggedByProjectCache: true, errorCode: errorCode); } - internal static void ThrowForMSBuildIssueWithTheProjectCache - ( + internal static void ThrowForMSBuildIssueWithTheProjectCache( string messageResourceName, - params string[] messageArgs - ) + params string[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need error message."); diff --git a/src/Build/BackEnd/Components/ProjectCache/ProjectCachePluginBase.cs b/src/Build/BackEnd/Components/ProjectCache/ProjectCachePluginBase.cs index 79d10b72864..2bf479c6055 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProjectCachePluginBase.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProjectCachePluginBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Threading; using System.Threading.Tasks; diff --git a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs index 957300c06ac..cf228ca379a 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProjectCacheService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -234,7 +234,7 @@ private static ProjectCachePluginBase GetPluginInstanceFromType(Type pluginType) { try { - return (ProjectCachePluginBase) Activator.CreateInstance(pluginType)!; + return (ProjectCachePluginBase)Activator.CreateInstance(pluginType)!; } catch (TargetInvocationException e) when (e.InnerException != null) { @@ -268,7 +268,7 @@ Assembly LoadAssembly(string resolverPath) IEnumerable GetTypes(Assembly assembly) { return assembly.ExportedTypes - .Select(type => new {type, info = type.GetTypeInfo()}) + .Select(type => new { type, info = type.GetTypeInfo() }) .Where( t => t.info.IsClass && t.info.IsPublic && @@ -374,8 +374,7 @@ void EvaluateProjectIfNecessary(BuildSubmission submission, BuildRequestConfigur _buildManager, submission.BuildRequestData.Flags, submission.SubmissionId, - Scheduler.InProcNodeId - ); + Scheduler.InProcNodeId); // If we're taking the time to evaluate, avoid having other nodes to repeat the same evaluation. // Based on the assumption that ProjectInstance serialization is faster than evaluating from scratch. @@ -542,8 +541,7 @@ private IReadOnlyCollection GetGraphEntryPoints(BuildReq static IReadOnlyCollection GenerateGraphEntryPointsFromSolutionConfigurationXml( string solutionConfigurationXml, string definingProjectPath, - Dictionary templateGlobalProperties - ) + Dictionary templateGlobalProperties) { // TODO: fix code clone for parsing CurrentSolutionConfiguration xml: https://github.com/dotnet/msbuild/issues/6751 var doc = new XmlDocument(); diff --git a/src/Build/BackEnd/Components/ProjectCache/ProxyTargets.cs b/src/Build/BackEnd/Components/ProjectCache/ProxyTargets.cs index 2379042fe5f..970dfdd3332 100644 --- a/src/Build/BackEnd/Components/ProjectCache/ProxyTargets.cs +++ b/src/Build/BackEnd/Components/ProjectCache/ProxyTargets.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -46,7 +46,7 @@ void ITranslatable.Translate(ITranslator translator) internal static ProxyTargets FactoryForDeserialization(ITranslator translator) { var instance = new ProxyTargets(); - ((ITranslatable) instance).Translate(translator); + ((ITranslatable)instance).Translate(translator); return instance; } diff --git a/src/Build/BackEnd/Components/RequestBuilder/BatchingEngine.cs b/src/Build/BackEnd/Components/RequestBuilder/BatchingEngine.cs index 363e9eaebc7..a985b059b81 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/BatchingEngine.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/BatchingEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -78,12 +78,10 @@ internal static class BatchingEngine /// buckets of items to pass to the object in each batch. /// /// List containing ItemBucket objects, each one representing an execution batch. - internal static List PrepareBatchingBuckets - ( + internal static List PrepareBatchingBuckets( List batchableObjectParameters, Lookup lookup, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { return PrepareBatchingBuckets(batchableObjectParameters, lookup, null, elementLocation); } @@ -98,13 +96,11 @@ ElementLocation elementLocation /// Any item type that can be considered an implicit input to this batchable object. /// This is useful for items inside targets, where the item name is plainly an item type that's an "input" to the object. /// List containing ItemBucket objects, each one representing an execution batch. - internal static List PrepareBatchingBuckets - ( + internal static List PrepareBatchingBuckets( List batchableObjectParameters, Lookup lookup, string implicitBatchableItemType, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { if (batchableObjectParameters == null) { @@ -199,14 +195,12 @@ ElementLocation elementLocation /// the entire list of items will be returned in the Value. Otherwise, the Value will be empty, indicating only the /// qualified item set (in the Key) should be batched. /// - private static Dictionary> GetItemListsToBeBatched - ( + private static Dictionary> GetItemListsToBeBatched( Dictionary consumedMetadataReferences, // Key is [string] potentially qualified metadata name // Value is [struct MetadataReference] HashSet consumedItemReferenceNames, Lookup lookup, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { // The keys in this hashtable are the names of the items that we will batch on. // The values are always String.Empty (not used). @@ -295,13 +289,11 @@ ElementLocation elementLocation /// to the comparison operations, which dominate the time spent in this method. /// /// List containing ItemBucket objects (can be empty), each one representing an execution batch. - private static List BucketConsumedItems - ( + private static List BucketConsumedItems( Lookup lookup, Dictionary> itemListsToBeBatched, Dictionary consumedMetadataReferences, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { ErrorUtilities.VerifyThrow(itemListsToBeBatched.Count > 0, "Need item types consumed by the batchable object."); ErrorUtilities.VerifyThrow(consumedMetadataReferences.Count > 0, "Need item metadata consumed by the batchable object."); @@ -379,12 +371,10 @@ ElementLocation elementLocation /// %(x) is expanded using the key "x", and %(z.x) is expanded using the key "z.x". /// /// the metadata values - private static Dictionary GetItemMetadataValues - ( + private static Dictionary GetItemMetadataValues( ProjectItemInstance item, Dictionary consumedMetadataReferences, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { var itemMetadataValues = new Dictionary(consumedMetadataReferences.Count, MSBuildNameIgnoreCaseComparer.Default); @@ -396,8 +386,7 @@ ElementLocation elementLocation if ( (metadataItemName != null) && - (!String.Equals(item.ItemType, metadataItemName, StringComparison.OrdinalIgnoreCase)) - ) + (!String.Equals(item.ItemType, metadataItemName, StringComparison.OrdinalIgnoreCase))) { itemMetadataValues[metadataQualifiedName] = String.Empty; } diff --git a/src/Build/BackEnd/Components/RequestBuilder/FullTracking.cs b/src/Build/BackEnd/Components/RequestBuilder/FullTracking.cs index 4ebc567c45d..5978f5ff450 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/FullTracking.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/FullTracking.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER diff --git a/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilder.cs index 503da08ff64..691e8c6efdc 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Execution; using NodeLoggingContext = Microsoft.Build.BackEnd.Logging.NodeLoggingContext; diff --git a/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilderCallback.cs b/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilderCallback.cs index 8f9b3188292..9c8542a8888 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilderCallback.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IRequestBuilderCallback.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Execution; using Microsoft.Build.Collections; diff --git a/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilder.cs index 5b88ab5db9e..51bbb39a2d9 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Threading; using System.Threading.Tasks; diff --git a/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilderCallback.cs b/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilderCallback.cs index 5d114eb00fd..946b66ddf91 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilderCallback.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/ITargetBuilderCallback.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using ElementLocation = Microsoft.Build.Construction.ElementLocation; using Microsoft.Build.Execution; diff --git a/src/Build/BackEnd/Components/RequestBuilder/ITaskBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/ITaskBuilder.cs index 8507f540064..b274bd8b11c 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/ITaskBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/ITaskBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Threading; diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs index 9fb80539f26..4406501a860 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/CallTarget.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/CallTarget.cs index 676a9d98c24..6e6c793ecc2 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/CallTarget.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/CallTarget.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/IntrinsicTaskFactory.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/IntrinsicTaskFactory.cs index 7d73eb5ae7c..166552fd23e 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/IntrinsicTaskFactory.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/IntrinsicTaskFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupIntrinsicTask.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupIntrinsicTask.cs index 446ef6e4c85..28607329499 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupIntrinsicTask.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupIntrinsicTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -63,8 +63,7 @@ internal override void ExecuteTask(Lookup lookup) // "Execute" each bucket foreach (ItemBucket bucket in buckets) { - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( child.Condition, ParserOptions.AllowAll, bucket.Expander, @@ -171,8 +170,7 @@ private void ExecuteAdd(ProjectItemGroupTaskItemInstance child, ItemBucket bucke // Third, expand the metadata. foreach (ProjectItemGroupTaskMetadataInstance metadataInstance in child.Metadata) { - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( metadataInstance.Condition, ParserOptions.AllowAll, bucket.Expander, @@ -201,8 +199,7 @@ private void ExecuteAdd(ProjectItemGroupTaskItemInstance child, ItemBucket bucke bucket.Expander.Metadata = originalMetadataTable; // Determine if we should NOT add duplicate entries - bool keepDuplicates = ConditionEvaluator.EvaluateCondition - ( + bool keepDuplicates = ConditionEvaluator.EvaluateCondition( child.KeepDuplicates, ParserOptions.AllowAll, bucket.Expander, @@ -311,8 +308,7 @@ private void ExecuteModify(ProjectItemGroupTaskItemInstance child, ItemBucket bu foreach (ProjectItemGroupTaskMetadataInstance metadataInstance in child.Metadata) { - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( metadataInstance.Condition, ParserOptions.AllowAll, bucket.Expander, @@ -369,14 +365,12 @@ private void GetBatchableValuesFromBuildItemGroupChild(List parameterVal /// been refactored. /// /// A list of items. - private List ExpandItemIntoItems - ( + private List ExpandItemIntoItems( ProjectItemGroupTaskItemInstance originalItem, Expander expander, ISet keepMetadata, ISet removeMetadata, - LoggingContext loggingContext = null - ) + LoggingContext loggingContext = null) { // todo this is duplicated logic with the item computation logic from evaluation (in LazyIncludeOperation.SelectItems) ProjectErrorUtilities.VerifyThrowInvalidProject(!(keepMetadata != null && removeMetadata != null), originalItem.KeepMetadataLocation, "KeepAndRemoveMetadataMutuallyExclusive"); @@ -525,14 +519,12 @@ private List ExpandItemIntoItems /// The expander to use /// Context for logging /// A list of matching items - private List FindItemsMatchingSpecification - ( + private List FindItemsMatchingSpecification( ICollection items, string specification, ElementLocation specificationLocation, Expander expander, - LoggingContext loggingContext = null - ) + LoggingContext loggingContext = null) { if (items.Count == 0 || specification.Length == 0) { diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupLoggingHelper.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupLoggingHelper.cs index 4f67ed79862..ccb65841cbb 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupLoggingHelper.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/ItemGroupLoggingHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs index a4c0de12aca..4ddc0ffb430 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/MSBuild.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -366,8 +366,7 @@ public async Task ExecuteInternal() _targetOutputs, UnloadProjectsOnCompletion, ToolsVersion, - SkipNonexistentTargets - ); + SkipNonexistentTargets); if (!executeResult) { @@ -421,10 +420,12 @@ private async Task BuildProjectsInParallel(Dictionary prop var projectToBuildInParallel = projectsToBuildList.ToArray(); // Make the call to build the projects - if (projectToBuildInParallel.Length <= 0) return success; + if (projectToBuildInParallel.Length <= 0) + { + return success; + } - bool executeResult = await ExecuteTargets - ( + bool executeResult = await ExecuteTargets( projectToBuildInParallel, propertiesTable, undefinePropertiesArray, @@ -436,8 +437,7 @@ private async Task BuildProjectsInParallel(Dictionary prop _targetOutputs, UnloadProjectsOnCompletion, ToolsVersion, - SkipNonexistentTargets - ); + SkipNonexistentTargets); if (!executeResult) { @@ -490,11 +490,9 @@ private void ExpandAllTargetsAndProperties() } } - internal static List CreateTargetLists - ( + internal static List CreateTargetLists( string[] targets, - bool runEachTargetSeparately - ) + bool runEachTargetSeparately) { // This is a list of string[]. That is, each element in the list is a string[]. Each // string[] represents a set of target names to build. Depending on the value @@ -561,14 +559,12 @@ internal static async Task ExecuteTargets( // parse the string containing the properties if (!String.IsNullOrEmpty(projects[i].GetMetadata(ItemMetadataNames.PropertiesMetadataName))) { - if (!PropertyParser.GetTableWithEscaping - ( + if (!PropertyParser.GetTableWithEscaping( log, ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.OverridingProperties", projectNames[i]), ItemMetadataNames.PropertiesMetadataName, projects[i].GetMetadata(ItemMetadataNames.PropertiesMetadataName).Split(MSBuildConstants.SemicolonChar, StringSplitOptions.RemoveEmptyEntries), - out Dictionary preProjectPropertiesTable) - ) + out Dictionary preProjectPropertiesTable)) { return false; } @@ -607,14 +603,12 @@ internal static async Task ExecuteTargets( // parse the string containing the properties if (!String.IsNullOrEmpty(projects[i].GetMetadata(ItemMetadataNames.AdditionalPropertiesMetadataName))) { - if (!PropertyParser.GetTableWithEscaping - ( + if (!PropertyParser.GetTableWithEscaping( log, ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.AdditionalProperties", projectNames[i]), ItemMetadataNames.AdditionalPropertiesMetadataName, projects[i].GetMetadata(ItemMetadataNames.AdditionalPropertiesMetadataName).Split(MSBuildConstants.SemicolonChar, StringSplitOptions.RemoveEmptyEntries), - out Dictionary additionalProjectPropertiesTable) - ) + out Dictionary additionalProjectPropertiesTable)) { return false; } diff --git a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/PropertyGroupIntrinsicTask.cs b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/PropertyGroupIntrinsicTask.cs index cc58134235c..419ff97e0bd 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/PropertyGroupIntrinsicTask.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/IntrinsicTasks/PropertyGroupIntrinsicTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Evaluation; @@ -57,8 +57,7 @@ internal override void ExecuteTask(Lookup lookup) // "Execute" each bucket foreach (ItemBucket bucket in buckets) { - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( property.Condition, ParserOptions.AllowAll, bucket.Expander, @@ -73,13 +72,11 @@ internal override void ExecuteTask(Lookup lookup) { // Check for a reserved name now, so it fails right here instead of later when the property eventually reaches // the outer scope. - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( !ReservedPropertyNames.IsReservedProperty(property.Name), property.Location, "CannotModifyReservedProperty", - property.Name - ); + property.Name); string evaluatedValue = bucket.Expander.ExpandIntoStringLeaveEscaped(property.Value, ExpanderOptions.ExpandAll, property.Location); diff --git a/src/Build/BackEnd/Components/RequestBuilder/ItemBucket.cs b/src/Build/BackEnd/Components/RequestBuilder/ItemBucket.cs index c15cee3f250..7f230112204 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/ItemBucket.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/ItemBucket.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -71,13 +71,11 @@ private ItemBucket() /// Hashtable of item metadata values: null indicates no batching is occurring /// The to use for the items in the bucket. /// A sequence number indication what order the buckets were created in. - internal ItemBucket - ( + internal ItemBucket( ICollection itemNames, Dictionary metadata, Lookup lookup, - int bucketSequenceNumber - ) + int bucketSequenceNumber) { ErrorUtilities.VerifyThrow(lookup != null, "Need lookup."); diff --git a/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs b/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs index 3aefd150c03..69fe0121518 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/Lookup.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -551,7 +551,9 @@ public ICollection GetItems(string itemType) itemsCount += allAdds?.Count ?? 0; // Add all the additions itemsCount -= allRemoves?.Count ?? 0; // Remove the removals if (itemsCount < 0) + { itemsCount = 0; + } // We have adds and/or removes and/or modifies to incorporate. // We can't modify the group, because that might diff --git a/src/Build/BackEnd/Components/RequestBuilder/RequestBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/RequestBuilder.cs index 7a1f6cc9c4f..607e0f576e4 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/RequestBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/RequestBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Collections; @@ -1125,20 +1125,17 @@ private async Task BuildProject() _componentHost, RequestEntry.Request.BuildRequestDataFlags, RequestEntry.Request.SubmissionId, - _nodeLoggingContext.BuildEventContext.NodeId - ); + _nodeLoggingContext.BuildEventContext.NodeId); } } catch { // make sure that any errors thrown by a child project are logged in the context of their parent project: create a temporary projectLoggingContext - _projectLoggingContext = new ProjectLoggingContext - ( + _projectLoggingContext = new ProjectLoggingContext( _nodeLoggingContext, _requestEntry.Request, _requestEntry.RequestConfiguration.ProjectFullPath, - _requestEntry.RequestConfiguration.ToolsVersion - ); + _requestEntry.RequestConfiguration.ToolsVersion); throw; } diff --git a/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs index 87604dfba2e..9bc4f3de097 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TargetBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; using Microsoft.Build.Eventing; @@ -406,21 +406,18 @@ private async Task ProcessTargetStack(ITaskBuilder taskBuilder) ( !_cancellationToken.IsCancellationRequested && !stopProcessingStack && - _targetsToBuild.Any() - ) + _targetsToBuild.Any()) { TargetEntry currentTargetEntry = _targetsToBuild.Peek(); switch (currentTargetEntry.State) { case TargetEntryState.Dependencies: // Ensure we are dealing with a target which actually exists. - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( _requestEntry.RequestConfiguration.Project.Targets.ContainsKey(currentTargetEntry.Name), currentTargetEntry.ReferenceLocation, "TargetDoesNotExist", - currentTargetEntry.Name - ); + currentTargetEntry.Name); // If we already have results for this target which were not skipped, we can ignore it. In // addition, we can also ignore its before and after targets -- if this target has already run, diff --git a/src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs b/src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs index e1479768ff2..79f3c4cd0f7 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -343,8 +343,7 @@ internal List GetDependencies(ProjectLoggingContext project // If condition is false (based on propertyBag), set this target's state to // "Skipped" since we won't actually build it. - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( _target.Condition, ParserOptions.AllowPropertiesAndItemLists, _expander, @@ -598,8 +597,7 @@ internal async Task ExecuteTarget(ITaskBuilder taskBuilder, BuildRequestEntry re if (!String.IsNullOrEmpty(targetReturns)) { // Determine if we should keep duplicates. - bool keepDupes = ConditionEvaluator.EvaluateCondition - ( + bool keepDupes = ConditionEvaluator.EvaluateCondition( _target.KeepDuplicateOutputs, ParserOptions.AllowPropertiesAndItemLists, _expander, @@ -678,8 +676,7 @@ internal List GetErrorTargets(ProjectLoggingContext project foreach (ProjectOnErrorInstance errorTargetInstance in _target.OnErrorChildren) { - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( errorTargetInstance.Condition, ParserOptions.AllowPropertiesAndItemLists, _expander, @@ -911,13 +908,11 @@ private void GetTargetInstance() { _requestEntry.RequestConfiguration.Project.Targets.TryGetValue(_targetSpecification.TargetName, out _target); - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( _target != null, _targetSpecification.ReferenceLocation ?? _requestEntry.RequestConfiguration.Project.ProjectFileLocation, "TargetDoesNotExist", - _targetSpecification.TargetName - ); + _targetSpecification.TargetName); } } } diff --git a/src/Build/BackEnd/Components/RequestBuilder/TargetSpecification.cs b/src/Build/BackEnd/Components/RequestBuilder/TargetSpecification.cs index cc55c5c90d3..9f0e9097a14 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TargetSpecification.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TargetSpecification.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using ElementLocation = Microsoft.Build.Construction.ElementLocation; using Microsoft.Build.Shared; @@ -55,7 +55,7 @@ void ITranslatable.Translate(ITranslator translator) internal static TargetSpecification FactoryForDeserialization(ITranslator translator) { var instance = new TargetSpecification(); - ((ITranslatable) instance).Translate(translator); + ((ITranslatable)instance).Translate(translator); return instance; } diff --git a/src/Build/BackEnd/Components/RequestBuilder/TargetUpToDateChecker.cs b/src/Build/BackEnd/Components/RequestBuilder/TargetUpToDateChecker.cs index e9b35b6b330..65f1f4cbb51 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TargetUpToDateChecker.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TargetUpToDateChecker.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -128,12 +128,10 @@ private string TargetOutputSpecification /// DependencyAnalysisResult.IncrementalBuild, if only some target outputs are out-of-date; /// DependencyAnalysisResult.FullBuild, if target is out-of-date /// - internal DependencyAnalysisResult PerformDependencyAnalysis - ( + internal DependencyAnalysisResult PerformDependencyAnalysis( ItemBucket bucket, out ItemDictionary changedTargetInputs, - out ItemDictionary upToDateTargetInputs - ) + out ItemDictionary upToDateTargetInputs) { // Clear any old dependency analysis logging details _dependencyAnalysisDetail.Clear(); @@ -380,16 +378,14 @@ private void LogUniqueInputsAndOutputs() /// /// /// - private void ParseTargetInputOutputSpecifications - ( + private void ParseTargetInputOutputSpecifications( ItemBucket bucket, out ItemVectorPartitionCollection itemVectorsInTargetInputs, out ItemVectorPartitionCollection itemVectorTransformsInTargetInputs, out Dictionary discreteItemsInTargetInputs, out ItemVectorPartitionCollection itemVectorsInTargetOutputs, out Dictionary discreteItemsInTargetOutputs, - out List targetOutputItemSpecs - ) + out List targetOutputItemSpecs) { // break down the input/output specifications along the standard separator, after expanding all embedded properties // and item metadata @@ -496,14 +492,12 @@ private DependencyAnalysisResult PerformDependencyAnalysisIfNoOutputs() /// /// /// Indication of how to build the target. - private DependencyAnalysisResult PerformDependencyAnalysisIfDiscreteInputs - ( + private DependencyAnalysisResult PerformDependencyAnalysisIfDiscreteInputs( ItemVectorPartitionCollection itemVectorsInTargetInputs, ItemVectorPartitionCollection itemVectorTransformsInTargetInputs, Dictionary discreteItemsInTargetInputs, List itemVectorsReferencedOnlyInTargetInputs, - List targetOutputItemSpecs - ) + List targetOutputItemSpecs) { DependencyAnalysisResult result = DependencyAnalysisResult.SkipUpToDate; @@ -571,14 +565,12 @@ List targetOutputItemSpecs /// The inputs which are "changed" and require a build /// The inpurt which are "up to date" and do not require a build /// Indication of how to build the target. - private DependencyAnalysisResult PerformDependencyAnalysisIfCorrelatedInputsOutputs - ( + private DependencyAnalysisResult PerformDependencyAnalysisIfCorrelatedInputsOutputs( ItemVectorPartitionCollection itemVectorsInTargetInputs, ItemVectorPartitionCollection itemVectorsInTargetOutputs, List itemVectorsReferencedInBothTargetInputsAndOutputs, out ItemDictionary changedTargetInputs, - out ItemDictionary upToDateTargetInputs - ) + out ItemDictionary upToDateTargetInputs) { DependencyAnalysisResult result = DependencyAnalysisResult.SkipUpToDate; @@ -722,13 +714,11 @@ out ItemDictionary upToDateTargetInputs /// /// /// Indication of how to build the target. - private DependencyAnalysisResult PerformDependencyAnalysisIfDiscreteOutputs - ( + private DependencyAnalysisResult PerformDependencyAnalysisIfDiscreteOutputs( ItemVectorPartitionCollection itemVectorsInTargetInputs, ItemVectorPartitionCollection itemVectorTransformsInTargetInputs, Dictionary discreteItemsInTargetInputs, - List targetOutputItemSpecs - ) + List targetOutputItemSpecs) { List targetInputItemSpecs = GetItemSpecsFromItemVectors(itemVectorsInTargetInputs); targetInputItemSpecs.AddRange(GetItemSpecsFromItemVectors(itemVectorTransformsInTargetInputs)); @@ -780,15 +770,13 @@ List targetOutputItemSpecs /// Collection for transforms if they should be collected separately, else null /// /// - private void SeparateItemVectorsFromDiscreteItems - ( + private void SeparateItemVectorsFromDiscreteItems( SemiColonTokenizer items, ItemBucket bucket, out ItemVectorPartitionCollection itemVectors, ItemVectorPartitionCollection itemVectorTransforms, out Dictionary discreteItems, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { itemVectors = new ItemVectorPartitionCollection(MSBuildNameIgnoreCaseComparer.Default); discreteItems = new Dictionary(MSBuildNameIgnoreCaseComparer.Default); diff --git a/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs b/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs index 8679287cd8a..2fbe1580634 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TaskBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -371,8 +371,7 @@ private async Task ExecuteBucket(TaskHost taskHost, ItemBucket b ParserOptions parserOptions = (_taskNode == null) ? ParserOptions.AllowPropertiesAndItemLists : ParserOptions.AllowAll; WorkUnitResult taskResult = new WorkUnitResult(WorkUnitResultCode.Failed, WorkUnitActionCode.Stop, null); - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( _targetChildInstance.Condition, parserOptions, bucket.Expander, @@ -494,11 +493,9 @@ private async Task ExecuteBucket(TaskHost taskHost, ItemBucket b { ErrorUtilities.VerifyThrow(howToExecuteTask == TaskExecutionMode.InferOutputsOnly, "should be inferring"); - ErrorUtilities.VerifyThrow - ( + ErrorUtilities.VerifyThrow( GatherTaskOutputs(null, howToExecuteTask, bucket), - "The method GatherTaskOutputs() should never fail when inferring task outputs." - ); + "The method GatherTaskOutputs() should never fail when inferring task outputs."); if (lookupHash != null) { @@ -629,14 +626,12 @@ private void LogSkippedTask(ItemBucket bucket, TaskExecutionMode howToExecuteTas // Whilst we are within the processing of the task, we haven't actually started executing it, so // our skip task message needs to be in the context of the target. However any errors should be reported // at the point where the task appears in the project. - _targetLoggingContext.LogComment - ( + _targetLoggingContext.LogComment( MessageImportance.Low, "TaskSkippedFalseCondition", _taskNode.Name, _targetChildInstance.Condition, - expanded - ); + expanded); } } } @@ -647,8 +642,7 @@ private void LogSkippedTask(ItemBucket bucket, TaskExecutionMode howToExecuteTas /// private void ExecuteIntrinsicTask(ItemBucket bucket) { - IntrinsicTask task = IntrinsicTask.InstantiateTask - ( + IntrinsicTask task = IntrinsicTask.InstantiateTask( _targetChildInstance, _targetLoggingContext, _buildRequestEntry.RequestConfiguration.Project, @@ -929,8 +923,7 @@ private async Task ExecuteInstantiatedTask(ITaskExecutionHost ta // from failures in the task. if (_continueOnError == ContinueOnError.WarnAndContinue) { - taskLoggingContext.LogTaskWarningFromException - ( + taskLoggingContext.LogTaskWarningFromException( exceptionToLog, new BuildEventFileInfo(_targetChildInstance.Location), _taskNode.Name); @@ -940,8 +933,7 @@ private async Task ExecuteInstantiatedTask(ITaskExecutionHost ta } else { - taskLoggingContext.LogFatalTaskError - ( + taskLoggingContext.LogFatalTaskError( exceptionToLog, new BuildEventFileInfo(_targetChildInstance.Location), _taskNode.Name); @@ -1013,14 +1005,12 @@ private async Task ExecuteInstantiatedTask(ITaskExecutionHost ta settingString = bucket.Expander.ExpandIntoStringAndUnescape(_taskNode.ContinueOnError, ExpanderOptions.ExpandAll, _taskNode.ContinueOnErrorLocation); // expand embedded item vectors after expanding properties and item metadata } - taskLoggingContext.LogComment - ( + taskLoggingContext.LogComment( MessageImportance.Normal, "TaskContinuedDueToContinueOnError", "ContinueOnError", _taskNode.Name, - settingString - ); + settingString); actionCode = WorkUnitActionCode.Continue; } @@ -1089,8 +1079,7 @@ private bool GatherTaskOutputs(ITaskExecutionHost taskExecutionHost, TaskExecuti foreach (ProjectTaskInstanceChild taskOutputSpecification in _taskNode.Outputs) { // if the task's outputs are supposed to be gathered - bool condition = ConditionEvaluator.EvaluateCondition - ( + bool condition = ConditionEvaluator.EvaluateCondition( taskOutputSpecification.Condition, ParserOptions.AllowAll, bucket.Expander, @@ -1117,16 +1106,14 @@ private bool GatherTaskOutputs(ITaskExecutionHost taskExecutionHost, TaskExecuti outputTargetName = bucket.Expander.ExpandIntoStringAndUnescape(taskOutputItemInstance.ItemType, ExpanderOptions.ExpandAll, taskOutputItemInstance.ItemTypeLocation); taskParameterName = taskOutputItemInstance.TaskParameter; - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( outputTargetName.Length > 0, taskOutputItemInstance.ItemTypeLocation, "InvalidEvaluatedAttributeValue", outputTargetName, taskOutputItemInstance.ItemType, XMakeAttributes.itemName, - XMakeElements.output - ); + XMakeElements.output); } else { @@ -1137,31 +1124,27 @@ private bool GatherTaskOutputs(ITaskExecutionHost taskExecutionHost, TaskExecuti outputTargetName = bucket.Expander.ExpandIntoStringAndUnescape(taskOutputPropertyInstance.PropertyName, ExpanderOptions.ExpandAll, taskOutputPropertyInstance.PropertyNameLocation); taskParameterName = taskOutputPropertyInstance.TaskParameter; - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( outputTargetName.Length > 0, taskOutputPropertyInstance.PropertyNameLocation, "InvalidEvaluatedAttributeValue", outputTargetName, taskOutputPropertyInstance.PropertyName, XMakeAttributes.propertyName, - XMakeElements.output - ); + XMakeElements.output); } string unexpandedTaskParameterName = taskParameterName; taskParameterName = bucket.Expander.ExpandIntoStringAndUnescape(taskParameterName, ExpanderOptions.ExpandAll, taskOutputSpecification.TaskParameterLocation); - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( taskParameterName.Length > 0, taskOutputSpecification.TaskParameterLocation, "InvalidEvaluatedAttributeValue", taskParameterName, unexpandedTaskParameterName, XMakeAttributes.taskParameter, - XMakeElements.output - ); + XMakeElements.output); // if we're gathering outputs by .NET reflection if (howToExecuteTask == TaskExecutionMode.ExecuteTaskAndGatherOutputs) @@ -1196,15 +1179,13 @@ private bool GatherTaskOutputs(ITaskExecutionHost taskExecutionHost, TaskExecuti /// can be null /// can be null /// The bucket for the batch. - private void InferTaskOutputs - ( + private void InferTaskOutputs( Lookup lookup, ProjectTaskInstanceChild taskOutputSpecification, string taskParameterName, string itemName, string propertyName, - ItemBucket bucket - ) + ItemBucket bucket) { string taskParameterAttribute = _taskNode.GetParameter(taskParameterName); diff --git a/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs b/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs index 4ee0c78cae4..3e0ea3b7abf 100644 --- a/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs +++ b/src/Build/BackEnd/Components/RequestBuilder/TaskHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -258,16 +258,14 @@ internal bool IsOutOfProc public bool BuildProjectFile(string projectFileName, string[] targetNames, System.Collections.IDictionary globalProperties, System.Collections.IDictionary targetOutputs, string toolsVersion) { VerifyActiveProxy(); - return BuildProjectFilesInParallel - ( + return BuildProjectFilesInParallel( new string[] { projectFileName }, targetNames, new IDictionary[] { globalProperties }, new IDictionary[] { targetOutputs }, new string[] { toolsVersion }, true, - false - ); + false); } /// @@ -425,8 +423,7 @@ public void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e) // ContinueOnError is that a project author expects that the task might fail, // but wants to ignore the failures. This implies that we shouldn't be logging // errors either, because you should never have a successful build with errors. - BuildWarningEventArgs warningEvent = new BuildWarningEventArgs - ( + BuildWarningEventArgs warningEvent = new BuildWarningEventArgs( e.Subcategory, e.Code, e.File, @@ -436,8 +433,7 @@ public void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e) e.EndColumnNumber, e.Message, e.HelpKeyword, - e.SenderName - ); + e.SenderName); warningEvent.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(warningEvent); @@ -450,8 +446,8 @@ public void LogErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs e) e.BuildEventContext = _taskLoggingContext.BuildEventContext; _taskLoggingContext.LoggingService.LogBuildEvent(e); } - - _taskLoggingContext.HasLoggedErrors = true; + + _taskLoggingContext.HasLoggedErrors = true; } } diff --git a/src/Build/BackEnd/Components/Scheduler/IScheduler.cs b/src/Build/BackEnd/Components/Scheduler/IScheduler.cs index f0b32acb722..d66e50d62c1 100644 --- a/src/Build/BackEnd/Components/Scheduler/IScheduler.cs +++ b/src/Build/BackEnd/Components/Scheduler/IScheduler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Threading.Tasks; diff --git a/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs b/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs index a3d17131919..142b8021262 100644 --- a/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs +++ b/src/Build/BackEnd/Components/Scheduler/SchedulableRequest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Scheduler/ScheduleResponse.cs b/src/Build/BackEnd/Components/Scheduler/ScheduleResponse.cs index 8e514e01dc6..bae176a6540 100644 --- a/src/Build/BackEnd/Components/Scheduler/ScheduleResponse.cs +++ b/src/Build/BackEnd/Components/Scheduler/ScheduleResponse.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Build/BackEnd/Components/Scheduler/ScheduleTimeRecord.cs b/src/Build/BackEnd/Components/Scheduler/ScheduleTimeRecord.cs index b274c9fdd3b..81b3ed3798d 100644 --- a/src/Build/BackEnd/Components/Scheduler/ScheduleTimeRecord.cs +++ b/src/Build/BackEnd/Components/Scheduler/ScheduleTimeRecord.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/Scheduler/Scheduler.cs b/src/Build/BackEnd/Components/Scheduler/Scheduler.cs index de7bd580e4a..2dea902ef71 100644 --- a/src/Build/BackEnd/Components/Scheduler/Scheduler.cs +++ b/src/Build/BackEnd/Components/Scheduler/Scheduler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -618,7 +618,7 @@ public void InitializeComponent(IBuildComponentHost host) _componentHost = host; _resultsCache = (IResultsCache)_componentHost.GetComponent(BuildComponentType.ResultsCache); _configCache = (IConfigCache)_componentHost.GetComponent(BuildComponentType.ConfigCache); - _inprocNodeContext = new NodeLoggingContext(_componentHost.LoggingService, InProcNodeId, true); + _inprocNodeContext = new NodeLoggingContext(_componentHost.LoggingService, InProcNodeId, true); } /// @@ -634,7 +634,7 @@ public void ShutdownComponent() /// /// Factory for component construction. /// - static internal IBuildComponent CreateComponent(BuildComponentType componentType) + internal static IBuildComponent CreateComponent(BuildComponentType componentType) { ErrorUtilities.VerifyThrow(componentType == BuildComponentType.Scheduler, "Cannot create components of type {0}", componentType); return new Scheduler(); @@ -668,8 +668,7 @@ private void ScheduleUnassignedRequests(List responses) // See if we are done. We are done if there are no unassigned requests and no requests assigned to nodes. if (_schedulingData.UnscheduledRequestsCount == 0 && _schedulingData.ReadyRequestsCount == 0 && - _schedulingData.BlockedRequestsCount == 0 - ) + _schedulingData.BlockedRequestsCount == 0) { if (_schedulingData.ExecutingRequestsCount == 0 && _schedulingData.YieldingRequestsCount == 0) { @@ -1631,7 +1630,7 @@ private void HandleRequestBlockedOnInProgressTarget(SchedulableRequest blockedRe // detect the case for https://github.com/dotnet/msbuild/issues/3047 // if we have partial results AND blocked and blocking share the same configuration AND are blocked on each other - if (blocker.PartialBuildResult !=null && + if (blocker.PartialBuildResult != null && blockingRequest.BuildRequest.ConfigurationId == blockedRequest.BuildRequest.ConfigurationId && blockingRequest.RequestsWeAreBlockedBy.Contains(blockedRequest)) { @@ -1777,8 +1776,7 @@ private void HandleRequestBlockedByNewRequests(SchedulableRequest parentRequest, requestAffinity, existingRequestAffinity, config.ProjectFullPath, - globalProperties - ))); + globalProperties))); response = GetResponseForResult(nodeForResults, request, result); responses.Add(response); continue; @@ -1964,7 +1962,7 @@ private bool CheckIfCacheMissOnReferencedProjectIsAllowedAndErrorIfNot(int nodeF emitNonErrorLogs = _ => { }; var isIsolatedBuild = _componentHost.BuildParameters.IsolateProjects; - var configCache = (IConfigCache) _componentHost.GetComponent(BuildComponentType.ConfigCache); + var configCache = (IConfigCache)_componentHost.GetComponent(BuildComponentType.ConfigCache); // do not check root requests as nothing depends on them if (!isIsolatedBuild || request.IsRootRequest || request.SkipStaticGraphIsolationConstraints) @@ -2470,8 +2468,7 @@ private void WriteRecursiveSummary(ILoggingService loggingService, BuildEventCon } } - loggingService.LogComment - ( + loggingService.LogComment( context, MessageImportance.Normal, "BuildHierarchyEntry", @@ -2481,8 +2478,7 @@ private void WriteRecursiveSummary(ILoggingService loggingService, BuildEventCon String.Format(CultureInfo.InvariantCulture, "{0:0.000}", request.GetTimeSpentInState(SchedulableRequestState.Executing).TotalSeconds), String.Format(CultureInfo.InvariantCulture, "{0:0.000}", request.GetTimeSpentInState(SchedulableRequestState.Executing).TotalSeconds + request.GetTimeSpentInState(SchedulableRequestState.Blocked).TotalSeconds + request.GetTimeSpentInState(SchedulableRequestState.Ready).TotalSeconds), _configCache[request.BuildRequest.ConfigurationId].ProjectFullPath, - String.Join(", ", request.BuildRequest.Targets) - ); + String.Join(", ", request.BuildRequest.Targets)); List childRequests = new List(_schedulingData.GetRequestsByHierarchy(request)); childRequests.Sort(delegate (SchedulableRequest left, SchedulableRequest right) diff --git a/src/Build/BackEnd/Components/Scheduler/SchedulerCircularDependencyException.cs b/src/Build/BackEnd/Components/Scheduler/SchedulerCircularDependencyException.cs index 4da80ca7d92..405d0290483 100644 --- a/src/Build/BackEnd/Components/Scheduler/SchedulerCircularDependencyException.cs +++ b/src/Build/BackEnd/Components/Scheduler/SchedulerCircularDependencyException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs b/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs index 71f82542916..ea8229ef246 100644 --- a/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs +++ b/src/Build/BackEnd/Components/Scheduler/SchedulingData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/Scheduler/SchedulingPlan.cs b/src/Build/BackEnd/Components/Scheduler/SchedulingPlan.cs index f411afbd2b2..ff41aea3c33 100644 --- a/src/Build/BackEnd/Components/Scheduler/SchedulingPlan.cs +++ b/src/Build/BackEnd/Components/Scheduler/SchedulingPlan.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Components/SdkResolution/CachingSdkResolverService.cs b/src/Build/BackEnd/Components/SdkResolution/CachingSdkResolverService.cs index 38bc4c3c23a..2e198bf29f6 100644 --- a/src/Build/BackEnd/Components/SdkResolution/CachingSdkResolverService.cs +++ b/src/Build/BackEnd/Components/SdkResolution/CachingSdkResolverService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Build/BackEnd/Components/SdkResolution/DefaultSdkResolver.cs b/src/Build/BackEnd/Components/SdkResolution/DefaultSdkResolver.cs index 0777e2ee6f3..e9239f1d124 100644 --- a/src/Build/BackEnd/Components/SdkResolution/DefaultSdkResolver.cs +++ b/src/Build/BackEnd/Components/SdkResolution/DefaultSdkResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Components/SdkResolution/HostedSdkResolverServiceBase.cs b/src/Build/BackEnd/Components/SdkResolution/HostedSdkResolverServiceBase.cs index 84da3c1f818..03806f0f311 100644 --- a/src/Build/BackEnd/Components/SdkResolution/HostedSdkResolverServiceBase.cs +++ b/src/Build/BackEnd/Components/SdkResolution/HostedSdkResolverServiceBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Construction; diff --git a/src/Build/BackEnd/Components/SdkResolution/ISdkResolverService.cs b/src/Build/BackEnd/Components/SdkResolution/ISdkResolverService.cs index 9a33b60ccbc..037279f85bd 100644 --- a/src/Build/BackEnd/Components/SdkResolution/ISdkResolverService.cs +++ b/src/Build/BackEnd/Components/SdkResolution/ISdkResolverService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Construction; diff --git a/src/Build/BackEnd/Components/SdkResolution/MainNodeSdkResolverService.cs b/src/Build/BackEnd/Components/SdkResolution/MainNodeSdkResolverService.cs index 8dc3f79b60a..1df10d45a37 100644 --- a/src/Build/BackEnd/Components/SdkResolution/MainNodeSdkResolverService.cs +++ b/src/Build/BackEnd/Components/SdkResolution/MainNodeSdkResolverService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Components.Logging; using Microsoft.Build.BackEnd.Logging; diff --git a/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverService.cs b/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverService.cs index 0b9e5ceecb8..78a3f1e42a2 100644 --- a/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverService.cs +++ b/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Collections; @@ -126,7 +126,7 @@ private SdkResult RequestSdkPathFromMainNode(int submissionId, SdkReference sdk, SendPacket(packet); // Wait for either the response or a shutdown event. Either event means this thread should return - WaitHandle.WaitAny(new WaitHandle[] {_responseReceivedEvent, ShutdownEvent}); + WaitHandle.WaitAny(new WaitHandle[] { _responseReceivedEvent, ShutdownEvent }); // Keep track of the element location of the reference _lastResponse.ElementLocation = sdkReferenceLocation; diff --git a/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverServiceFactory.cs b/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverServiceFactory.cs index 95e380153f1..6c739e55493 100644 --- a/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverServiceFactory.cs +++ b/src/Build/BackEnd/Components/SdkResolution/OutOfProcNodeSdkResolverServiceFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkLogger.cs b/src/Build/BackEnd/Components/SdkResolution/SdkLogger.cs index a08ba96dc43..7002af1ea6f 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkLogger.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverContext.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverContext.cs index 7c846f8decb..9f873deae43 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverContext.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverException.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverException.cs index 505f3d40275..bd8af074fb0 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverException.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverException.cs @@ -1,6 +1,5 @@ // 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 Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs index 0ccdd796da6..4bb7ed9bfb1 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverLoader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -28,16 +28,16 @@ internal class SdkResolverLoader // as an SDK resolver built for .NET Framework probably won't work on .NET Core, and vice versa. private readonly string AdditionalResolversFolder = Environment.GetEnvironmentVariable( #if NETFRAMEWORK - "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NETFRAMEWORK" + "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NETFRAMEWORK") #elif NET - "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NET" + "MSBUILDADDITIONALSDKRESOLVERSFOLDER_NET") #endif - ) ?? Environment.GetEnvironmentVariable("MSBUILDADDITIONALSDKRESOLVERSFOLDER"); + ?? Environment.GetEnvironmentVariable("MSBUILDADDITIONALSDKRESOLVERSFOLDER"); internal virtual IList GetDefaultResolvers(LoggingContext loggingContext, ElementLocation location) { var resolvers = !String.Equals(IncludeDefaultResolver, "false", StringComparison.OrdinalIgnoreCase) ? - new List {new DefaultSdkResolver()} + new List { new DefaultSdkResolver() } : new List(); return resolvers; @@ -47,7 +47,7 @@ internal virtual IList LoadAllResolvers(LoggingContext loggingConte ElementLocation location) { var resolvers = !String.Equals(IncludeDefaultResolver, "false", StringComparison.OrdinalIgnoreCase) ? - new List {new DefaultSdkResolver()} + new List { new DefaultSdkResolver() } : new List(); var potentialResolvers = FindPotentialSdkResolvers( @@ -171,7 +171,10 @@ public int GetHashCode(DirectoryInfo value) private bool TryAddAssemblyManifestFromXml(string pathToManifest, string manifestFolder, List manifestsList, ElementLocation location) { - if (!string.IsNullOrEmpty(pathToManifest) && !FileUtilities.FileExistsNoThrow(pathToManifest)) return false; + if (!string.IsNullOrEmpty(pathToManifest) && !FileUtilities.FileExistsNoThrow(pathToManifest)) + { + return false; + } SdkResolverManifest manifest = null; try @@ -213,7 +216,10 @@ private bool TryAddAssemblyManifestFromXml(string pathToManifest, string manifes private bool TryAddAssemblyManifestFromDll(string assemblyPath, List manifestsList) { - if (string.IsNullOrEmpty(assemblyPath) || !FileUtilities.FileExistsNoThrow(assemblyPath)) return false; + if (string.IsNullOrEmpty(assemblyPath) || !FileUtilities.FileExistsNoThrow(assemblyPath)) + { + return false; + } manifestsList.Add(new SdkResolverManifest(DisplayName: assemblyPath, Path: assemblyPath, ResolvableSdkRegex: null)); return true; @@ -222,7 +228,7 @@ private bool TryAddAssemblyManifestFromDll(string assemblyPath, List GetResolverTypes(Assembly assembly) { return assembly.ExportedTypes - .Select(type => new {type, info = type.GetTypeInfo()}) + .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); } diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverManifest.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverManifest.cs index f8d0baf5e71..e6743f911e7 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverManifest.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverManifest.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Shared; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Shared; using System; using System.IO; using System.Text.RegularExpressions; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverRequest.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverRequest.cs index 89c54eff53a..8d17baeba38 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverRequest.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverRequest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Framework; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs index ce94320a586..275e2b6bd03 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResolverService.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Construction; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResult.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResult.cs index 9bf0dddb0a6..f95bc780ca1 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResult.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using System; diff --git a/src/Build/BackEnd/Components/SdkResolution/SdkResultFactory.cs b/src/Build/BackEnd/Components/SdkResolution/SdkResultFactory.cs index 082ee42c97a..d4341ee5f1c 100644 --- a/src/Build/BackEnd/Components/SdkResolution/SdkResultFactory.cs +++ b/src/Build/BackEnd/Components/SdkResolution/SdkResultFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using System.Collections.Generic; diff --git a/src/Build/BackEnd/Components/SdkResolution/TranslationHelpers.cs b/src/Build/BackEnd/Components/SdkResolution/TranslationHelpers.cs index 586db964fec..0e2ee6b45c8 100644 --- a/src/Build/BackEnd/Components/SdkResolution/TranslationHelpers.cs +++ b/src/Build/BackEnd/Components/SdkResolution/TranslationHelpers.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Framework; using System; using System.Collections.Generic; @@ -6,7 +9,7 @@ namespace Microsoft.Build.BackEnd.SdkResolution { - static class SdkResultTranslationHelpers + internal static class SdkResultTranslationHelpers { public static void Translate(this ITranslator t, ref SdkReference sdkReference) { diff --git a/src/Build/BackEnd/Node/ConsoleOutput.cs b/src/Build/BackEnd/Node/ConsoleOutput.cs index 2a685c594d7..ea4938d43d5 100644 --- a/src/Build/BackEnd/Node/ConsoleOutput.cs +++ b/src/Build/BackEnd/Node/ConsoleOutput.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BackEnd { diff --git a/src/Build/BackEnd/Node/INode.cs b/src/Build/BackEnd/Node/INode.cs index 1eff91490df..c0c9edf9b19 100644 --- a/src/Build/BackEnd/Node/INode.cs +++ b/src/Build/BackEnd/Node/INode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/BackEnd/Node/InProcNode.cs b/src/Build/BackEnd/Node/InProcNode.cs index 8d00119a2f5..c143daf038e 100644 --- a/src/Build/BackEnd/Node/InProcNode.cs +++ b/src/Build/BackEnd/Node/InProcNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Node/LoggingNodeConfiguration.cs b/src/Build/BackEnd/Node/LoggingNodeConfiguration.cs index ba9dfbfff31..1bae5efa98b 100644 --- a/src/Build/BackEnd/Node/LoggingNodeConfiguration.cs +++ b/src/Build/BackEnd/Node/LoggingNodeConfiguration.cs @@ -1,9 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -//----------------------------------------------------------------------- -// -// A packet which contains information needed for a node to configure itself for build. -//----------------------------------------------------------------------- +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/BackEnd/Node/NativeMethods.cs b/src/Build/BackEnd/Node/NativeMethods.cs index 66eb9b8f702..b986a5bce03 100644 --- a/src/Build/BackEnd/Node/NativeMethods.cs +++ b/src/Build/BackEnd/Node/NativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; @@ -49,8 +49,7 @@ internal static class NativeMethods /// [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CreateProcess - ( + internal static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, @@ -61,8 +60,7 @@ internal static extern bool CreateProcess IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUP_INFO lpStartupInfo, - out PROCESS_INFORMATION lpProcessInformation - ); + out PROCESS_INFORMATION lpProcessInformation); /// /// Structure that contains the startupinfo diff --git a/src/Build/BackEnd/Node/NodeConfiguration.cs b/src/Build/BackEnd/Node/NodeConfiguration.cs index 52f8dfc21db..0b678346842 100644 --- a/src/Build/BackEnd/Node/NodeConfiguration.cs +++ b/src/Build/BackEnd/Node/NodeConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_APPDOMAIN using System; @@ -53,16 +53,14 @@ internal class NodeConfiguration : INodePacket /// The forwarding loggers. /// The AppDomain setup information. /// The logging configuration for the node. - public NodeConfiguration - ( + public NodeConfiguration( int nodeId, BuildParameters buildParameters, LoggerDescription[] forwardingLoggers, #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif - LoggingNodeConfiguration loggingNodeConfiguration - ) + LoggingNodeConfiguration loggingNodeConfiguration) { _nodeId = nodeId; _buildParameters = buildParameters; @@ -137,7 +135,7 @@ public LoggingNodeConfiguration LoggingNodeConfiguration { return _loggingNodeConfiguration; } } -#region INodePacket Members + #region INodePacket Members /// /// Retrieves the packet type. @@ -149,9 +147,9 @@ public NodePacketType Type { return NodePacketType.NodeConfiguration; } } -#endregion + #endregion -#region INodePacketTranslatable Members + #region INodePacketTranslatable Members /// /// Translates the packet to/from binary form. @@ -177,7 +175,7 @@ internal static INodePacket FactoryForDeserialization(ITranslator translator) configuration.Translate(translator); return configuration; } -#endregion + #endregion /// /// We need to clone this object since it gets modified for each node which is launched. @@ -188,8 +186,7 @@ internal NodeConfiguration Clone() #if FEATURE_APPDOMAIN , _appDomainSetup #endif - , _loggingNodeConfiguration - ); + , _loggingNodeConfiguration); } } } diff --git a/src/Build/BackEnd/Node/OutOfProcNode.cs b/src/Build/BackEnd/Node/OutOfProcNode.cs index f45bb803573..266b8189db5 100644 --- a/src/Build/BackEnd/Node/OutOfProcNode.cs +++ b/src/Build/BackEnd/Node/OutOfProcNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -153,7 +153,7 @@ public OutOfProcNode() // Create a factory for the out-of-proc SDK resolver service which can pass our SendPacket delegate to be used for sending packets to the main node OutOfProcNodeSdkResolverServiceFactory sdkResolverServiceFactory = new OutOfProcNodeSdkResolverServiceFactory(SendPacket); - ((IBuildComponentHost) this).RegisterFactory(BuildComponentType.SdkResolverService, sdkResolverServiceFactory.CreateInstance); + ((IBuildComponentHost)this).RegisterFactory(BuildComponentType.SdkResolverService, sdkResolverServiceFactory.CreateInstance); _sdkResolverService = (this as IBuildComponentHost).GetComponent(BuildComponentType.SdkResolverService) as ISdkResolverService; @@ -833,7 +833,7 @@ private void HandleNodeBuildComplete(NodeBuildComplete buildComplete) } } } - + _shutdownEvent.Set(); } } diff --git a/src/Build/BackEnd/Node/OutOfProcServerNode.cs b/src/Build/BackEnd/Node/OutOfProcServerNode.cs index 18297977aaa..cc23c012e8e 100644 --- a/src/Build/BackEnd/Node/OutOfProcServerNode.cs +++ b/src/Build/BackEnd/Node/OutOfProcServerNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -111,7 +111,7 @@ public NodeEngineShutdownReason Run(out Exception? shutdownException) return NodeEngineShutdownReason.Error; } - while(true) + while (true) { NodeEngineShutdownReason shutdownReason = RunInternal(out shutdownException, handshake); if (shutdownReason != NodeEngineShutdownReason.BuildCompleteReuse) @@ -331,7 +331,7 @@ private void HandleServerNodeBuildCommandAsync(ServerNodeBuildCommand command) { HandleServerNodeBuildCommand(command); } - catch(Exception e) + catch (Exception e) { _shutdownException = e; _shutdownReason = NodeEngineShutdownReason.Error; @@ -415,7 +415,7 @@ private void HandleServerNodeBuildCommand(ServerNodeBuildCommand command) Console.SetOut(oldOut); Console.SetError(oldErr); } - + // On Windows, a process holds a handle to the current directory, // so reset it away from a user-requested folder that may get deleted. NativeMethodsShared.SetCurrentDirectory(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory); diff --git a/src/Build/BackEnd/Node/PartialBuildTelemetry.cs b/src/Build/BackEnd/Node/PartialBuildTelemetry.cs index b9960a0e752..5164ed8cb4d 100644 --- a/src/Build/BackEnd/Node/PartialBuildTelemetry.cs +++ b/src/Build/BackEnd/Node/PartialBuildTelemetry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/BackEnd/Node/ServerNamedMutex.cs b/src/Build/BackEnd/Node/ServerNamedMutex.cs index ac7244a6cc0..d109ca586c2 100644 --- a/src/Build/BackEnd/Node/ServerNamedMutex.cs +++ b/src/Build/BackEnd/Node/ServerNamedMutex.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Threading; diff --git a/src/Build/BackEnd/Node/ServerNodeBuildCancel.cs b/src/Build/BackEnd/Node/ServerNodeBuildCancel.cs index 67cd7f0df7f..37508396c35 100644 --- a/src/Build/BackEnd/Node/ServerNodeBuildCancel.cs +++ b/src/Build/BackEnd/Node/ServerNodeBuildCancel.cs @@ -1,10 +1,10 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BackEnd { internal sealed class ServerNodeBuildCancel : INodePacket - { + { public NodePacketType Type => NodePacketType.ServerNodeBuildCancel; public void Translate(ITranslator translator) diff --git a/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs b/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs index ee8bd565d25..589d3f9670b 100644 --- a/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs +++ b/src/Build/BackEnd/Node/ServerNodeBuildCommand.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Node/ServerNodeBuildResult.cs b/src/Build/BackEnd/Node/ServerNodeBuildResult.cs index 4ea012ebafd..16c10c7662c 100644 --- a/src/Build/BackEnd/Node/ServerNodeBuildResult.cs +++ b/src/Build/BackEnd/Node/ServerNodeBuildResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BackEnd { diff --git a/src/Build/BackEnd/Node/ServerNodeConsoleWrite.cs b/src/Build/BackEnd/Node/ServerNodeConsoleWrite.cs index da3f8473905..4198ce5b436 100644 --- a/src/Build/BackEnd/Node/ServerNodeConsoleWrite.cs +++ b/src/Build/BackEnd/Node/ServerNodeConsoleWrite.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BackEnd { diff --git a/src/Build/BackEnd/Shared/BuildAbortedException.cs b/src/Build/BackEnd/Shared/BuildAbortedException.cs index e86a747c6b5..ab5d34af0e4 100644 --- a/src/Build/BackEnd/Shared/BuildAbortedException.cs +++ b/src/Build/BackEnd/Shared/BuildAbortedException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Build/BackEnd/Shared/BuildRequest.cs b/src/Build/BackEnd/Shared/BuildRequest.cs index d0ffa213952..a2c3132444d 100644 --- a/src/Build/BackEnd/Shared/BuildRequest.cs +++ b/src/Build/BackEnd/Shared/BuildRequest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Build/BackEnd/Shared/BuildRequestBlocker.cs b/src/Build/BackEnd/Shared/BuildRequestBlocker.cs index a694cb56329..70716800c48 100644 --- a/src/Build/BackEnd/Shared/BuildRequestBlocker.cs +++ b/src/Build/BackEnd/Shared/BuildRequestBlocker.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.Execution; diff --git a/src/Build/BackEnd/Shared/BuildRequestConfiguration.cs b/src/Build/BackEnd/Shared/BuildRequestConfiguration.cs index b0b4f1204e3..b1616f43858 100644 --- a/src/Build/BackEnd/Shared/BuildRequestConfiguration.cs +++ b/src/Build/BackEnd/Shared/BuildRequestConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -489,8 +489,7 @@ internal void LoadProjectIntoConfiguration( private void InitializeProject(BuildParameters buildParameters, Func loadProjectFromFile) { if (_project == null || // building from file. Load project from file - _transferredProperties != null // need to overwrite particular properties, so load project from file and overwrite properties - ) + _transferredProperties != null) // need to overwrite particular properties, so load project from file and overwrite properties { Project = loadProjectFromFile.Invoke(); } diff --git a/src/Build/BackEnd/Shared/BuildRequestUnblocker.cs b/src/Build/BackEnd/Shared/BuildRequestUnblocker.cs index b3419d0e869..6617ff8b911 100644 --- a/src/Build/BackEnd/Shared/BuildRequestUnblocker.cs +++ b/src/Build/BackEnd/Shared/BuildRequestUnblocker.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.Shared; diff --git a/src/Build/BackEnd/Shared/BuildResult.cs b/src/Build/BackEnd/Shared/BuildResult.cs index 97b64d603a3..414eb216ed6 100644 --- a/src/Build/BackEnd/Shared/BuildResult.cs +++ b/src/Build/BackEnd/Shared/BuildResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Build/BackEnd/Shared/CircularDependencyException.cs b/src/Build/BackEnd/Shared/CircularDependencyException.cs index a2e1910b3ec..08cfb2a4783 100644 --- a/src/Build/BackEnd/Shared/CircularDependencyException.cs +++ b/src/Build/BackEnd/Shared/CircularDependencyException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Build/BackEnd/Shared/ConfigurationMetadata.cs b/src/Build/BackEnd/Shared/ConfigurationMetadata.cs index a58dceeaaa8..c964394f0f0 100644 --- a/src/Build/BackEnd/Shared/ConfigurationMetadata.cs +++ b/src/Build/BackEnd/Shared/ConfigurationMetadata.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Shared/IBuildResults.cs b/src/Build/BackEnd/Shared/IBuildResults.cs index 28fe90b842c..8dbd46dc8ac 100644 --- a/src/Build/BackEnd/Shared/IBuildResults.cs +++ b/src/Build/BackEnd/Shared/IBuildResults.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/Shared/ITargetResult.cs b/src/Build/BackEnd/Shared/ITargetResult.cs index 8fd59e071c7..71dcdf5a1ab 100644 --- a/src/Build/BackEnd/Shared/ITargetResult.cs +++ b/src/Build/BackEnd/Shared/ITargetResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics.CodeAnalysis; diff --git a/src/Build/BackEnd/Shared/ResourceRequest.cs b/src/Build/BackEnd/Shared/ResourceRequest.cs index 0dfe5c9d808..bcfd0ddf0e7 100644 --- a/src/Build/BackEnd/Shared/ResourceRequest.cs +++ b/src/Build/BackEnd/Shared/ResourceRequest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/BackEnd/Shared/ResourceResponse.cs b/src/Build/BackEnd/Shared/ResourceResponse.cs index a1cc63c18fc..9e001ca2dc7 100644 --- a/src/Build/BackEnd/Shared/ResourceResponse.cs +++ b/src/Build/BackEnd/Shared/ResourceResponse.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/BackEnd/Shared/TargetResult.cs b/src/Build/BackEnd/Shared/TargetResult.cs index 26d41241e41..21634fb0f4e 100644 --- a/src/Build/BackEnd/Shared/TargetResult.cs +++ b/src/Build/BackEnd/Shared/TargetResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -298,7 +298,7 @@ private void TranslateItems(ITranslator translator) // rough guess for an average number of bytes needed to store them. This doesn't have to be accurate, just // big enough to avoid unnecessary buffer reallocations in most cases. var defaultBufferCapacity = _items.Length * 128; - + using var itemsStream = new MemoryStream(defaultBufferCapacity); var itemTranslator = BinaryTranslator.GetWriteTranslator(itemsStream); diff --git a/src/Build/BackEnd/Shared/WorkUnitResult.cs b/src/Build/BackEnd/Shared/WorkUnitResult.cs index fdf1b3c909f..b2a644d054e 100644 --- a/src/Build/BackEnd/Shared/WorkUnitResult.cs +++ b/src/Build/BackEnd/Shared/WorkUnitResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/BackEnd/TaskExecutionHost/AddInParts/ITaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/AddInParts/ITaskExecutionHost.cs index b882915f83c..6d25f2f4688 100644 --- a/src/Build/BackEnd/TaskExecutionHost/AddInParts/ITaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/AddInParts/ITaskExecutionHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs index ce0b8db4ad0..389f8c6459b 100644 --- a/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs +++ b/src/Build/BackEnd/TaskExecutionHost/TaskExecutionHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -372,14 +372,12 @@ bool ITaskExecutionHost.SetTaskParameters(IDictionary requiredParameter in requiredParameters) { - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( setParameters.ContainsKey(requiredParameter.Key), _taskLocation, "RequiredPropertyNotSetError", _taskName, - requiredParameter.Key - ); + requiredParameter.Key); } } @@ -409,24 +407,20 @@ bool ITaskExecutionHost.GatherTaskOutputs(string parameterName, ElementLocation } // flag an error if we find a parameter that has no .NET property equivalent - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( parameter != null, parameterLocation, "UnexpectedTaskOutputAttribute", parameterName, - _taskName - ); + _taskName); // output parameters must have their corresponding .NET properties marked with the Output attribute - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( _taskFactoryWrapper.GetNamesOfPropertiesWithOutputAttribute.ContainsKey(parameterName), parameterLocation, "UnmarkedOutputTaskParameter", parameter.Name, - _taskName - ); + _taskName); EnsureParameterInitialized(parameter, _batchBucket.Lookup); @@ -442,27 +436,23 @@ bool ITaskExecutionHost.GatherTaskOutputs(string parameterName, ElementLocation } else { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "UnsupportedTaskParameterTypeError", parameter.PropertyType.FullName, parameter.Name, - _taskName - ); + _taskName); } } catch (InvalidOperationException e) { // handle invalid TaskItems in task outputs - _targetLoggingContext.LogError - ( + _targetLoggingContext.LogError( new BuildEventFileInfo(parameterLocation), "InvalidTaskItemsInTaskOutputs", _taskName, parameterName, - e.Message - ); + e.Message); gatheredGeneratedOutputsSuccessfully = false; } @@ -473,33 +463,28 @@ bool ITaskExecutionHost.GatherTaskOutputs(string parameterName, ElementLocation // Log the stack, so the task vendor can fix their code // Log the task line number, whatever the value of ContinueOnError; // because this will be a hard error anyway. - _targetLoggingContext.LogFatalTaskError - ( + _targetLoggingContext.LogFatalTaskError( e.InnerException, new BuildEventFileInfo(parameterLocation), _taskName); // We do not recover from a task exception while getting outputs, // so do not merely set gatheredGeneratedOutputsSuccessfully = false; here - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "FailedToRetrieveTaskOutputs", _taskName, parameterName, - e.InnerException?.Message - ); + e.InnerException?.Message); } catch (Exception e) when (!ExceptionHandling.NotExpectedReflectionException(e)) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "FailedToRetrieveTaskOutputs", _taskName, parameterName, - e.Message - ); + e.Message); } return gatheredGeneratedOutputsSuccessfully; @@ -753,15 +738,13 @@ ex is ArgumentException || // can't convert to bool ex is FormatException || // bad string representation of a type ex is OverflowException) // overflow when converting string representation of a numerical type { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "InvalidTaskParameterValueError", currentItem.ItemSpec, parameter.Name, parameterType.FullName, - _taskName - ); + _taskName); } throw; @@ -859,13 +842,11 @@ private TaskFactoryWrapper FindTaskInRegistry(IDictionary taskId if (returnClass == null) { - _targetLoggingContext.LogError - ( + _targetLoggingContext.LogError( new BuildEventFileInfo(_taskLocation), "MissingTaskError", _taskName, - _projectInstance.TaskRegistry.Toolset.ToolsPath - ); + _projectInstance.TaskRegistry.Toolset.ToolsPath); return null; } @@ -883,16 +864,14 @@ private TaskFactoryWrapper FindTaskInRegistry(IDictionary taskId taskIdentityParameters.TryGetValue(XMakeAttributes.runtime, out string taskRuntime); taskIdentityParameters.TryGetValue(XMakeAttributes.architecture, out string taskArchitecture); - _targetLoggingContext.LogError - ( + _targetLoggingContext.LogError( new BuildEventFileInfo(_taskLocation), "TaskExistsButHasMismatchedIdentityError", _taskName, usingTaskRuntime ?? XMakeAttributes.MSBuildRuntimeValues.any, usingTaskArchitecture ?? XMakeAttributes.MSBuildArchitectureValues.any, taskRuntime ?? XMakeAttributes.MSBuildRuntimeValues.any, - taskArchitecture ?? XMakeAttributes.MSBuildArchitectureValues.any - ); + taskArchitecture ?? XMakeAttributes.MSBuildArchitectureValues.any); // if we've logged this error, even though we've found something, we want to act like we didn't. return null; @@ -959,39 +938,33 @@ private ITask InstantiateTask(IDictionary taskIdentityParameters } catch (InvalidCastException e) { - _taskLoggingContext.LogError - ( + _taskLoggingContext.LogError( new BuildEventFileInfo(_taskLocation), "TaskInstantiationFailureErrorInvalidCast", _taskName, _taskFactoryWrapper.TaskFactory.FactoryName, - e.Message - ); + e.Message); } catch (TargetInvocationException e) { // Exception thrown by the called code itself // Log the stack, so the task vendor can fix their code - _taskLoggingContext.LogError - ( + _taskLoggingContext.LogError( new BuildEventFileInfo(_taskLocation), "TaskInstantiationFailureError", _taskName, _taskFactoryWrapper.TaskFactory.FactoryName, - Environment.NewLine + e.InnerException - ); + Environment.NewLine + e.InnerException); } catch (Exception e) when (!ExceptionHandling.IsCriticalException(e)) { // Reflection related exception - _taskLoggingContext.LogError - ( + _taskLoggingContext.LogError( new BuildEventFileInfo(_taskLocation), "TaskInstantiationFailureError", _taskName, _taskFactoryWrapper.TaskFactory.FactoryName, - e.Message - ); + e.Message); } return task; @@ -1000,14 +973,12 @@ private ITask InstantiateTask(IDictionary taskIdentityParameters /// /// Set the specified parameter based on its type. /// - private bool SetTaskParameter - ( + private bool SetTaskParameter( string parameterName, string parameterValue, ElementLocation parameterLocation, bool isRequired, - out bool parameterSet - ) + out bool parameterSet) { bool success = false; parameterSet = false; @@ -1057,85 +1028,71 @@ out bool parameterSet // try to set the parameter if (TaskParameterTypeVerifier.IsValidScalarInputParameter(parameterType)) { - success = InitializeTaskScalarParameter - ( + success = InitializeTaskScalarParameter( parameter, parameterType, parameterValue, parameterLocation, - out parameterSet - ); + out parameterSet); } else if (TaskParameterTypeVerifier.IsValidVectorInputParameter(parameterType)) { - success = InitializeTaskVectorParameter - ( + success = InitializeTaskVectorParameter( parameter, parameterType, parameterValue, parameterLocation, isRequired, - out parameterSet - ); + out parameterSet); } else { - _taskLoggingContext.LogError - ( + _taskLoggingContext.LogError( new BuildEventFileInfo(parameterLocation), "UnsupportedTaskParameterTypeError", parameterType.FullName, parameter.Name, - _taskName - ); + _taskName); } if (!success) { // flag an error if the parameter could not be set - _taskLoggingContext.LogError - ( + _taskLoggingContext.LogError( new BuildEventFileInfo(parameterLocation), "InvalidTaskAttributeError", parameterName, parameterValue, - _taskName - ); + _taskName); } } else { // flag an error if we find a parameter that has no .NET property equivalent - _taskLoggingContext.LogError - ( - new BuildEventFileInfo( parameterLocation ), + _taskLoggingContext.LogError( + new BuildEventFileInfo(parameterLocation), "UnexpectedTaskAttribute", parameterName, _taskName, _taskFactoryWrapper.TaskFactoryLoadedType.LoadedAssemblyName.FullName, - _taskFactoryWrapper.TaskFactoryLoadedType.Path - ); + _taskFactoryWrapper.TaskFactoryLoadedType.Path); } } catch (AmbiguousMatchException) { - _taskLoggingContext.LogError - ( + _taskLoggingContext.LogError( new BuildEventFileInfo(parameterLocation), "AmbiguousTaskParameterError", _taskName, - parameterName - ); + parameterName); } catch (ArgumentException) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "SetAccessorNotAvailableOnTaskParameter", parameterName, - _taskName - ); + _taskName); } return success; @@ -1144,14 +1101,12 @@ out parameterSet /// /// Given an instantiated task, this helper method sets the specified scalar parameter based on its type. /// - private bool InitializeTaskScalarParameter - ( + private bool InitializeTaskScalarParameter( TaskPropertyInfo parameter, Type parameterType, string parameterValue, ElementLocation parameterLocation, - out bool taskParameterSet - ) + out bool taskParameterSet) { taskParameterSet = false; @@ -1176,15 +1131,13 @@ out bool taskParameterSet // We only allow a single item to be passed into a parameter of ITaskItem. // Some of the computation (expansion) here is expensive, so don't switch to VerifyThrowInvalidProject. - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "CannotPassMultipleItemsIntoScalarParameter", _batchBucket.Expander.ExpandIntoStringAndUnescape(parameterValue, ExpanderOptions.ExpandAll, parameterLocation), parameter.Name, parameterType.FullName, - _taskName - ); + _taskName); } RecordItemForDisconnectIfNecessary(finalTaskItems[0]); @@ -1217,15 +1170,13 @@ ex is ArgumentException || // can't convert to bool ex is FormatException || // bad string representation of a type ex is OverflowException) // overflow when converting string representation of a numerical type { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameterLocation, "InvalidTaskParameterValueError", _batchBucket.Expander.ExpandIntoStringAndUnescape(parameterValue, ExpanderOptions.ExpandAll, parameterLocation), parameter.Name, parameterType.FullName, - _taskName - ); + _taskName); } throw; @@ -1274,15 +1225,13 @@ private void EnsureParameterInitialized(TaskPropertyInfo parameter, Lookup looku /// /// "xxx@(CPPFiles)xxx" converts to <error> /// - private bool InitializeTaskVectorParameter - ( + private bool InitializeTaskVectorParameter( TaskPropertyInfo parameter, Type parameterType, string parameterValue, ElementLocation parameterLocation, bool isRequired, - out bool taskParameterSet - ) + out bool taskParameterSet) { ErrorUtilities.VerifyThrow(parameterValue != null, "Didn't expect null parameterValue in InitializeTaskVectorParameter"); @@ -1339,11 +1288,9 @@ private bool InternalSetTaskParameter(TaskPropertyInfo parameter, IList paramete /// /// Given an instantiated task, this helper method sets the specified parameter /// - private bool InternalSetTaskParameter - ( + private bool InternalSetTaskParameter( TaskPropertyInfo parameter, - object parameterValue - ) + object parameterValue) { bool success = false; @@ -1374,8 +1321,7 @@ object parameterValue // Exception thrown by the called code itself // Log the stack, so the task vendor can fix their code - _taskLoggingContext.LogFatalTaskError - ( + _taskLoggingContext.LogFatalTaskError( e.InnerException, new BuildEventFileInfo(_taskLocation), _taskName); @@ -1384,8 +1330,7 @@ object parameterValue // InternalLoggerException is an arbitrary logger exception. catch (Exception e) when (e is not LoggerException && e is not InternalLoggerException && !ExceptionHandling.NotExpectedReflectionException(e)) { - _taskLoggingContext.LogFatalTaskError - ( + _taskLoggingContext.LogFatalTaskError( e, new BuildEventFileInfo(_taskLocation), _taskName); diff --git a/src/Build/Collections/ArrayDictionary.cs b/src/Build/Collections/ArrayDictionary.cs index 8eea6dead68..d0f1d5e0a32 100644 --- a/src/Build/Collections/ArrayDictionary.cs +++ b/src/Build/Collections/ArrayDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Collections/ConcurrentQueueExtensions.cs b/src/Build/Collections/ConcurrentQueueExtensions.cs index 6160e4605a9..f855230c204 100644 --- a/src/Build/Collections/ConcurrentQueueExtensions.cs +++ b/src/Build/Collections/ConcurrentQueueExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; using Microsoft.Build.Shared; diff --git a/src/Build/Collections/ConcurrentStackExtensions.cs b/src/Build/Collections/ConcurrentStackExtensions.cs index e4a552676d9..aea11c91672 100644 --- a/src/Build/Collections/ConcurrentStackExtensions.cs +++ b/src/Build/Collections/ConcurrentStackExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; using Microsoft.Build.Shared; diff --git a/src/Build/Collections/ConvertingEnumerable.cs b/src/Build/Collections/ConvertingEnumerable.cs index d7d8980bb20..b4b3e1d7058 100644 --- a/src/Build/Collections/ConvertingEnumerable.cs +++ b/src/Build/Collections/ConvertingEnumerable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Collections/CopyOnReadEnumerable.cs b/src/Build/Collections/CopyOnReadEnumerable.cs index 437d417df30..06956f83617 100644 --- a/src/Build/Collections/CopyOnReadEnumerable.cs +++ b/src/Build/Collections/CopyOnReadEnumerable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Collections/CopyOnWritePropertyDictionary.cs b/src/Build/Collections/CopyOnWritePropertyDictionary.cs index 5454b4ae4dc..83b46097d82 100644 --- a/src/Build/Collections/CopyOnWritePropertyDictionary.cs +++ b/src/Build/Collections/CopyOnWritePropertyDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Collections/HashTableUtility.cs b/src/Build/Collections/HashTableUtility.cs index 74dfee37ef8..bddb1b3bfff 100644 --- a/src/Build/Collections/HashTableUtility.cs +++ b/src/Build/Collections/HashTableUtility.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Collections/IImmutable.cs b/src/Build/Collections/IImmutable.cs index 012cfaf1948..95681f94032 100644 --- a/src/Build/Collections/IImmutable.cs +++ b/src/Build/Collections/IImmutable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Collections/IValued.cs b/src/Build/Collections/IValued.cs index 966d5497d31..5e6548bb204 100644 --- a/src/Build/Collections/IValued.cs +++ b/src/Build/Collections/IValued.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Collections/ItemDictionary.cs b/src/Build/Collections/ItemDictionary.cs index 6f4bd864bda..d2543da7f5b 100644 --- a/src/Build/Collections/ItemDictionary.cs +++ b/src/Build/Collections/ItemDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Collections/LookasideStringInterner.cs b/src/Build/Collections/LookasideStringInterner.cs index c0f5e1d3142..c4850971372 100644 --- a/src/Build/Collections/LookasideStringInterner.cs +++ b/src/Build/Collections/LookasideStringInterner.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Collections/MultiDictionary.cs b/src/Build/Collections/MultiDictionary.cs index 1f34c6009bb..7a1492aa855 100644 --- a/src/Build/Collections/MultiDictionary.cs +++ b/src/Build/Collections/MultiDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -245,7 +245,7 @@ public void Add(TT value) } else if (_entry is TT) { - var list = new List { (TT) _entry, value }; + var list = new List { (TT)_entry, value }; _entry = list; } else diff --git a/src/Build/Collections/PropertyDictionary.cs b/src/Build/Collections/PropertyDictionary.cs index 649880df456..71ddf8eb4b4 100644 --- a/src/Build/Collections/PropertyDictionary.cs +++ b/src/Build/Collections/PropertyDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Collections/ReadOnlyConvertingDictionary.cs b/src/Build/Collections/ReadOnlyConvertingDictionary.cs index d14ed476c1c..cc0a4fdac8b 100644 --- a/src/Build/Collections/ReadOnlyConvertingDictionary.cs +++ b/src/Build/Collections/ReadOnlyConvertingDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Collections/RetrievableEntryHashSet/BitHelper.cs b/src/Build/Collections/RetrievableEntryHashSet/BitHelper.cs index 8099a4d75ac..89412677013 100644 --- a/src/Build/Collections/RetrievableEntryHashSet/BitHelper.cs +++ b/src/Build/Collections/RetrievableEntryHashSet/BitHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Security; diff --git a/src/Build/Collections/RetrievableEntryHashSet/HashHelpers.cs b/src/Build/Collections/RetrievableEntryHashSet/HashHelpers.cs index 735c08b2a37..49baf191c18 100644 --- a/src/Build/Collections/RetrievableEntryHashSet/HashHelpers.cs +++ b/src/Build/Collections/RetrievableEntryHashSet/HashHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -92,7 +92,7 @@ internal static int ExpandPrime(int oldSize) // Allow the hashtables to grow to maximum possible size (~2G elements) before encoutering capacity overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast - if ((uint) newSize > MaxPrimeArrayLength) + if ((uint)newSize > MaxPrimeArrayLength) { return MaxPrimeArrayLength; } diff --git a/src/Build/Collections/RetrievableEntryHashSet/HashSet.cs b/src/Build/Collections/RetrievableEntryHashSet/HashSet.cs index b581d671b9d..c480f2cc80e 100644 --- a/src/Build/Collections/RetrievableEntryHashSet/HashSet.cs +++ b/src/Build/Collections/RetrievableEntryHashSet/HashSet.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -120,7 +120,7 @@ internal class RetrievableEntryHashSet : ICollection, // temporary variable needed during deserialization private SerializationInfo _siInfo; -#region Constructors + #region Constructors public RetrievableEntryHashSet(IEqualityComparer comparer) { @@ -203,7 +203,7 @@ protected RetrievableEntryHashSet(SerializationInfo info, StreamingContext conte _siInfo = info; } -#endregion + #endregion // Convenience to minimise change to callers used to dictionaries public ICollection Keys @@ -229,7 +229,7 @@ public ICollection Values get { return this; } } -#region ICollection methods + #region ICollection methods // Convenience to minimise change to callers used to dictionaries internal T this[string name] @@ -342,14 +342,20 @@ public T Get(string key) public T Get(string key, int index, int length) { if (length < 0) + { throw new ArgumentOutOfRangeException(nameof(length)); + } if (index < 0 || index > (key == null ? 0 : key.Length) - length) + { throw new ArgumentOutOfRangeException(nameof(index)); + } if (_constrainedComparer == null) + { throw new InvalidOperationException("Cannot do a constrained lookup on this collection."); - + } + return GetCore(key, index, length); } @@ -480,9 +486,9 @@ internal void MakeReadOnly() _readOnly = true; } -#endregion + #endregion -#region IEnumerable methods + #region IEnumerable methods public Enumerator GetEnumerator() { @@ -507,9 +513,9 @@ IEnumerator IEnumerable.GetEnumerator() return new Enumerator(this); } -#endregion + #endregion -#region ISerializable methods + #region ISerializable methods // [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] [SecurityCritical] @@ -532,9 +538,9 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte } } -#endregion + #endregion -#region IDeserializationCallback methods + #region IDeserializationCallback methods public virtual void OnDeserialization(Object sender) { @@ -579,9 +585,9 @@ public virtual void OnDeserialization(Object sender) _siInfo = null; } -#endregion + #endregion -#region HashSet methods + #region HashSet methods /// /// Add item to this HashSet. @@ -595,7 +601,9 @@ public void Add(T item) void IDictionary.Add(string key, T item) { if (key != item.Key) + { throw new InvalidOperationException(); + } AddEvenIfPresent(item); } @@ -988,7 +996,9 @@ public bool SetEquals(IEnumerable other) { void ICollection>.CopyTo(KeyValuePair[] array, int index) { if (index < 0 || Count > array.Length - index) + { throw new ArgumentException("index"); + } int i = index; foreach (var entry in this) @@ -1151,9 +1161,9 @@ public static IEqualityComparer> CreateSetComparer() #endif #endif -#endregion + #endregion -#region Helper methods + #region Helper methods /// /// Initializes buckets and slots arrays. Uses suggested capacity by finding next prime @@ -1698,12 +1708,14 @@ private static bool AreEqualityComparersEqual(RetrievableEntryHashSet set1, R return set1.Comparer.Equals(set2.Comparer); } #endif - + private int InternalGetHashCode(string item, int index, int length) { // No need to check for null 'item' as we own all comparers if (_constrainedComparer != null) + { return _constrainedComparer.GetHashCode(item, index, length) & Lower31BitMask; + } return InternalGetHashCode(item); } @@ -1722,7 +1734,7 @@ private int InternalGetHashCode(string item) return _comparer.GetHashCode(item) & Lower31BitMask; } -#endregion + #endregion // used for set checking operations (using enumerables) that rely on counting internal struct ElementCount diff --git a/src/Build/Collections/RetrievableEntryHashSet/HashSetDebugView.cs b/src/Build/Collections/RetrievableEntryHashSet/HashSetDebugView.cs index b4cd58a485b..369164778dd 100644 --- a/src/Build/Collections/RetrievableEntryHashSet/HashSetDebugView.cs +++ b/src/Build/Collections/RetrievableEntryHashSet/HashSetDebugView.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Collections/WeakValueDictionary.cs b/src/Build/Collections/WeakValueDictionary.cs index 5b2f1e62e56..c4c04d802eb 100644 --- a/src/Build/Collections/WeakValueDictionary.cs +++ b/src/Build/Collections/WeakValueDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Construction/ImplicitImportLocation.cs b/src/Build/Construction/ImplicitImportLocation.cs index c6bf445e366..78027b2dcc6 100644 --- a/src/Build/Construction/ImplicitImportLocation.cs +++ b/src/Build/Construction/ImplicitImportLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Construction/ProjectChooseElement.cs b/src/Build/Construction/ProjectChooseElement.cs index e89bfe3aa96..5914776c11f 100644 --- a/src/Build/Construction/ProjectChooseElement.cs +++ b/src/Build/Construction/ProjectChooseElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Xml; diff --git a/src/Build/Construction/ProjectElement.cs b/src/Build/Construction/ProjectElement.cs index 0b8916d5f2b..bc4edf2addd 100644 --- a/src/Build/Construction/ProjectElement.cs +++ b/src/Build/Construction/ProjectElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -90,7 +90,7 @@ internal virtual bool ExpressedAsAttribute _expressedAsAttribute = value; Parent?.AddToXml(this); MarkDirty("Set express as attribute: {0}", value.ToString()); - } + } } } @@ -210,7 +210,7 @@ public IEnumerable AllParents public ProjectElement PreviousSibling { [DebuggerStepThrough] - get => Link != null? Link.PreviousSibling : _previousSibling; + get => Link != null ? Link.PreviousSibling : _previousSibling; [DebuggerStepThrough] internal set => _previousSibling = value; } @@ -291,10 +291,10 @@ internal set /// In the case of an unsaved edit, the location only /// contains the path to the file that the element originates from. /// - public ElementLocation Location => Link != null ? Link.Location : XmlElement.Location; + public ElementLocation Location => Link != null ? Link.Location : XmlElement.Location; /// - public string ElementName => Link != null? Link.ElementName : XmlElement.Name; + public string ElementName => Link != null ? Link.ElementName : XmlElement.Name; // Using ILinkedXml to share single field for either Linked (external) and local (XML backed) nodes. private ILinkedXml _xmlSource; @@ -331,7 +331,7 @@ internal XmlDocumentWithLocation XmlDocument [DebuggerStepThrough] get { - return (XmlDocumentWithLocation) XmlElement?.OwnerDocument; + return (XmlDocumentWithLocation)XmlElement?.OwnerDocument; } } @@ -544,7 +544,11 @@ internal string GetAttributeValue(string attributeName, bool nullIfNotExists = f internal string GetAttributeValue(string attributeName, ref string cache) { - if (cache != null) return cache; + if (cache != null) + { + return cache; + } + var value = GetAttributeValue(attributeName, false); if (Link == null) { diff --git a/src/Build/Construction/ProjectElementContainer.cs b/src/Build/Construction/ProjectElementContainer.cs index 3de6bee0c32..5f0c2d45ada 100644 --- a/src/Build/Construction/ProjectElementContainer.cs +++ b/src/Build/Construction/ProjectElementContainer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -72,10 +72,8 @@ public ICollection Children [DebuggerStepThrough] get { - return new Collections.ReadOnlyCollection - ( - new ProjectElementSiblingEnumerable(FirstChild) - ); + return new Collections.ReadOnlyCollection( + new ProjectElementSiblingEnumerable(FirstChild)); } } @@ -87,10 +85,8 @@ public ICollection ChildrenReversed [DebuggerStepThrough] get { - return new Collections.ReadOnlyCollection - ( - new ProjectElementSiblingEnumerable(LastChild, false /* reverse */) - ); + return new Collections.ReadOnlyCollection( + new ProjectElementSiblingEnumerable(LastChild, false /* reverse */)); } } diff --git a/src/Build/Construction/ProjectExtensionsElement.cs b/src/Build/Construction/ProjectExtensionsElement.cs index ae667ee6675..9f0058fcbda 100644 --- a/src/Build/Construction/ProjectExtensionsElement.cs +++ b/src/Build/Construction/ProjectExtensionsElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Build/Construction/ProjectImportElement.cs b/src/Build/Construction/ProjectImportElement.cs index 36ba393d7be..a38385ca9b8 100644 --- a/src/Build/Construction/ProjectImportElement.cs +++ b/src/Build/Construction/ProjectImportElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.Framework; @@ -144,7 +144,7 @@ public string MinimumVersion internal static ProjectImportElement CreateDisconnected(string project, ProjectRootElement containingProject) { XmlElementWithLocation element = containingProject.CreateElement(XMakeElements.import); - return new ProjectImportElement(element, containingProject) {Project = project}; + return new ProjectImportElement(element, containingProject) { Project = project }; } /// diff --git a/src/Build/Construction/ProjectImportGroupElement.cs b/src/Build/Construction/ProjectImportGroupElement.cs index 62337399feb..d6c6979e996 100644 --- a/src/Build/Construction/ProjectImportGroupElement.cs +++ b/src/Build/Construction/ProjectImportGroupElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Build/Construction/ProjectItemDefinitionElement.cs b/src/Build/Construction/ProjectItemDefinitionElement.cs index 1d9eacd9309..be712263f49 100644 --- a/src/Build/Construction/ProjectItemDefinitionElement.cs +++ b/src/Build/Construction/ProjectItemDefinitionElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Xml; diff --git a/src/Build/Construction/ProjectItemDefinitionGroupElement.cs b/src/Build/Construction/ProjectItemDefinitionGroupElement.cs index f55a6a0b1f5..f8f4d2aad05 100644 --- a/src/Build/Construction/ProjectItemDefinitionGroupElement.cs +++ b/src/Build/Construction/ProjectItemDefinitionGroupElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Xml; diff --git a/src/Build/Construction/ProjectItemElement.cs b/src/Build/Construction/ProjectItemElement.cs index 3bf4639787c..2d9a2e0adfd 100644 --- a/src/Build/Construction/ProjectItemElement.cs +++ b/src/Build/Construction/ProjectItemElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -104,7 +104,7 @@ public string Include set { - ErrorUtilities.VerifyThrowInvalidOperation(String.IsNullOrEmpty(value) || (Remove.Length == 0 && Update.Length == 0) , "OM_OneOfAttributeButNotMore", ElementName, XMakeAttributes.include, XMakeAttributes.remove, XMakeAttributes.update); + ErrorUtilities.VerifyThrowInvalidOperation(String.IsNullOrEmpty(value) || (Remove.Length == 0 && Update.Length == 0), "OM_OneOfAttributeButNotMore", ElementName, XMakeAttributes.include, XMakeAttributes.remove, XMakeAttributes.update); SetOrRemoveAttribute(XMakeAttributes.include, value, ref _include, "Set item Include {0}", value); _includeHasWildcards = null; } diff --git a/src/Build/Construction/ProjectItemGroupElement.cs b/src/Build/Construction/ProjectItemGroupElement.cs index 58418960335..b637161a355 100644 --- a/src/Build/Construction/ProjectItemGroupElement.cs +++ b/src/Build/Construction/ProjectItemGroupElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Construction/ProjectMetadataElement.cs b/src/Build/Construction/ProjectMetadataElement.cs index 2acd6b83299..a8ba5cd5c10 100644 --- a/src/Build/Construction/ProjectMetadataElement.cs +++ b/src/Build/Construction/ProjectMetadataElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.ObjectModelRemoting; @@ -67,7 +67,7 @@ public string Name { if (value) { - ValidateValidMetadataAsAttributeName(Name, Parent?.ElementName ?? "null" , Parent?.Location); + ValidateValidMetadataAsAttributeName(Name, Parent?.ElementName ?? "null", Parent?.Location); } base.ExpressedAsAttribute = value; } diff --git a/src/Build/Construction/ProjectOnErrorElement.cs b/src/Build/Construction/ProjectOnErrorElement.cs index a1564143564..cad2f56b7e8 100644 --- a/src/Build/Construction/ProjectOnErrorElement.cs +++ b/src/Build/Construction/ProjectOnErrorElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.ObjectModelRemoting; @@ -76,7 +76,7 @@ internal static ProjectOnErrorElement CreateDisconnected(string executeTargets, XmlElementWithLocation element = containingProject.CreateElement(XMakeElements.onError); var onError = new ProjectOnErrorElement(element, containingProject) { ExecuteTargetsAttribute = executeTargets }; - + return onError; } diff --git a/src/Build/Construction/ProjectOtherwiseElement.cs b/src/Build/Construction/ProjectOtherwiseElement.cs index f41d862b1fe..f3002cc8a8c 100644 --- a/src/Build/Construction/ProjectOtherwiseElement.cs +++ b/src/Build/Construction/ProjectOtherwiseElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Build/Construction/ProjectOutputElement.cs b/src/Build/Construction/ProjectOutputElement.cs index 92c23bd1274..d1b22301339 100644 --- a/src/Build/Construction/ProjectOutputElement.cs +++ b/src/Build/Construction/ProjectOutputElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -138,14 +138,12 @@ public string PropertyName /// internal static ProjectOutputElement CreateDisconnected(string taskParameter, string itemType, string propertyName, ProjectRootElement containingProject) { - ErrorUtilities.VerifyThrowArgument - ( + ErrorUtilities.VerifyThrowArgument( String.IsNullOrEmpty(itemType) ^ String.IsNullOrEmpty(propertyName), "OM_EitherAttributeButNotBoth", XMakeElements.output, XMakeAttributes.propertyName, - XMakeAttributes.itemName - ); + XMakeAttributes.itemName); XmlElementWithLocation element = containingProject.CreateElement(XMakeElements.output); diff --git a/src/Build/Construction/ProjectPropertyElement.cs b/src/Build/Construction/ProjectPropertyElement.cs index 1cac5075d00..eca5645ab18 100644 --- a/src/Build/Construction/ProjectPropertyElement.cs +++ b/src/Build/Construction/ProjectPropertyElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.Internal; diff --git a/src/Build/Construction/ProjectPropertyGroupElement.cs b/src/Build/Construction/ProjectPropertyGroupElement.cs index e211c892f6e..4c9fc27fe46 100644 --- a/src/Build/Construction/ProjectPropertyGroupElement.cs +++ b/src/Build/Construction/ProjectPropertyGroupElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Construction/ProjectRootElement.cs b/src/Build/Construction/ProjectRootElement.cs index 3463e872980..b0ff4459c4a 100644 --- a/src/Build/Construction/ProjectRootElement.cs +++ b/src/Build/Construction/ProjectRootElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -209,12 +209,10 @@ private ProjectRootElement(ProjectRootElementCacheBase projectRootElementCache, /// Assumes path is already normalized. /// May throw InvalidProjectFileException. /// - private ProjectRootElement - ( + private ProjectRootElement( string path, ProjectRootElementCacheBase projectRootElementCache, - bool preserveFormatting - ) + bool preserveFormatting) { ErrorUtilities.VerifyThrowArgumentLength(path, nameof(path)); ErrorUtilities.VerifyThrowInternalRooted(path); @@ -238,7 +236,7 @@ bool preserveFormatting /// /// Do not make public: we do not wish to expose particular XML API's. /// - private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementCacheBase projectRootElementCache) + private ProjectRootElement(XmlDocumentWithLocation document, ProjectRootElementCacheBase projectRootElementCache) { ErrorUtilities.VerifyThrowArgumentNull(document, nameof(document)); ErrorUtilities.VerifyThrowArgumentNull(projectRootElementCache, nameof(projectRootElementCache)); @@ -789,7 +787,8 @@ public static ProjectRootElement Create(string path, ProjectCollection projectCo var projectRootElement = new ProjectRootElement( projectCollection.ProjectRootElementCache, - newProjectFileOptions) { FullPath = path }; + newProjectFileOptions) + { FullPath = path }; return projectRootElement; } @@ -1239,7 +1238,7 @@ public ProjectUsingTaskElement AddUsingTask(string name, string assemblyFile, st /// public ProjectChooseElement CreateChooseElement() { - return Link!=null ? RootLink.CreateChooseElement() : ProjectChooseElement.CreateDisconnected(this); + return Link != null ? RootLink.CreateChooseElement() : ProjectChooseElement.CreateDisconnected(this); } /// @@ -1266,7 +1265,7 @@ public ProjectItemElement CreateItemElement(string itemType) /// public ProjectItemElement CreateItemElement(string itemType, string include) { - if (Link != null ) + if (Link != null) { return RootLink.CreateItemElement(itemType, include); } @@ -2010,12 +2009,10 @@ private static ProjectRootElement OpenLoader(string path, ProjectRootElementCach /// If the file is in MSBuild format, may throw InvalidProjectFileException. /// If the file is a solution, will throw an IO-related exception if the file cannot be read. /// - private static ProjectRootElement CreateProjectFromPath - ( + private static ProjectRootElement CreateProjectFromPath( string projectFile, ProjectRootElementCacheBase projectRootElementCache, - bool preserveFormatting - ) + bool preserveFormatting) { ErrorUtilities.VerifyThrowInternalRooted(projectFile); @@ -2054,7 +2051,7 @@ private XmlDocumentWithLocation LoadDocument(string fullPath, bool preserveForma { ErrorUtilities.VerifyThrowInternalRooted(fullPath); - var document = new XmlDocumentWithLocation(loadAsReadOnly ? true : (bool?) null) + var document = new XmlDocumentWithLocation(loadAsReadOnly ? true : (bool?)null) { FullPath = fullPath, PreserveWhitespace = preserveFormatting @@ -2104,7 +2101,7 @@ private XmlDocumentWithLocation LoadDocument(string fullPath, bool preserveForma /// private static XmlDocumentWithLocation LoadDocument(XmlReader reader, bool preserveFormatting) { - var document = new XmlDocumentWithLocation {PreserveWhitespace = preserveFormatting}; + var document = new XmlDocumentWithLocation { PreserveWhitespace = preserveFormatting }; try { diff --git a/src/Build/Construction/ProjectSdkElement.cs b/src/Build/Construction/ProjectSdkElement.cs index 751a1c80a39..19abbbf834e 100644 --- a/src/Build/Construction/ProjectSdkElement.cs +++ b/src/Build/Construction/ProjectSdkElement.cs @@ -1,6 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -//----------------------------------------------------------------------- +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.ObjectModelRemoting; using Microsoft.Build.Shared; diff --git a/src/Build/Construction/ProjectTargetElement.cs b/src/Build/Construction/ProjectTargetElement.cs index 5865039ceff..f7618c427be 100644 --- a/src/Build/Construction/ProjectTargetElement.cs +++ b/src/Build/Construction/ProjectTargetElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -88,7 +88,11 @@ public string Name if (Link != null) { return TargetLink.Name; } // No thread-safety lock required here because many reader threads would set the same value to the field. - if (_name != null) return _name; + if (_name != null) + { + return _name; + } + string unescapedValue = EscapingUtilities.UnescapeAll(GetAttributeValue(XMakeAttributes.name)); return _name = unescapedValue; } @@ -265,13 +269,11 @@ public string Returns return; } - XmlAttributeWithLocation returnsAttribute = ProjectXmlUtilities.SetOrRemoveAttribute - ( + XmlAttributeWithLocation returnsAttribute = ProjectXmlUtilities.SetOrRemoveAttribute( XmlElement, XMakeAttributes.returns, value, - true /* only remove the element if the value is null -- setting to empty string is OK */ - ); + true); /* only remove the element if the value is null -- setting to empty string is OK */ // if this target's Returns attribute is non-null, then there is at least one target in the // parent project that has the returns attribute. diff --git a/src/Build/Construction/ProjectTaskElement.cs b/src/Build/Construction/ProjectTaskElement.cs index f599e4d6f71..9798a27df29 100644 --- a/src/Build/Construction/ProjectTaskElement.cs +++ b/src/Build/Construction/ProjectTaskElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Construction/ProjectUsingTaskBodyElement.cs b/src/Build/Construction/ProjectUsingTaskBodyElement.cs index 02f37cebceb..9ef2a82faf0 100644 --- a/src/Build/Construction/ProjectUsingTaskBodyElement.cs +++ b/src/Build/Construction/ProjectUsingTaskBodyElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.ObjectModelRemoting; diff --git a/src/Build/Construction/ProjectUsingTaskElement.cs b/src/Build/Construction/ProjectUsingTaskElement.cs index 22a741e4370..75a989967bb 100644 --- a/src/Build/Construction/ProjectUsingTaskElement.cs +++ b/src/Build/Construction/ProjectUsingTaskElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Construction/ProjectUsingTaskParameterElement.cs b/src/Build/Construction/ProjectUsingTaskParameterElement.cs index 77ff6bc1893..e7da47595bc 100644 --- a/src/Build/Construction/ProjectUsingTaskParameterElement.cs +++ b/src/Build/Construction/ProjectUsingTaskParameterElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -16,7 +16,7 @@ namespace Microsoft.Build.Construction [DebuggerDisplay("Name={Name} ParameterType={ParameterType} Output={Output} Required={Required}")] public class ProjectUsingTaskParameterElement : ProjectElement { - ProjectUsingTaskParameterElementLink TaskParameterLink => (ProjectUsingTaskParameterElementLink)Link; + private ProjectUsingTaskParameterElementLink TaskParameterLink => (ProjectUsingTaskParameterElementLink)Link; /// /// External projects support /// @@ -75,7 +75,7 @@ public string Name XmlElementWithLocation newElement = XmlUtilities.RenameXmlElement(XmlElement, value, XmlElement.NamespaceURI); ReplaceElement(newElement); - // SetOrRemoveAttribute(XMakeAttributes.name, value, "Set usingtaskparameter {0}", value); + // SetOrRemoveAttribute(XMakeAttributes.name, value, "Set usingtaskparameter {0}", value); } } diff --git a/src/Build/Construction/ProjectWhenElement.cs b/src/Build/Construction/ProjectWhenElement.cs index 105aa19ad69..bf4c2dc4db0 100644 --- a/src/Build/Construction/ProjectWhenElement.cs +++ b/src/Build/Construction/ProjectWhenElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Xml; diff --git a/src/Build/Construction/Solution/ProjectConfigurationInSolution.cs b/src/Build/Construction/Solution/ProjectConfigurationInSolution.cs index 6f3507e19c3..4056ee44afd 100644 --- a/src/Build/Construction/Solution/ProjectConfigurationInSolution.cs +++ b/src/Build/Construction/Solution/ProjectConfigurationInSolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/Construction/Solution/ProjectInSolution.cs b/src/Build/Construction/Solution/ProjectInSolution.cs index 46581a81688..6fe5e032d8d 100644 --- a/src/Build/Construction/Solution/ProjectInSolution.cs +++ b/src/Build/Construction/Solution/ProjectInSolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Construction/Solution/SolutionConfigurationInSolution.cs b/src/Build/Construction/Solution/SolutionConfigurationInSolution.cs index 7518fc26980..57d868d3a03 100644 --- a/src/Build/Construction/Solution/SolutionConfigurationInSolution.cs +++ b/src/Build/Construction/Solution/SolutionConfigurationInSolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Construction/Solution/SolutionFile.cs b/src/Build/Construction/Solution/SolutionFile.cs index ce67004e11c..8326549c24b 100644 --- a/src/Build/Construction/Solution/SolutionFile.cs +++ b/src/Build/Construction/Solution/SolutionFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -37,8 +37,7 @@ public sealed class SolutionFile // An example of a project line looks like this: // Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClassLibrary1", "ClassLibrary1\ClassLibrary1.csproj", "{05A5AD00-71B5-4612-AF2F-9EA9121C4111}" private static readonly Lazy s_crackProjectLine = new Lazy( - () => new Regex - ( + () => new Regex( "^" // Beginning of line + "Project\\(\"(?.*)\"\\)" + "\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace @@ -48,9 +47,7 @@ public sealed class SolutionFile + "\\s*,\\s*" // Any amount of whitespace plus "," plus any amount of whitespace + "\"(?.*)\"" + "$", // End-of-line - RegexOptions.Compiled - ) - ); + RegexOptions.Compiled)); // An example of a property line looks like this: // AspNetCompiler.VirtualPath = "/webprecompile" @@ -58,16 +55,13 @@ public sealed class SolutionFile // one of their properties, may now have '=' in it. private static readonly Lazy s_crackPropertyLine = new Lazy( - () => new Regex - ( + () => new Regex( "^" // Beginning of line + "(?[^=]*)" + "\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace + "(?.*)" + "$", // End-of-line - RegexOptions.Compiled - ) - ); + RegexOptions.Compiled)); internal const int slnFileMinUpgradableVersion = 7; // Minimum version for MSBuild to give a nice message internal const int slnFileMinVersion = 9; // Minimum version for MSBuild to actually do anything useful @@ -325,28 +319,24 @@ internal static void GetSolutionFileAndVisualStudioMajorVersions(string solution if (!System.Version.TryParse(fileVersionFromHeader, out Version version)) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFile), "SolutionParseVersionMismatchError", slnFileMinUpgradableVersion, - slnFileMaxVersion - ); + slnFileMaxVersion); } solutionVersion = version.Major; // Validate against our min & max - ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( solutionVersion >= slnFileMinUpgradableVersion, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFile), "SolutionParseVersionMismatchError", slnFileMinUpgradableVersion, - slnFileMaxVersion - ); + slnFileMaxVersion); validVersionFound = true; } @@ -372,12 +362,10 @@ internal static void GetSolutionFileAndVisualStudioMajorVersions(string solution } // Didn't find the header in lines 1-4, so the solution file is invalid. - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFile), - "SolutionParseNoHeaderError" - ); + "SolutionParseNoHeaderError"); } private void ParseSolutionFilter(string solutionFilterFile) @@ -388,14 +376,12 @@ private void ParseSolutionFilter(string solutionFilterFile) _solutionFile = ParseSolutionFromSolutionFilter(solutionFilterFile, out JsonElement solution); if (!FileSystems.Default.FileExists(_solutionFile)) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(_solutionFile), "SolutionFilterMissingSolutionError", solutionFilterFile, - _solutionFile - ); + _solutionFile); } SolutionFileDirectory = Path.GetDirectoryName(_solutionFile); @@ -408,15 +394,13 @@ private void ParseSolutionFilter(string solutionFilterFile) } catch (Exception e) when (e is JsonException || e is KeyNotFoundException || e is InvalidOperationException) { - ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( false, /* Just throw the exception */ "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFilterFile), e, "SolutionFilterJsonParsingError", - solutionFilterFile - ); + solutionFilterFile); } } @@ -432,15 +416,13 @@ internal static string ParseSolutionFromSolutionFilter(string solutionFilterFile } catch (Exception e) when (e is JsonException || e is KeyNotFoundException || e is InvalidOperationException) { - ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( false, /* Just throw the exception */ "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFilterFile), e, "SolutionFilterJsonParsingError", - solutionFilterFile - ); + solutionFilterFile); } solution = new JsonElement(); return string.Empty; @@ -571,15 +553,13 @@ internal void ParseSolution() { if (!projectPaths.Contains(project)) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(FileUtilities.GetFullPath(project, Path.GetDirectoryName(_solutionFile))), "SolutionFilterFilterContainsProjectNotInSolution", _solutionFilterFile, project, - _solutionFile - ); + _solutionFile); } } } @@ -1062,12 +1042,10 @@ private void ValidateProjectRelativePath(ProjectInSolution proj) /// Takes a property name / value that comes from the SLN file for a Venus project, and /// stores it appropriately in our data structures. /// - private static void ParseAspNetCompilerProperty - ( + private static void ParseAspNetCompilerProperty( ProjectInSolution proj, string propertyName, - string propertyValue - ) + string propertyValue) { // What we expect to find in the SLN file is something that looks like this: // @@ -1241,10 +1219,8 @@ string propertyValue /// /// Strips a single pair of leading/trailing double-quotes from a string. /// - private static string TrimQuotes - ( - string property - ) + private static string TrimQuotes( + string property) { // If the incoming string starts and ends with a double-quote, strip the double-quotes. if (!string.IsNullOrEmpty(property) && (property[0] == '"') && (property[property.Length - 1] == '"')) @@ -1265,11 +1241,9 @@ string property /// /// /// - internal void ParseFirstProjectLine - ( + internal void ParseFirstProjectLine( string firstLine, - ProjectInSolution proj - ) + ProjectInSolution proj) { Match match = s_crackProjectLine.Value.Match(firstLine); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(match.Success, "SubCategoryForSolutionParsingErrors", @@ -1548,8 +1522,7 @@ internal void ProcessProjectConfigurationSection(Dictionary rawP var projectConfiguration = new ProjectConfigurationInSolution( configurationPlatformParts[0], (configurationPlatformParts.Length > 1) ? configurationPlatformParts[1] : string.Empty, - rawProjectConfigurationsEntries.ContainsKey(entryNameBuild) - ); + rawProjectConfigurationsEntries.ContainsKey(entryNameBuild)); project.SetProjectConfiguration(solutionConfiguration.FullName, projectConfiguration); } diff --git a/src/Build/Construction/Solution/SolutionProjectGenerator.cs b/src/Build/Construction/Solution/SolutionProjectGenerator.cs index 7bfceeffa27..02b2bc09e15 100644 --- a/src/Build/Construction/Solution/SolutionProjectGenerator.cs +++ b/src/Build/Construction/Solution/SolutionProjectGenerator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; #if FEATURE_ASPNET_COMPILER @@ -85,8 +85,7 @@ internal class SolutionProjectGenerator "ValidateSolutionConfiguration", "ValidateToolsVersions", "ValidateProjects", - "GetSolutionConfigurationContents" - ); + "GetSolutionConfigurationContents"); #if FEATURE_ASPNET_COMPILER /// @@ -207,8 +206,7 @@ private SolutionProjectGenerator( /// An to use. /// The current build submission ID. /// An array of ProjectInstances. The first instance is the traversal project, the remaining are the metaprojects for each project referenced in the solution. - internal static ProjectInstance[] Generate - ( + internal static ProjectInstance[] Generate( SolutionFile solution, IDictionary globalProperties, string toolsVersionOverride, @@ -218,8 +216,7 @@ internal static ProjectInstance[] Generate ISdkResolverService sdkResolverService = null, int submissionId = BuildEventContext.InvalidSubmissionId) { - SolutionProjectGenerator projectGenerator = new SolutionProjectGenerator - ( + SolutionProjectGenerator projectGenerator = new SolutionProjectGenerator( solution, globalProperties, toolsVersionOverride, @@ -227,8 +224,7 @@ internal static ProjectInstance[] Generate loggingService, targetNames, sdkResolverService, - submissionId - ); + submissionId); return projectGenerator.Generate(); } @@ -314,14 +310,12 @@ internal static void AddPropertyGroupForSolutionConfiguration(ProjectRootElement /// /// Add a new error/warning/message tag into the given target /// - internal static ProjectTaskElement AddErrorWarningMessageElement - ( + internal static ProjectTaskElement AddErrorWarningMessageElement( ProjectTargetElement target, string elementType, bool treatAsLiteral, string textResourceName, - params object[] args - ) + params object[] args) { string text = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string code, out string helpKeyword, textResourceName, args); @@ -409,13 +403,11 @@ private static string DetermineWrapperProjectToolsVersion(string toolsVersionOve /// the Copy task to copy all these files (or at least the ones that RAR determined should /// be copied local) into the web project's bin directory. /// - private static void AddTasksToCopyAllDependenciesIntoBinDir - ( + private static void AddTasksToCopyAllDependenciesIntoBinDir( ProjectTargetInstance target, ProjectInSolution project, string referenceItemName, - string conditionDescribingValidConfigurations - ) + string conditionDescribingValidConfigurations) { string copyLocalFilesItemName = referenceItemName + "_CopyLocalFiles"; string targetFrameworkDirectoriesName = GenerateSafePropertyName(project, "_TargetFrameworkDirectories"); @@ -459,11 +451,9 @@ string conditionDescribingValidConfigurations // directory. ProjectTaskInstance copyTask = target.AddTask("Copy", conditionDescribingValidConfigurations, null); copyTask.SetParameter("SourceFiles", "@(" + copyLocalFilesItemName + ")"); - copyTask.SetParameter - ( + copyTask.SetParameter( "DestinationFiles", - String.Format(CultureInfo.InvariantCulture, @"@({0}->'{1}%(DestinationSubDirectory)%(Filename)%(Extension)')", copyLocalFilesItemName, destinationFolder) - ); + String.Format(CultureInfo.InvariantCulture, @"@({0}->'{1}%(DestinationSubDirectory)%(Filename)%(Extension)')", copyLocalFilesItemName, destinationFolder)); } /// @@ -473,12 +463,10 @@ string conditionDescribingValidConfigurations /// search all *.REFRESH files and extract fully-qualified absolute paths for /// each of the references. /// - private static void AddTasksToResolveAutoRefreshFileReferences - ( + private static void AddTasksToResolveAutoRefreshFileReferences( ProjectTargetInstance target, ProjectInSolution project, - string referenceItemName - ) + string referenceItemName) { string webRoot = "$(" + GenerateSafePropertyName(project, "AspNetPhysicalPath") + ")"; @@ -505,15 +493,13 @@ string referenceItemName /// /// Adds an MSBuild task to the specified target /// - private static ProjectTaskInstance AddMSBuildTaskInstance - ( + private static ProjectTaskInstance AddMSBuildTaskInstance( ProjectTargetInstance target, string projectPath, string msbuildTargetName, string configurationName, string platformName, - bool specifyProjectToolsVersion - ) + bool specifyProjectToolsVersion) { ProjectTaskInstance msbuildTask = target.AddTask("MSBuild", null, null); msbuildTask.SetParameter("Projects", EscapingUtilities.Escape(projectPath)); @@ -527,8 +513,7 @@ bool specifyProjectToolsVersion CultureInfo.InvariantCulture, "Configuration={0}; Platform={1}; BuildingSolutionFile=true; CurrentSolutionConfigurationContents=$(CurrentSolutionConfigurationContents); SolutionDir=$(SolutionDir); SolutionExt=$(SolutionExt); SolutionFileName=$(SolutionFileName); SolutionName=$(SolutionName); SolutionPath=$(SolutionPath)", EscapingUtilities.Escape(configurationName), - EscapingUtilities.Escape(platformName) - ); + EscapingUtilities.Escape(platformName)); msbuildTask.SetParameter("Properties", additionalProperties); if (specifyProjectToolsVersion) @@ -544,11 +529,9 @@ bool specifyProjectToolsVersion /// that can safely be used as an XML element name, and is also unique to that project (by /// embedding the project's GUID into the property name. /// - private static string GenerateSafePropertyName - ( + private static string GenerateSafePropertyName( ProjectInSolution proj, - string propertyName - ) + string propertyName) { // XML element names cannot contain curly braces, so get rid of them from the project guid. string projectGuid = proj.ProjectGuid.Substring(1, proj.ProjectGuid.Length - 2); @@ -585,15 +568,13 @@ private static string MakeIntoSafeItemName(string name) /// /// Add a new error/warning/message tag into the given target /// - private static ProjectTaskInstance AddErrorWarningMessageInstance - ( + private static ProjectTaskInstance AddErrorWarningMessageInstance( ProjectTargetInstance target, string condition, string elementType, bool treatAsLiteral, string textResourceName, - params object[] args - ) + params object[] args) { string text = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out string code, out string helpKeyword, textResourceName, args); @@ -627,13 +608,11 @@ params object[] args /// private static string GetConditionStringForConfiguration(SolutionConfigurationInSolution configuration) { - return string.Format - ( + return string.Format( CultureInfo.InvariantCulture, " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", EscapingUtilities.Escape(configuration.ConfigurationName), - EscapingUtilities.Escape(configuration.PlatformName) - ); + EscapingUtilities.Escape(configuration.PlatformName)); } /// @@ -707,13 +686,11 @@ private static bool WouldProjectBuild(SolutionFile solutionFile, string selected private ProjectInstance[] Generate() { // Validate against our minimum for upgradable projects - ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( _solutionFile.Version >= SolutionFile.slnFileMinVersion, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(_solutionFile.FullPath), - "SolutionParseUpgradeNeeded" - ); + "SolutionParseUpgradeNeeded"); // This is needed in order to make decisions about tools versions such as whether to put a // ToolsVersion parameter on task tags and what MSBuildToolsPath to use when @@ -1008,8 +985,7 @@ private ProjectInstance CreateTraversalInstance(string wrapperProjectToolsVersio traversalProject.FullPath = path; // Create the instance. From this point forward we can evaluate conditions against the traversal project directly. - var traversalInstance = new ProjectInstance - ( + var traversalInstance = new ProjectInstance( traversalProject, _globalProperties, explicitToolsVersionSpecified ? wrapperProjectToolsVersion : null, @@ -1017,8 +993,7 @@ private ProjectInstance CreateTraversalInstance(string wrapperProjectToolsVersio _solutionFile.VisualStudioVersion, new ProjectCollection(), _sdkResolverService, - _submissionId - ); + _submissionId); // Traversal meta project entire state has to be serialized as it was generated and hence // does not have disk representation to load project from. @@ -1168,14 +1143,12 @@ private bool CanBuildDirectly(ProjectInstance traversalProject, ProjectInSolutio { if (!_solutionFile.ProjectsByGuid.TryGetValue(dependencyProjectGuid, out ProjectInSolution dependencyProject)) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(traversalProject.FullPath), "SolutionParseProjectDepNotFoundError", projectToAdd.ProjectGuid, - dependencyProjectGuid - ); + dependencyProjectGuid); } if (WouldProjectBuild(_solutionFile, _selectedSolutionConfiguration, dependencyProject, projectConfiguration)) @@ -1240,13 +1213,11 @@ private ProjectInstance CreateMetaproject(ProjectInstance traversalProject, Proj if (project.ProjectType == SolutionProjectType.WebProject) { #if !FEATURE_ASPNET_COMPILER - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(_solutionFile.FullPath), "AspNetCompiler.UnsupportedMSBuildVersion", - project.ProjectName - ); + project.ProjectName); #else AddMetaprojectTargetForWebProject(traversalProject, metaprojectInstance, project, null); AddMetaprojectTargetForWebProject(traversalProject, metaprojectInstance, project, "Clean"); @@ -1328,14 +1299,12 @@ private void AddMetaprojectReferenceItems(ProjectInstance traversalProject, Proj { if (!_solutionFile.ProjectsByGuid.TryGetValue(dependencyProjectGuid, out ProjectInSolution dependencyProject)) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(traversalProject.FullPath), "SolutionParseProjectDepNotFoundError", project.ProjectGuid, - dependencyProjectGuid - ); + dependencyProjectGuid); } else { @@ -1498,15 +1467,13 @@ private void AddMetaprojectTargetForWebProject(ProjectInstance traversalProject, // of referenced projects. foreach (SolutionConfigurationInSolution solutionConfiguration in _solutionFile.SolutionConfigurations) { - AddResolveProjectReferenceTasks - ( + AddResolveProjectReferenceTasks( traversalProject, newTarget, project, solutionConfiguration, referenceItemName.ToString(), - out _ - ); + out _); } } @@ -1523,26 +1490,22 @@ out _ // Add a call to the task, conditioned on having an *invalid* Configuration. The // message says that we're skipping the Venus project because it's either not enabled // for precompilation, or doesn't support the given configuration. - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( newTarget, "!(" + conditionDescribingValidConfigurations + ")", XMakeElements.message, false, - "SolutionVenusProjectSkipped" - ); + "SolutionVenusProjectSkipped"); } } /// /// Helper method to add a call to the AspNetCompiler task into the given target. /// - private void AddTaskForAspNetCompiler - ( + private void AddTaskForAspNetCompiler( ProjectTargetInstance target, ProjectInSolution project, - string conditionDescribingValidConfigurations - ) + string conditionDescribingValidConfigurations) { // Add a call to the AspNetCompiler task, conditioned on having a valid Configuration. ProjectTaskInstance newTask = target.AddTask("AspNetCompiler", conditionDescribingValidConfigurations, null); @@ -1566,15 +1529,13 @@ string conditionDescribingValidConfigurations } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( new BuildEventFileInfo(_solutionFile.FullPath), e, "AspNetCompiler.InvalidTargetFrameworkMonikerFromException", project.ProjectName, project.TargetFrameworkMoniker, - e.Message - ); + e.Message); } } @@ -1585,25 +1546,21 @@ private void ValidateTargetFrameworkForWebProject(ProjectInSolution project) if (targetFramework.Version > _version40) { - _loggingService.LogComment - ( + _loggingService.LogComment( _projectBuildEventContext, MessageImportance.Low, "AspNetCompiler.TargetingHigherFrameworksDefaultsTo40", project.ProjectName, - targetFramework.Version.ToString() - ); + targetFramework.Version.ToString()); } if (!isDotNetFramework) { - ProjectFileErrorUtilities.ThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.ThrowInvalidProjectFile( "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(_solutionFile.FullPath), "AspNetCompiler.InvalidTargetFrameworkMonikerNotDotNET", project.ProjectName, - project.TargetFrameworkMoniker - ); + project.TargetFrameworkMoniker); } } @@ -1618,13 +1575,11 @@ private void SetToolPathForAspNetCompilerTask(ProjectInSolution project, Project Version aspnetCompilerVersion = shouldDefaultToVersion40 ? _version40 : _version20; string aspnetCompilerPath = FrameworkLocationHelper.GetPathToDotNetFramework(aspnetCompilerVersion); - ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( aspnetCompilerPath != null, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(_solutionFile.FullPath), - "AspNetCompiler.20NotInstalled" - ); + "AspNetCompiler.20NotInstalled"); task.SetParameter("ToolPath", aspnetCompilerPath); } @@ -1632,15 +1587,13 @@ private void SetToolPathForAspNetCompilerTask(ProjectInSolution project, Project /// /// Adds MSBuild tasks to a project target to pre-resolve its project references /// - private void AddResolveProjectReferenceTasks - ( + private void AddResolveProjectReferenceTasks( ProjectInstance traversalProject, ProjectTargetInstance target, ProjectInSolution project, SolutionConfigurationInSolution solutionConfiguration, string outputReferenceItemName, - out string addedReferenceGuids - ) + out string addedReferenceGuids) { var referenceGuids = new StringBuilder(); @@ -1668,15 +1621,13 @@ out string addedReferenceGuids bool specifyProjectToolsVersion = !String.Equals(traversalProject.ToolsVersion, "2.0", StringComparison.OrdinalIgnoreCase); - ProjectTaskInstance msbuildTask = AddMSBuildTaskInstance - ( + ProjectTaskInstance msbuildTask = AddMSBuildTaskInstance( target, referencedProject.RelativePath, "GetTargetPath", referencedProjectConfiguration.ConfigurationName, referencedProjectConfiguration.PlatformName, - specifyProjectToolsVersion - ); + specifyProjectToolsVersion); msbuildTask.AddOutputItem("TargetOutputs", outputReferenceItemNameWithSuffix, null); } @@ -1705,15 +1656,13 @@ out string addedReferenceGuids /// Add a PropertyGroup to the project for a particular Asp.Net configuration. This PropertyGroup /// will have the correct values for all the Asp.Net properties for this project and this configuration. /// - private static void AddPropertyGroupForAspNetConfiguration - ( + private static void AddPropertyGroupForAspNetConfiguration( ProjectInstance traversalProject, ProjectInstance metaprojectInstance, ProjectInSolution project, string configurationName, AspNetCompilerParameters aspNetCompilerParameters, - string solutionFile - ) + string solutionFile) { // If the configuration doesn't match, don't add the properties. if (!traversalProject.EvaluateCondition(String.Format(CultureInfo.InvariantCulture, " '$(AspNetConfiguration)' == '{0}' ", EscapingUtilities.Escape(configurationName)))) @@ -1741,8 +1690,7 @@ string solutionFile // Trim the trailing slash if one exists. if ( (aspNetPhysicalPath[aspNetPhysicalPath.Length - 1] == Path.AltDirectorySeparatorChar) || - (aspNetPhysicalPath[aspNetPhysicalPath.Length - 1] == Path.DirectorySeparatorChar) - ) + (aspNetPhysicalPath[aspNetPhysicalPath.Length - 1] == Path.DirectorySeparatorChar)) { aspNetPhysicalPath = aspNetPhysicalPath.Substring(0, aspNetPhysicalPath.Length - 1); } @@ -1756,16 +1704,14 @@ string solutionFile } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { - ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile - ( + ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( false, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFile), e, "SolutionParseInvalidProjectFileName", project.RelativePath, - e.Message - ); + e.Message); } if (!String.IsNullOrEmpty(lastFolderInPhysicalPath)) @@ -1786,11 +1732,9 @@ string solutionFile // Make sure the path we are appending to has no leading slash to prevent double slashes. string publishWebsitePath = EscapingUtilities.Escape(WebProjectOverrideFolder) + Path.DirectorySeparatorChar + EscapingUtilities.Escape(lastFolderInPhysicalPath) + Path.DirectorySeparatorChar; - metaprojectInstance.SetProperty - ( + metaprojectInstance.SetProperty( GenerateSafePropertyName(project, "AspNetTargetPath"), - outDirValue + publishWebsitePath - ); + outDirValue + publishWebsitePath); } } } @@ -1915,57 +1859,49 @@ private void AddMetaprojectTargetForUnknownProjectType(ProjectInstance traversal { // we haven't encountered any problems accessing the project file in the past, but do not support // building this project type - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( newTarget, null, XMakeElements.warning, true, "SolutionParseUnknownProjectType", - project.RelativePath - ); + project.RelativePath); } else { // this project file may be of supported type, but we have encountered problems accessing it - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( newTarget, null, XMakeElements.warning, true, "SolutionParseErrorReadingProject", project.RelativePath, - unknownProjectTypeErrorMessage - ); + unknownProjectTypeErrorMessage); } } else { - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( newTarget, null, XMakeElements.message, true, "SolutionProjectSkippedForBuilding", project.ProjectName, - solutionConfiguration.FullName - ); + solutionConfiguration.FullName); } } else { - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( newTarget, null, XMakeElements.warning, true, "SolutionProjectConfigurationMissing", project.ProjectName, - solutionConfiguration.FullName - ); + solutionConfiguration.FullName); } } } @@ -1987,30 +1923,26 @@ private void AddValidateProjectsTarget(ProjectInstance traversalProject, List 0) { - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( initialTarget, "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' != 'true')", XMakeElements.error, false /* do not treat as literal */, "SolutionInvalidSolutionConfiguration", - "$(Configuration)|$(Platform)" - ); + "$(Configuration)|$(Platform)"); - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( initialTarget, "('$(CurrentSolutionConfigurationContents)' == '') and ('$(SkipInvalidConfigurations)' == 'true')", XMakeElements.warning, false /* do not treat as literal */, "SolutionInvalidSolutionConfiguration", - "$(Configuration)|$(Platform)" - ); + "$(Configuration)|$(Platform)"); - AddErrorWarningMessageInstance - ( + AddErrorWarningMessageInstance( initialTarget, "'$(CurrentSolutionConfigurationContents)' != ''", XMakeElements.message, false /* do not treat as literal */, "SolutionBuildingSolutionConfiguration", - "$(Configuration)|$(Platform)" - ); + "$(Configuration)|$(Platform)"); } } @@ -2448,15 +2370,13 @@ private void AddValidateSolutionConfigurationTarget(ProjectInstance traversalPro private static void AddValidateToolsVersionsTarget(ProjectInstance traversalProject) { ProjectTargetInstance validateToolsVersionsTarget = traversalProject.AddTarget("ValidateToolsVersions", null, null, null, null, null, null, null, null, false /* legacy target returns behaviour */); - ProjectTaskInstance toolsVersionErrorTask = AddErrorWarningMessageInstance - ( + ProjectTaskInstance toolsVersionErrorTask = AddErrorWarningMessageInstance( validateToolsVersionsTarget, "'$(MSBuildToolsVersion)' == '2.0' and ('$(ProjectToolsVersion)' != '2.0' and '$(ProjectToolsVersion)' != '')", XMakeElements.error, false /* do not treat as literal */, "SolutionToolsVersionDoesNotSupportProjectToolsVersion", - "$(MSBuildToolsVersion)" - ); + "$(MSBuildToolsVersion)"); } /// Adds the target to fetch solution configuration contents for given configuration|platform combo. diff --git a/src/Build/Construction/UsingTaskParameterGroupElement.cs b/src/Build/Construction/UsingTaskParameterGroupElement.cs index 0f52d672ff0..9b58223c601 100644 --- a/src/Build/Construction/UsingTaskParameterGroupElement.cs +++ b/src/Build/Construction/UsingTaskParameterGroupElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Definition/BuiltInMetadata.cs b/src/Build/Definition/BuiltInMetadata.cs index dd325c8a458..7687a4a47e9 100644 --- a/src/Build/Definition/BuiltInMetadata.cs +++ b/src/Build/Definition/BuiltInMetadata.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -20,7 +20,7 @@ internal static class BuiltInMetadata /// /// Retrieves the count of built-in metadata. /// - static internal int MetadataCount + internal static int MetadataCount { [DebuggerStepThrough] get @@ -30,7 +30,7 @@ static internal int MetadataCount /// /// Retrieves the list of metadata names. /// - static internal ICollection MetadataNames + internal static ICollection MetadataNames { [DebuggerStepThrough] get diff --git a/src/Build/Definition/NewProjectFileOptions.cs b/src/Build/Definition/NewProjectFileOptions.cs index 12e32de1a01..a4a4d04c066 100644 --- a/src/Build/Definition/NewProjectFileOptions.cs +++ b/src/Build/Definition/NewProjectFileOptions.cs @@ -1,4 +1,7 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; #nullable disable diff --git a/src/Build/Definition/Project.cs b/src/Build/Definition/Project.cs index 0ba22cdf4e7..6faa9cde0ea 100644 --- a/src/Build/Definition/Project.cs +++ b/src/Build/Definition/Project.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -2660,9 +2660,9 @@ private static IMSBuildGlob CreateIncludeGlobWithGaps(IMSBuildGlob includeGlob, { return (excludeGlob, removeGlob) switch { - (null, null) => includeGlob, - (not null, null) => new MSBuildGlobWithGaps(includeGlob, excludeGlob), - (null, not null) => new MSBuildGlobWithGaps(includeGlob, removeGlob), + (null, null) => includeGlob, + (not null, null) => new MSBuildGlobWithGaps(includeGlob, excludeGlob), + (null, not null) => new MSBuildGlobWithGaps(includeGlob, removeGlob), (not null, not null) => new MSBuildGlobWithGaps(includeGlob, new CompositeGlob(excludeGlob, removeGlob)) }; } @@ -4296,14 +4296,12 @@ public void InitializeForEvaluation(IToolsetProvider toolsetProvider, Evaluation toolsVersionLocation = Project.Xml.ToolsVersionLocation; } - string toolsVersionToUse = Utilities.GenerateToolsVersionToUse - ( + string toolsVersionToUse = Utilities.GenerateToolsVersionToUse( ExplicitToolsVersion, Project.Xml.ToolsVersion, Project.ProjectCollection.GetToolset, Project.ProjectCollection.DefaultToolsVersion, - out var usingDifferentToolsVersionFromProjectFile - ); + out var usingDifferentToolsVersionFromProjectFile); UsingDifferentToolsVersionFromProjectFile = usingDifferentToolsVersionFromProjectFile; diff --git a/src/Build/Definition/ProjectCollection.cs b/src/Build/Definition/ProjectCollection.cs index 838e95574fc..2a7325a9d32 100644 --- a/src/Build/Definition/ProjectCollection.cs +++ b/src/Build/Definition/ProjectCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -613,7 +613,7 @@ public ICollection Loggers using (_locker.EnterDisposableUpgradeableReadLock()) { return _loggingService.Loggers == null - ? (ICollection) ReadOnlyEmptyCollection.Instance + ? (ICollection)ReadOnlyEmptyCollection.Instance : new List(_loggingService.Loggers); } } @@ -1090,7 +1090,7 @@ internal ICollection GetLoadedProjects(bool includeExternal, string ful List loaded; using (_locker.EnterDisposableWriteLock()) { - loaded = fullPath == null ? new List(_loadedProjects) : new List(_loadedProjects.GetMatchingProjectsIfAny(fullPath)); + loaded = fullPath == null ? new List(_loadedProjects) : new List(_loadedProjects.GetMatchingProjectsIfAny(fullPath)); } if (includeExternal) @@ -1495,7 +1495,7 @@ public void Dispose() GC.SuppressFinalize(this); } -#region IBuildComponent Members + #region IBuildComponent Members /// /// Initializes the component with the component host. @@ -1512,7 +1512,7 @@ void IBuildComponent.ShutdownComponent() { } -#endregion + #endregion /// /// Unloads a project XML root element from the cache entirely, if it is not @@ -1780,8 +1780,7 @@ private void InitializeToolsetCollection( #if FEATURE_WIN32_REGISTRY ToolsetRegistryReader registryReader = null, #endif - ToolsetConfigurationReader configReader = null - ) + ToolsetConfigurationReader configReader = null) { _toolsets = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -1934,7 +1933,7 @@ public ReusableLogger(ILogger originalLogger) _originalLogger = originalLogger; } -#region IEventSource Members + #region IEventSource Members /// /// The Message logging event @@ -2161,7 +2160,7 @@ public void Shutdown() } } -#endregion + #endregion /// /// Registers for all of the events on the specified event source. diff --git a/src/Build/Definition/ProjectCollectionChangedEventArgs.cs b/src/Build/Definition/ProjectCollectionChangedEventArgs.cs index 2b7f7d5f927..5248067010c 100644 --- a/src/Build/Definition/ProjectCollectionChangedEventArgs.cs +++ b/src/Build/Definition/ProjectCollectionChangedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/Definition/ProjectImportPathMatch.cs b/src/Build/Definition/ProjectImportPathMatch.cs index f793dda52fd..60e07850b99 100644 --- a/src/Build/Definition/ProjectImportPathMatch.cs +++ b/src/Build/Definition/ProjectImportPathMatch.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.BackEnd; diff --git a/src/Build/Definition/ProjectItem.cs b/src/Build/Definition/ProjectItem.cs index 6dd0d58102c..11e35aa5ece 100644 --- a/src/Build/Definition/ProjectItem.cs +++ b/src/Build/Definition/ProjectItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.Collections; @@ -124,8 +124,7 @@ internal ProjectItem( string evaluatedIncludeEscaped, string evaluatedIncludeBeforeWildcardExpansionEscaped, PropertyDictionary directMetadataCloned, - List inheritedItemDefinitionsCloned - ) + List inheritedItemDefinitionsCloned) { ErrorUtilities.VerifyThrowInternalNull(project, nameof(project)); ErrorUtilities.VerifyThrowArgumentNull(xml, nameof(xml)); @@ -270,7 +269,7 @@ public int DirectMetadataCount { [DebuggerStepThrough] get - { return Link != null ? Link.DirectMetadata.Count : _directMetadata != null ? _directMetadata.Count : 0; } + { return Link != null ? Link.DirectMetadata.Count : _directMetadata != null ? _directMetadata.Count : 0; } } /// diff --git a/src/Build/Definition/ProjectItemDefinition.cs b/src/Build/Definition/ProjectItemDefinition.cs index 3dac87761bb..0e3ddd7a1d8 100644 --- a/src/Build/Definition/ProjectItemDefinition.cs +++ b/src/Build/Definition/ProjectItemDefinition.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/Build/Definition/ProjectLoadSettings.cs b/src/Build/Definition/ProjectLoadSettings.cs index 9f767d1bf47..a257aa08128 100644 --- a/src/Build/Definition/ProjectLoadSettings.cs +++ b/src/Build/Definition/ProjectLoadSettings.cs @@ -1,4 +1,7 @@ -using System; +// 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.Diagnostics.CodeAnalysis; #nullable disable diff --git a/src/Build/Definition/ProjectMetadata.cs b/src/Build/Definition/ProjectMetadata.cs index 198c8231ac8..aa172d165b5 100644 --- a/src/Build/Definition/ProjectMetadata.cs +++ b/src/Build/Definition/ProjectMetadata.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Definition/ProjectOptions.cs b/src/Build/Definition/ProjectOptions.cs index 6cdbc750dbd..5c5e3cee3f9 100644 --- a/src/Build/Definition/ProjectOptions.cs +++ b/src/Build/Definition/ProjectOptions.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Generic; using Microsoft.Build.Evaluation; using Microsoft.Build.Evaluation.Context; using Microsoft.Build.FileSystem; diff --git a/src/Build/Definition/ProjectProperty.cs b/src/Build/Definition/ProjectProperty.cs index e03454a5f7d..6a05f7dadbc 100644 --- a/src/Build/Definition/ProjectProperty.cs +++ b/src/Build/Definition/ProjectProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Definition/ResolvedImport.cs b/src/Build/Definition/ResolvedImport.cs index 378b6546baa..72cde59d08e 100644 --- a/src/Build/Definition/ResolvedImport.cs +++ b/src/Build/Definition/ResolvedImport.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using Microsoft.Build.Construction; diff --git a/src/Build/Definition/SubToolset.cs b/src/Build/Definition/SubToolset.cs index af5f8e9ffa2..95cf1aa153e 100644 --- a/src/Build/Definition/SubToolset.cs +++ b/src/Build/Definition/SubToolset.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Build/Definition/Toolset.cs b/src/Build/Definition/Toolset.cs index aed480e2f4e..ec59aaff465 100644 --- a/src/Build/Definition/Toolset.cs +++ b/src/Build/Definition/Toolset.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -562,8 +562,7 @@ internal static bool Dev10IsInstalled RegistryKeyWrapper.KeyExists(Dev10VBExpressInstallKeyRegistryPath, RegistryHive.LocalMachine, RegistryView.Registry32) || RegistryKeyWrapper.KeyExists(Dev10VCExpressInstallKeyRegistryPath, RegistryHive.LocalMachine, RegistryView.Registry32) || RegistryKeyWrapper.KeyExists(Dev10VWDExpressInstallKeyRegistryPath, RegistryHive.LocalMachine, RegistryView.Registry32) || - RegistryKeyWrapper.KeyExists(Dev10LightSwitchInstallKeyRegistryPath, RegistryHive.LocalMachine, RegistryView.Registry32) - ) + RegistryKeyWrapper.KeyExists(Dev10LightSwitchInstallKeyRegistryPath, RegistryHive.LocalMachine, RegistryView.Registry32)) { s_dev10IsInstalled = true; } @@ -710,30 +709,26 @@ internal static string[] GetTaskFiles(DirectoryGetFiles getFiles, ILoggingServic if (defaultTasksFiles.Length == 0) { - loggingServices.LogWarning - ( + loggingServices.LogWarning( buildEventContext, null, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), taskFileWarning, taskPattern, searchPath, - String.Empty - ); + String.Empty); } } catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e)) { - loggingServices.LogWarning - ( + loggingServices.LogWarning( buildEventContext, null, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), taskFileWarning, taskPattern, searchPath, - e.Message - ); + e.Message); } // Sort the file names to give a deterministic order @@ -1073,16 +1068,13 @@ private void LoadAndRegisterFromTasksFile(string[] defaultTaskFiles, ILoggingSer if (usingTask == null) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( elementXml.Location, "UnrecognizedElement", - elementXml.XmlElement.Name - ); + elementXml.XmlElement.Name); } - TaskRegistry.RegisterTasksFromUsingTaskElement - ( + TaskRegistry.RegisterTasksFromUsingTaskElement( loggingServices, buildEventContext, Path.GetDirectoryName(defaultTasksFile), @@ -1090,8 +1082,7 @@ private void LoadAndRegisterFromTasksFile(string[] defaultTaskFiles, ILoggingSer registry, _expander, ExpanderOptions.ExpandProperties, - FileSystems.Default - ); + FileSystems.Default); } } catch (XmlException e) diff --git a/src/Build/Definition/ToolsetConfigurationReader.cs b/src/Build/Definition/ToolsetConfigurationReader.cs index db1aa93901e..f754cbf4d3c 100644 --- a/src/Build/Definition/ToolsetConfigurationReader.cs +++ b/src/Build/Definition/ToolsetConfigurationReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -267,8 +267,8 @@ private static Configuration ReadOpenMappedExeConfiguration() { // When running from the command-line or from VS, use the msbuild.exe.config file. if (BuildEnvironmentHelper.Instance.Mode != BuildEnvironmentMode.None && - // This FEATURE_SYSTEM_CONFIGURATION is needed as OpenExeConfiguration for net5.0 works differently, without this condition unit tests won't pass. - // ConfigurationManager.OpenExeConfiguration in net5.0 will find testhost.exe instead which does not contain any configuration and therefore fail. + // This FEATURE_SYSTEM_CONFIGURATION is needed as OpenExeConfiguration for net5.0 works differently, without this condition unit tests won't pass. + // ConfigurationManager.OpenExeConfiguration in net5.0 will find testhost.exe instead which does not contain any configuration and therefore fail. #if FEATURE_SYSTEM_CONFIGURATION !BuildEnvironmentHelper.Instance.RunningTests && #endif diff --git a/src/Build/Definition/ToolsetLocalReader.cs b/src/Build/Definition/ToolsetLocalReader.cs index ce17fd8ffb1..b4476a5786e 100644 --- a/src/Build/Definition/ToolsetLocalReader.cs +++ b/src/Build/Definition/ToolsetLocalReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; using Microsoft.Build.Construction; diff --git a/src/Build/Definition/ToolsetPropertyDefinition.cs b/src/Build/Definition/ToolsetPropertyDefinition.cs index 01e4a01bc6c..2c38bce7b0c 100644 --- a/src/Build/Definition/ToolsetPropertyDefinition.cs +++ b/src/Build/Definition/ToolsetPropertyDefinition.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; diff --git a/src/Build/Definition/ToolsetReader.cs b/src/Build/Definition/ToolsetReader.cs index f2393bfcbc1..c7723447806 100644 --- a/src/Build/Definition/ToolsetReader.cs +++ b/src/Build/Definition/ToolsetReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -99,8 +99,7 @@ internal static string ReadAllToolsets(Dictionary toolsets, Pro /// Gathers toolset data from the registry and configuration file, if any. /// NOTE: this method is internal for unit testing purposes only. /// - internal static string ReadAllToolsets - ( + internal static string ReadAllToolsets( Dictionary toolsets, #if FEATURE_WIN32_REGISTRY ToolsetRegistryReader registryReader, @@ -108,8 +107,7 @@ internal static string ReadAllToolsets ToolsetConfigurationReader configurationReader, PropertyDictionary environmentProperties, PropertyDictionary globalProperties, - ToolsetDefinitionLocations locations - ) + ToolsetDefinitionLocations locations) { var initialProperties = new PropertyDictionary(environmentProperties); @@ -356,15 +354,13 @@ void ReadConfigToolset() /// /// Internal for unit testing only /// the default tools version if available, or null otherwise - internal string ReadToolsets - ( + internal string ReadToolsets( Dictionary toolsets, PropertyDictionary globalProperties, PropertyDictionary initialProperties, bool accumulateProperties, out string msBuildOverrideTasksPath, - out string defaultOverrideToolsVersion - ) + out string defaultOverrideToolsVersion) { ErrorUtils.VerifyThrowArgumentNull(toolsets, "Toolsets"); @@ -416,13 +412,11 @@ out string defaultOverrideToolsVersion /// /// Reads all the toolsets and populates the given ToolsetCollection with them /// - private void ReadEachToolset - ( + private void ReadEachToolset( Dictionary toolsets, PropertyDictionary globalProperties, PropertyDictionary initialProperties, - bool accumulateProperties - ) + bool accumulateProperties) { foreach (ToolsetPropertyDefinition toolsVersion in ToolsVersions) { @@ -482,13 +476,11 @@ string existingRootOrNull(string path) /// /// Reads the settings for a specified tools version /// - private Toolset ReadToolset - ( + private Toolset ReadToolset( ToolsetPropertyDefinition toolsVersion, PropertyDictionary globalProperties, PropertyDictionary initialProperties, - bool accumulateProperties - ) + bool accumulateProperties) { // Initial properties is the set of properties we're going to use to expand property expressions like $(foo) // in the values we read out of the registry or config file. We'll add to it as we pick up properties (including binpath) @@ -673,12 +665,10 @@ private void EvaluateAndSetProperty(ToolsetPropertyDefinition property, Property if (accumulateProperties) { - SetProperty - ( + SetProperty( new ToolsetPropertyDefinition(ReservedPropertyNames.toolsPath, toolsPath, property.Source), initialProperties, - globalProperties - ); + globalProperties); } } else if (String.Equals(property.Name, ReservedPropertyNames.binPath, StringComparison.OrdinalIgnoreCase)) @@ -688,12 +678,10 @@ private void EvaluateAndSetProperty(ToolsetPropertyDefinition property, Property if (accumulateProperties) { - SetProperty - ( + SetProperty( new ToolsetPropertyDefinition(ReservedPropertyNames.binPath, binPath, property.Source), initialProperties, - globalProperties - ); + globalProperties); } } else if (ReservedPropertyNames.IsReservedProperty(property.Name)) @@ -853,5 +841,5 @@ public static MSBuildExtensionsPathReferenceKind FindIn(string expression) return MSBuildExtensionsPathReferenceKind.None; } - } + } } diff --git a/src/Build/Definition/ToolsetRegistryReader.cs b/src/Build/Definition/ToolsetRegistryReader.cs index f049808eaea..7c38151cac7 100644 --- a/src/Build/Definition/ToolsetRegistryReader.cs +++ b/src/Build/Definition/ToolsetRegistryReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_WIN32_REGISTRY diff --git a/src/Build/ElementLocation/ElementLocation.cs b/src/Build/ElementLocation/ElementLocation.cs index e0cc6e95fcc..63629f1ef21 100644 --- a/src/Build/ElementLocation/ElementLocation.cs +++ b/src/Build/ElementLocation/ElementLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Microsoft.Build.BackEnd; diff --git a/src/Build/ElementLocation/RegistryLocation.cs b/src/Build/ElementLocation/RegistryLocation.cs index 598b72a853c..b39b4da62a2 100644 --- a/src/Build/ElementLocation/RegistryLocation.cs +++ b/src/Build/ElementLocation/RegistryLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Microsoft.Build.BackEnd; @@ -89,7 +89,7 @@ public void Translate(ITranslator translator) /// /// Factory for serialization. /// - static internal RegistryLocation FactoryForDeserialization(ITranslator translator) + internal static RegistryLocation FactoryForDeserialization(ITranslator translator) { return new RegistryLocation(translator); } diff --git a/src/Build/ElementLocation/XmlAttributeWithLocation.cs b/src/Build/ElementLocation/XmlAttributeWithLocation.cs index 8aa000ccfab..c0fbad7e82c 100644 --- a/src/Build/ElementLocation/XmlAttributeWithLocation.cs +++ b/src/Build/ElementLocation/XmlAttributeWithLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Build/ElementLocation/XmlDocumentWithLocation.cs b/src/Build/ElementLocation/XmlDocumentWithLocation.cs index 9b8b04e1736..bbc34c86a57 100644 --- a/src/Build/ElementLocation/XmlDocumentWithLocation.cs +++ b/src/Build/ElementLocation/XmlDocumentWithLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -174,7 +174,7 @@ public override void Load(string fullPath) _fullPath = fullPath; - using(var xtr = XmlReaderExtension.Create(fullPath, _loadAsReadOnly ?? false)) + using (var xtr = XmlReaderExtension.Create(fullPath, _loadAsReadOnly ?? false)) { this.Load(xtr.Reader); } diff --git a/src/Build/ElementLocation/XmlElementWithLocation.cs b/src/Build/ElementLocation/XmlElementWithLocation.cs index 726bf84df57..91a5f107a36 100644 --- a/src/Build/ElementLocation/XmlElementWithLocation.cs +++ b/src/Build/ElementLocation/XmlElementWithLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Build/ElementLocation/XmlNameTableThreadSafe.cs b/src/Build/ElementLocation/XmlNameTableThreadSafe.cs index a5f068becf4..1bcb4e7dd8f 100644 --- a/src/Build/ElementLocation/XmlNameTableThreadSafe.cs +++ b/src/Build/ElementLocation/XmlNameTableThreadSafe.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Build/Errors/InternalLoggerException.cs b/src/Build/Errors/InternalLoggerException.cs index 7acb0b4603d..06daa610cd9 100644 --- a/src/Build/Errors/InternalLoggerException.cs +++ b/src/Build/Errors/InternalLoggerException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -80,22 +80,20 @@ public InternalLoggerException(string message, Exception innerException) /// /// /// - internal InternalLoggerException - ( + internal InternalLoggerException( string message, Exception innerException, BuildEventArgs e, string errorCode, string helpKeyword, - bool initializationException - ) + bool initializationException) : base(message, innerException) { ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(message), "Need error message."); ErrorUtilities.VerifyThrow(innerException != null || initializationException, "Need the logger exception."); ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(errorCode), "Must specify the error message code."); ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(helpKeyword), "Must specify the help keyword for the IDE."); - + this.e = e; this.errorCode = errorCode; this.helpKeyword = helpKeyword; @@ -128,7 +126,7 @@ private InternalLoggerException(SerializationInfo info, StreamingContext context #if FEATURE_SECURITY_PERMISSIONS [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] #endif - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); @@ -216,14 +214,12 @@ public bool InitializationException /// /// /// - internal static void Throw - ( + internal static void Throw( Exception innerException, BuildEventArgs e, string messageResourceName, bool initializationException, - params string[] messageArgs - ) + params string[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need error message."); diff --git a/src/Build/Errors/InvalidProjectFileException.cs b/src/Build/Errors/InvalidProjectFileException.cs index a947dd83005..71c7d93d2cc 100644 --- a/src/Build/Errors/InvalidProjectFileException.cs +++ b/src/Build/Errors/InvalidProjectFileException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -107,7 +107,7 @@ private InvalidProjectFileException(SerializationInfo info, StreamingContext con #if FEATURE_SECURITY_PERMISSIONS [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] #endif - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); @@ -139,8 +139,7 @@ override public void GetObjectData(SerializationInfo info, StreamingContext cont /// Error sub-category that describes the error (can be null). /// The error code (can be null). /// The F1-help keyword for the host IDE (can be null). - public InvalidProjectFileException - ( + public InvalidProjectFileException( string projectFile, int lineNumber, int columnNumber, @@ -149,8 +148,7 @@ public InvalidProjectFileException string message, string errorSubcategory, string errorCode, - string helpKeyword - ) : + string helpKeyword) : this(projectFile, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, errorSubcategory, errorCode, helpKeyword, null) { } @@ -169,8 +167,7 @@ string helpKeyword /// The error code (can be null). /// The F1-help keyword for the host IDE (can be null). /// Any inner exception. May be null. - internal InvalidProjectFileException - ( + internal InvalidProjectFileException( string projectFile, int lineNumber, int columnNumber, @@ -180,8 +177,7 @@ internal InvalidProjectFileException string errorSubcategory, string errorCode, string helpKeyword, - Exception innerException - ) : base(message, innerException) + Exception innerException) : base(message, innerException) { ErrorUtilities.VerifyThrowArgumentNull(projectFile, nameof(projectFile)); ErrorUtilities.VerifyThrowArgumentLength(message, nameof(message)); diff --git a/src/Build/Errors/InvalidToolsetDefinitionException.cs b/src/Build/Errors/InvalidToolsetDefinitionException.cs index 3d516446388..9f7c51e0b61 100644 --- a/src/Build/Errors/InvalidToolsetDefinitionException.cs +++ b/src/Build/Errors/InvalidToolsetDefinitionException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -126,11 +126,9 @@ public string ErrorCode /// /// /// - internal static void Throw - ( + internal static void Throw( string resourceName, - params string[] args - ) + params string[] args) { Throw(null, resourceName, args); } @@ -143,12 +141,10 @@ params string[] args /// is expensive, because memory is allocated for the array of arguments -- do /// not call this method repeatedly in performance-critical scenarios /// - internal static void Throw - ( + internal static void Throw( Exception innerException, string resourceName, - params string[] args - ) + params string[] args) { #if DEBUG ResourceUtilities.VerifyResourceStringExists(resourceName); diff --git a/src/Build/Errors/RegistryException.cs b/src/Build/Errors/RegistryException.cs index 4e3cb2e25ac..13d4335634d 100644 --- a/src/Build/Errors/RegistryException.cs +++ b/src/Build/Errors/RegistryException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Build/Evaluation/ConditionEvaluator.cs b/src/Build/Evaluation/ConditionEvaluator.cs index 183ce5117d6..653cfe536b9 100644 --- a/src/Build/Evaluation/ConditionEvaluator.cs +++ b/src/Build/Evaluation/ConditionEvaluator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -36,18 +36,13 @@ internal static class ConditionEvaluator /// concatenated together with a vertical bar, as in ' /// $(Configuration)|$(Platform)' == 'Debug|x86' /// - /// - /// - /// - internal static void UpdateConditionedPropertiesTable - ( - Dictionary> conditionedPropertiesTable, // List of possible values, keyed by property name - - string leftValue, // The raw value on the left side of the operator - - string rightValueExpanded // The fully expanded value on the right side - // of the operator. - ) + /// List of possible values, keyed by property name. + /// The raw value on the left side of the operator. + /// The fully expanded value on the right side of the operator. + internal static void UpdateConditionedPropertiesTable( + Dictionary> conditionedPropertiesTable, + string leftValue, + string rightValueExpanded) { if ((conditionedPropertiesTable != null) && (rightValueExpanded.Length > 0)) { @@ -171,8 +166,7 @@ public ConcurrentStack GetOrAdd(string condition, Func - internal static bool EvaluateCondition - ( + internal static bool EvaluateCondition( string condition, ParserOptions options, Expander expander, @@ -209,8 +203,7 @@ internal static bool EvaluateCondition /// This method is thread safe and is called from engine and task execution module threads /// Logging service may be null. /// - internal static bool EvaluateConditionCollectingConditionedProperties - ( + internal static bool EvaluateConditionCollectingConditionedProperties( string condition, ParserOptions options, Expander expander, @@ -222,8 +215,7 @@ internal static bool EvaluateConditionCollectingConditionedProperties BuildEventContext buildEventContext, IFileSystem fileSystem, ProjectRootElementCacheBase projectRootElementCache = null, - LoggingContext loggingContext = null - ) + LoggingContext loggingContext = null) where P : class, IProperty where I : class, IItem { @@ -413,8 +405,7 @@ internal class ConditionEvaluationState : IConditionEvaluationState /// public ProjectRootElementCacheBase LoadedProjectsCache { get; } - internal ConditionEvaluationState - ( + internal ConditionEvaluationState( string condition, Expander expander, ExpanderOptions expanderOptions, @@ -422,8 +413,7 @@ internal ConditionEvaluationState string evaluationDirectory, ElementLocation elementLocation, IFileSystem fileSystem, - ProjectRootElementCacheBase projectRootElementCache = null - ) + ProjectRootElementCacheBase projectRootElementCache = null) { ErrorUtilities.VerifyThrowArgumentNull(condition, nameof(condition)); ErrorUtilities.VerifyThrowArgumentNull(expander, nameof(expander)); diff --git a/src/Build/Evaluation/Conditionals/AndExpressionNode.cs b/src/Build/Evaluation/Conditionals/AndExpressionNode.cs index 47481c625c3..07708c80e85 100644 --- a/src/Build/Evaluation/Conditionals/AndExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/AndExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Shared; diff --git a/src/Build/Evaluation/Conditionals/CharacterUtilities.cs b/src/Build/Evaluation/Conditionals/CharacterUtilities.cs index 9eb85cf6b6d..06e7345b1b0 100644 --- a/src/Build/Evaluation/Conditionals/CharacterUtilities.cs +++ b/src/Build/Evaluation/Conditionals/CharacterUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -7,28 +7,28 @@ namespace Microsoft.Build.Evaluation { internal static class CharacterUtilities { - static internal bool IsNumberStart(char candidate) + internal static bool IsNumberStart(char candidate) { return candidate == '+' || candidate == '-' || candidate == '.' || char.IsDigit(candidate); } - static internal bool IsSimpleStringStart(char candidate) + internal static bool IsSimpleStringStart(char candidate) { return candidate == '_' || char.IsLetter(candidate); } - static internal bool IsSimpleStringChar(char candidate) + internal static bool IsSimpleStringChar(char candidate) { return IsSimpleStringStart(candidate) || char.IsDigit(candidate); } - static internal bool IsHexAlphabetic(char candidate) + internal static bool IsHexAlphabetic(char candidate) { return candidate == 'a' || candidate == 'b' || candidate == 'c' || candidate == 'd' || candidate == 'e' || candidate == 'f' || candidate == 'A' || candidate == 'B' || candidate == 'C' || candidate == 'D' || candidate == 'E' || candidate == 'F'; } - static internal bool IsHexDigit(char candidate) + internal static bool IsHexDigit(char candidate) { return char.IsDigit(candidate) || IsHexAlphabetic(candidate); } diff --git a/src/Build/Evaluation/Conditionals/EqualExpressionNode.cs b/src/Build/Evaluation/Conditionals/EqualExpressionNode.cs index 939493a148f..8241009f778 100644 --- a/src/Build/Evaluation/Conditionals/EqualExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/EqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/FunctionCallExpressionNode.cs b/src/Build/Evaluation/Conditionals/FunctionCallExpressionNode.cs index 4ec222243fd..ee3ccbe9b2d 100644 --- a/src/Build/Evaluation/Conditionals/FunctionCallExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/FunctionCallExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -187,8 +187,8 @@ private List ExpandArgumentAsFileList(GenericExpressionNode argumentNode /// private void VerifyArgumentCount(int expected, ConditionEvaluator.IConditionEvaluationState state) { - ProjectErrorUtilities.VerifyThrowInvalidProject - (_arguments.Count == expected, + ProjectErrorUtilities.VerifyThrowInvalidProject( + _arguments.Count == expected, state.ElementLocation, "IncorrectNumberOfFunctionArguments", state.Condition, diff --git a/src/Build/Evaluation/Conditionals/GenericExpressionNode.cs b/src/Build/Evaluation/Conditionals/GenericExpressionNode.cs index 50efb172cf7..aa512c045b3 100644 --- a/src/Build/Evaluation/Conditionals/GenericExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/GenericExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd.Logging; diff --git a/src/Build/Evaluation/Conditionals/GreaterThanExpressionNode.cs b/src/Build/Evaluation/Conditionals/GreaterThanExpressionNode.cs index 0639c92cf4f..f616f66850d 100644 --- a/src/Build/Evaluation/Conditionals/GreaterThanExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/GreaterThanExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/GreaterThanOrEqualExpressionNode.cs b/src/Build/Evaluation/Conditionals/GreaterThanOrEqualExpressionNode.cs index 74a3e162ce4..75ef77df664 100644 --- a/src/Build/Evaluation/Conditionals/GreaterThanOrEqualExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/GreaterThanOrEqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/IItem.cs b/src/Build/Evaluation/Conditionals/IItem.cs index e26b0b3e567..ed523ed33c1 100644 --- a/src/Build/Evaluation/Conditionals/IItem.cs +++ b/src/Build/Evaluation/Conditionals/IItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Construction; diff --git a/src/Build/Evaluation/Conditionals/LessThanExpressionNode.cs b/src/Build/Evaluation/Conditionals/LessThanExpressionNode.cs index a7cf6dcff1e..8b2476a7a34 100644 --- a/src/Build/Evaluation/Conditionals/LessThanExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/LessThanExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/LessThanOrEqualExpressionNode.cs b/src/Build/Evaluation/Conditionals/LessThanOrEqualExpressionNode.cs index 19de29eccf6..f641827e5fe 100644 --- a/src/Build/Evaluation/Conditionals/LessThanOrEqualExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/LessThanOrEqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/MultipleComparisonExpressionNode.cs b/src/Build/Evaluation/Conditionals/MultipleComparisonExpressionNode.cs index 1ef13748bdc..e1cf63fd6bf 100644 --- a/src/Build/Evaluation/Conditionals/MultipleComparisonExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/MultipleComparisonExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Shared; @@ -39,8 +39,8 @@ internal abstract class MultipleComparisonNode : OperatorExpressionNode /// internal override bool BoolEvaluate(ConditionEvaluator.IConditionEvaluationState state, LoggingContext loggingContext) { - ProjectErrorUtilities.VerifyThrowInvalidProject - (LeftChild != null && RightChild != null, + ProjectErrorUtilities.VerifyThrowInvalidProject( + LeftChild != null && RightChild != null, state.ElementLocation, "IllFormedCondition", state.Condition); @@ -77,8 +77,8 @@ internal override bool BoolEvaluate(ConditionEvaluator.IConditionEvaluationState string leftExpandedValue = LeftChild.GetExpandedValue(state, loggingContext); string rightExpandedValue = RightChild.GetExpandedValue(state, loggingContext); - ProjectErrorUtilities.VerifyThrowInvalidProject - (leftExpandedValue != null && rightExpandedValue != null, + ProjectErrorUtilities.VerifyThrowInvalidProject( + leftExpandedValue != null && rightExpandedValue != null, state.ElementLocation, "IllFormedCondition", state.Condition); @@ -109,16 +109,16 @@ private void UpdateConditionedProperties(ConditionEvaluator.IConditionEvaluation if (leftUnexpandedValue != null) { - ConditionEvaluator.UpdateConditionedPropertiesTable - (state.ConditionedPropertiesInProject, + ConditionEvaluator.UpdateConditionedPropertiesTable( + state.ConditionedPropertiesInProject, leftUnexpandedValue, RightChild.GetExpandedValue(state)); } if (rightUnexpandedValue != null) { - ConditionEvaluator.UpdateConditionedPropertiesTable - (state.ConditionedPropertiesInProject, + ConditionEvaluator.UpdateConditionedPropertiesTable( + state.ConditionedPropertiesInProject, rightUnexpandedValue, LeftChild.GetExpandedValue(state)); } diff --git a/src/Build/Evaluation/Conditionals/NotEqualExpressionNode.cs b/src/Build/Evaluation/Conditionals/NotEqualExpressionNode.cs index 34aedc61d6c..c0770a833f2 100644 --- a/src/Build/Evaluation/Conditionals/NotEqualExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/NotEqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/NotExpressionNode.cs b/src/Build/Evaluation/Conditionals/NotExpressionNode.cs index 1d2e1d6311e..f40106ded47 100644 --- a/src/Build/Evaluation/Conditionals/NotExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/NotExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Shared; diff --git a/src/Build/Evaluation/Conditionals/NumericComparisonExpressionNode.cs b/src/Build/Evaluation/Conditionals/NumericComparisonExpressionNode.cs index f161ad5d18b..a371e9a0850 100644 --- a/src/Build/Evaluation/Conditionals/NumericComparisonExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/NumericComparisonExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd.Logging; diff --git a/src/Build/Evaluation/Conditionals/NumericExpressionNode.cs b/src/Build/Evaluation/Conditionals/NumericExpressionNode.cs index 7725d9962dc..536ac17ae9b 100644 --- a/src/Build/Evaluation/Conditionals/NumericExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/NumericExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/OperandExpressionNode.cs b/src/Build/Evaluation/Conditionals/OperandExpressionNode.cs index 1dfbc5ecba4..09ab3630596 100644 --- a/src/Build/Evaluation/Conditionals/OperandExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/OperandExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Evaluation/Conditionals/OperatorExpressionNode.cs b/src/Build/Evaluation/Conditionals/OperatorExpressionNode.cs index a3f76ff20ff..0f20ef208c3 100644 --- a/src/Build/Evaluation/Conditionals/OperatorExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/OperatorExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BackEnd.Logging; diff --git a/src/Build/Evaluation/Conditionals/OrExpressionNode.cs b/src/Build/Evaluation/Conditionals/OrExpressionNode.cs index fa1816c2e1d..ea702400754 100644 --- a/src/Build/Evaluation/Conditionals/OrExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/OrExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Shared; diff --git a/src/Build/Evaluation/Conditionals/Parser.cs b/src/Build/Evaluation/Conditionals/Parser.cs index 3496e8f3b8b..0984647db61 100644 --- a/src/Build/Evaluation/Conditionals/Parser.cs +++ b/src/Build/Evaluation/Conditionals/Parser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Evaluation/Conditionals/Scanner.cs b/src/Build/Evaluation/Conditionals/Scanner.cs index f8f74e0686a..76ad5124991 100644 --- a/src/Build/Evaluation/Conditionals/Scanner.cs +++ b/src/Build/Evaluation/Conditionals/Scanner.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System; @@ -134,10 +134,14 @@ internal string UnexpectedlyFound internal bool Advance() { if (_errorState) + { return false; + } if (_lookahead?.IsToken(Token.TokenType.EndOfInput) == true) + { return true; + } SkipWhiteSpace(); @@ -166,11 +170,17 @@ internal bool Advance() break; case '$': if (!ParseProperty()) + { return false; + } + break; case '%': if (!ParseItemMetadata()) + { return false; + } + break; case '@': int start = _parsePoint; @@ -186,7 +196,10 @@ internal bool Advance() } } if (!ParseItemList()) + { return false; + } + break; case '!': // negation and not-equal @@ -253,12 +266,18 @@ internal bool Advance() break; case '\'': if (!ParseQuotedString()) + { return false; + } + break; default: // Simple strings, function calls, decimal numbers, hex numbers if (!ParseRemaining()) + { return false; + } + break; } } @@ -644,12 +663,16 @@ private bool ParseRemaining() if (CharacterUtilities.IsNumberStart(_expression[_parsePoint])) // numeric { if (!ParseNumeric(start)) + { return false; + } } else if (CharacterUtilities.IsSimpleStringStart(_expression[_parsePoint])) // simple string (handle 'and' and 'or') { if (!ParseSimpleStringOrFunction(start)) + { return false; + } } else { @@ -742,25 +765,37 @@ private bool ParseNumeric(int start) private void SkipWhiteSpace() { while (_parsePoint < _expression.Length && char.IsWhiteSpace(_expression[_parsePoint])) + { _parsePoint++; + } + return; } private void SkipDigits() { while (_parsePoint < _expression.Length && char.IsDigit(_expression[_parsePoint])) + { _parsePoint++; + } + return; } private void SkipHexDigits() { while (_parsePoint < _expression.Length && CharacterUtilities.IsHexDigit(_expression[_parsePoint])) + { _parsePoint++; + } + return; } private void SkipSimpleStringChars() { while (_parsePoint < _expression.Length && CharacterUtilities.IsSimpleStringChar(_expression[_parsePoint])) + { _parsePoint++; + } + return; } } diff --git a/src/Build/Evaluation/Conditionals/StringExpressionNode.cs b/src/Build/Evaluation/Conditionals/StringExpressionNode.cs index 43dd324e7a8..2f05a821326 100644 --- a/src/Build/Evaluation/Conditionals/StringExpressionNode.cs +++ b/src/Build/Evaluation/Conditionals/StringExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/Conditionals/Token.cs b/src/Build/Evaluation/Conditionals/Token.cs index d26adca0462..182c3e3c6b0 100644 --- a/src/Build/Evaluation/Conditionals/Token.cs +++ b/src/Build/Evaluation/Conditionals/Token.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using ErrorUtilities = Microsoft.Build.Shared.ErrorUtilities; @@ -15,19 +15,19 @@ namespace Microsoft.Build.Evaluation /// internal sealed class Token { - internal readonly static Token Comma = new Token(TokenType.Comma); - internal readonly static Token LeftParenthesis = new Token(TokenType.LeftParenthesis); - internal readonly static Token RightParenthesis = new Token(TokenType.RightParenthesis); - internal readonly static Token LessThan = new Token(TokenType.LessThan); - internal readonly static Token GreaterThan = new Token(TokenType.GreaterThan); - internal readonly static Token LessThanOrEqualTo = new Token(TokenType.LessThanOrEqualTo); - internal readonly static Token GreaterThanOrEqualTo = new Token(TokenType.GreaterThanOrEqualTo); - internal readonly static Token And = new Token(TokenType.And); - internal readonly static Token Or = new Token(TokenType.Or); - internal readonly static Token EqualTo = new Token(TokenType.EqualTo); - internal readonly static Token NotEqualTo = new Token(TokenType.NotEqualTo); - internal readonly static Token Not = new Token(TokenType.Not); - internal readonly static Token EndOfInput = new Token(TokenType.EndOfInput); + internal static readonly Token Comma = new Token(TokenType.Comma); + internal static readonly Token LeftParenthesis = new Token(TokenType.LeftParenthesis); + internal static readonly Token RightParenthesis = new Token(TokenType.RightParenthesis); + internal static readonly Token LessThan = new Token(TokenType.LessThan); + internal static readonly Token GreaterThan = new Token(TokenType.GreaterThan); + internal static readonly Token LessThanOrEqualTo = new Token(TokenType.LessThanOrEqualTo); + internal static readonly Token GreaterThanOrEqualTo = new Token(TokenType.GreaterThanOrEqualTo); + internal static readonly Token And = new Token(TokenType.And); + internal static readonly Token Or = new Token(TokenType.Or); + internal static readonly Token EqualTo = new Token(TokenType.EqualTo); + internal static readonly Token NotEqualTo = new Token(TokenType.NotEqualTo); + internal static readonly Token Not = new Token(TokenType.Not); + internal static readonly Token EndOfInput = new Token(TokenType.EndOfInput); /// /// Valid tokens @@ -90,16 +90,14 @@ internal Token(TokenType type, string tokenString) /// internal Token(TokenType type, string tokenString, bool expandable) { - ErrorUtilities.VerifyThrow - ( + ErrorUtilities.VerifyThrow( type == TokenType.Property || type == TokenType.String || type == TokenType.Numeric || type == TokenType.ItemList || type == TokenType.ItemMetadata || type == TokenType.Function, - "Unexpected token type" - ); + "Unexpected token type"); ErrorUtilities.VerifyThrowInternalNull(tokenString, nameof(tokenString)); diff --git a/src/Build/Evaluation/Context/EvaluationContext.cs b/src/Build/Evaluation/Context/EvaluationContext.cs index 7d9b891a484..d28c9210e29 100644 --- a/src/Build/Evaluation/Context/EvaluationContext.cs +++ b/src/Build/Evaluation/Context/EvaluationContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -67,7 +67,7 @@ private EvaluationContext(SharingPolicy policy, IFileSystem fileSystem, ISdkReso /// public static EvaluationContext Create(SharingPolicy policy) { - + // ReSharper disable once IntroduceOptionalParameters.Global // do not remove this method to avoid breaking binary compatibility return Create(policy, fileSystem: null); diff --git a/src/Build/Evaluation/Evaluator.cs b/src/Build/Evaluation/Evaluator.cs index 59dba0b96ad..dd25193cec7 100644 --- a/src/Build/Evaluation/Evaluator.cs +++ b/src/Build/Evaluation/Evaluator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -411,31 +411,27 @@ private static ProjectTaskInstance ReadTaskElement(ProjectTaskElement taskElemen { if (output.IsOutputItem) { - ProjectTaskOutputItemInstance outputItem = new ProjectTaskOutputItemInstance - ( + ProjectTaskOutputItemInstance outputItem = new ProjectTaskOutputItemInstance( output.ItemType, output.TaskParameter, output.Condition, output.Location, output.ItemTypeLocation, output.TaskParameterLocation, - output.ConditionLocation - ); + output.ConditionLocation); taskOutputs.Add(outputItem); } else { - ProjectTaskOutputPropertyInstance outputProperty = new ProjectTaskOutputPropertyInstance - ( + ProjectTaskOutputPropertyInstance outputProperty = new ProjectTaskOutputPropertyInstance( output.PropertyName, output.TaskParameter, output.Condition, output.Location, output.PropertyNameLocation, output.TaskParameterLocation, - output.ConditionLocation - ); + output.ConditionLocation); taskOutputs.Add(outputProperty); } @@ -489,18 +485,15 @@ private static ProjectItemGroupTaskInstance ReadItemGroupUnderTargetElement(Proj foreach (ProjectMetadataElement metadataElement in itemElement.Metadata) { - metadata.Add(new ProjectItemGroupTaskMetadataInstance - ( + metadata.Add(new ProjectItemGroupTaskMetadataInstance( metadataElement.Name, metadataElement.Value, metadataElement.Condition, metadataElement.Location, - metadataElement.ConditionLocation - )); + metadataElement.ConditionLocation)); } - items.Add(new ProjectItemGroupTaskItemInstance - ( + items.Add(new ProjectItemGroupTaskItemInstance( itemElement.ItemType, itemElement.Include, itemElement.Exclude, @@ -521,8 +514,7 @@ private static ProjectItemGroupTaskInstance ReadItemGroupUnderTargetElement(Proj itemElement.RemoveMetadataLocation, itemElement.KeepDuplicatesLocation, itemElement.ConditionLocation, - metadata - )); + metadata)); } ProjectItemGroupTaskInstance itemGroup = new ProjectItemGroupTaskInstance(itemGroupElement.Condition, itemGroupElement.Location, itemGroupElement.ConditionLocation, items); @@ -570,8 +562,7 @@ private static ProjectTargetInstance ReadNewTargetElement(ProjectTargetElement t ObjectModel.ReadOnlyCollection readOnlyTargetChildren = new ObjectModel.ReadOnlyCollection(targetChildren); ObjectModel.ReadOnlyCollection readOnlyTargetOnErrorChildren = new ObjectModel.ReadOnlyCollection(targetOnErrorChildren); - ProjectTargetInstance targetInstance = new ProjectTargetInstance - ( + ProjectTargetInstance targetInstance = new ProjectTargetInstance( targetElement.Name, targetElement.Condition, targetElement.Inputs, @@ -592,8 +583,7 @@ private static ProjectTargetInstance ReadNewTargetElement(ProjectTargetElement t targetElement.AfterTargetsLocation, readOnlyTargetChildren, readOnlyTargetOnErrorChildren, - parentProjectSupportsReturnsAttribute - ); + parentProjectSupportsReturnsAttribute); targetElement.TargetInstance = targetInstance; return targetInstance; @@ -1025,8 +1015,7 @@ private void EvaluateItemGroupElement(ProjectItemGroupElement itemGroupElement, /// private void EvaluateUsingTaskElement(string directoryOfImportingFile, ProjectUsingTaskElement projectUsingTaskElement) { - TaskRegistry.RegisterTasksFromUsingTaskElement - ( + TaskRegistry.RegisterTasksFromUsingTaskElement( _evaluationLoggingContext.LoggingService, _evaluationLoggingContext.BuildEventContext, directoryOfImportingFile, @@ -1034,8 +1023,7 @@ private void EvaluateUsingTaskElement(string directoryOfImportingFile, ProjectUs _data.TaskRegistry, _expander, ExpanderOptions.ExpandPropertiesAndItems, - _evaluationContext.FileSystem - ); + _evaluationContext.FileSystem); } /// @@ -1300,8 +1288,7 @@ private void EvaluatePropertyElement(ProjectPropertyElement propertyElement) // of this project (or import). if ( ((IDictionary)_data.GlobalPropertiesDictionary).ContainsKey(propertyElement.Name) && - !_data.GlobalPropertiesToTreatAsLocal.Contains(propertyElement.Name) - ) + !_data.GlobalPropertiesToTreatAsLocal.Contains(propertyElement.Name)) { _evaluationLoggingContext.LogComment(MessageImportance.Low, "OM_GlobalProperty", propertyElement.Name); return; @@ -1648,7 +1635,9 @@ private List ExpandAndLoadImports(string directoryOfImportin // In the rare case that the property we've enabled for search paths hasn't been defined // we will skip it, but continue with other paths in the fallback order. if (string.IsNullOrEmpty(extensionPath)) + { continue; + } string extensionPathExpanded = _data.ExpandString(extensionPath); @@ -1776,7 +1765,7 @@ private void ExpandAndLoadImportsFromUnescapedImportExpressionConditioned( _evaluationLoggingContext.LogBuildEvent(eventArgs); } - + return; } @@ -1791,7 +1780,11 @@ private void ExpandAndLoadImportsFromUnescapedImportExpressionConditioned( // for backward compatibility, we shouldn't change that. But resolvers should be exposed to a string // that's null or a full path, so correct that here. var solutionPath = _data.GetProperty(SolutionProjectGenerator.SolutionPathPropertyName)?.EvaluatedValue; - if (solutionPath == "*Undefined*") solutionPath = null; + if (solutionPath == "*Undefined*") + { + solutionPath = null; + } + var projectPath = _data.GetProperty(ReservedPropertyNames.projectFullPath)?.EvaluatedValue; CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo; @@ -1810,13 +1803,17 @@ static bool HasProperty(string value, CompareInfo compareInfo) => if (mode != SdkReferencePropertyExpansionMode.NoExpansion) { if (mode == SdkReferencePropertyExpansionMode.DefaultExpand) + { mode = SdkReferencePropertyExpansionMode.ExpandUnescape; + } static string EvaluateProperty(string value, IElementLocation location, Expander expander, SdkReferencePropertyExpansionMode mode) { if (value == null) + { return null; + } const ExpanderOptions Options = ExpanderOptions.ExpandProperties; @@ -1839,8 +1836,7 @@ static string EvaluateProperty(string value, IElementLocation location, sdkReference = new SdkReference( EvaluateProperty(sdkReference.Name, sdkReferenceOrigin, _expander, mode), EvaluateProperty(sdkReference.Version, sdkReferenceOrigin, _expander, mode), - EvaluateProperty(sdkReference.MinimumVersion, sdkReferenceOrigin, _expander, mode) - ); + EvaluateProperty(sdkReference.MinimumVersion, sdkReferenceOrigin, _expander, mode)); } } @@ -2444,8 +2440,7 @@ private bool EvaluateCondition(ProjectElement element, string condition, Expande using (_evaluationProfiler.TrackCondition(element.ConditionLocation, condition)) { - bool result = ConditionEvaluator.EvaluateCondition - ( + bool result = ConditionEvaluator.EvaluateCondition( condition, parserOptions, _expander, @@ -2455,8 +2450,7 @@ private bool EvaluateCondition(ProjectElement element, string condition, Expande _evaluationLoggingContext.LoggingService, _evaluationLoggingContext.BuildEventContext, _evaluationContext.FileSystem, - loggingContext: _evaluationLoggingContext - ); + loggingContext: _evaluationLoggingContext); return result; } @@ -2484,8 +2478,7 @@ private bool EvaluateConditionCollectingConditionedProperties(ProjectElement ele using (_evaluationProfiler.TrackCondition(element.ConditionLocation, condition)) { - bool result = ConditionEvaluator.EvaluateConditionCollectingConditionedProperties - ( + bool result = ConditionEvaluator.EvaluateConditionCollectingConditionedProperties( condition, parserOptions, _expander, @@ -2496,8 +2489,7 @@ private bool EvaluateConditionCollectingConditionedProperties(ProjectElement ele _evaluationLoggingContext.LoggingService, _evaluationLoggingContext.BuildEventContext, _evaluationContext.FileSystem, - projectRootElementCache - ); + projectRootElementCache); return result; } diff --git a/src/Build/Evaluation/EvaluatorMetadataTable.cs b/src/Build/Evaluation/EvaluatorMetadataTable.cs index 686f524e965..9f7c871a7e0 100644 --- a/src/Build/Evaluation/EvaluatorMetadataTable.cs +++ b/src/Build/Evaluation/EvaluatorMetadataTable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Evaluation/Expander.cs b/src/Build/Evaluation/Expander.cs index 88e5fea6c1b..ab6d9b76eb6 100644 --- a/src/Build/Evaluation/Expander.cs +++ b/src/Build/Evaluation/Expander.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -1028,8 +1028,7 @@ internal string ExpandSingleMetadata(Match itemMetadataMatch) if ( (isBuiltInMetadata && ((_options & ExpanderOptions.ExpandBuiltInMetadata) != 0)) || - (!isBuiltInMetadata && ((_options & ExpanderOptions.ExpandCustomMetadata) != 0)) - ) + (!isBuiltInMetadata && ((_options & ExpanderOptions.ExpandCustomMetadata) != 0))) { metadataValue = _metadata.GetEscapedValue(itemType, metadataName); if (IsTruncationEnabled(_options) && metadataValue.Length > CharacterLimitPerExpansion) @@ -1934,8 +1933,7 @@ internal static bool ExpandExpressionCapture( ExpanderOptions options, bool includeNullEntries, out bool isTransformExpression, - out List> itemsFromCapture - ) + out List> itemsFromCapture) where S : class, IItem { ErrorUtilities.VerifyThrow(evaluatedItems != null, "Cannot expand items without providing items"); @@ -2112,8 +2110,7 @@ private static bool ExpandExpressionCaptureIntoStringBuilder( IItemProvider evaluatedItems, IElementLocation elementLocation, SpanBasedStringBuilder builder, - ExpanderOptions options - ) + ExpanderOptions options) where S : class, IItem { List> itemsFromCapture; @@ -3038,15 +3035,13 @@ private static class RegularExpressions /// /// PERF WARNING: this Regex is complex and tends to run slowly. internal static readonly Lazy NonTransformItemMetadataPattern = new Lazy( - () => new Regex - ( + () => new Regex( @"((?<=" + ItemVectorWithTransformLHS + @")" + ItemMetadataSpecification + @"(?!" + ItemVectorWithTransformRHS + @")) | ((? /// Complete description of an item metadata reference, including the optional qualifying item type. @@ -3125,8 +3120,7 @@ internal Function Build() BindingFlags, Remainder, UsedUninitializedProperties, - FileSystem - ); + FileSystem); } } @@ -3236,7 +3230,7 @@ internal static Function ExtractPropertyFunction( IFileSystem fileSystem) { // Used to aggregate all the components needed for a Function - FunctionBuilder functionBuilder = new FunctionBuilder {FileSystem = fileSystem}; + FunctionBuilder functionBuilder = new FunctionBuilder { FileSystem = fileSystem }; // By default the expression root is the whole function expression ReadOnlySpan expressionRoot = expressionFunction == null ? ReadOnlySpan.Empty : expressionFunction.AsSpan(); @@ -3453,7 +3447,7 @@ internal object Execute(object objectInstance, IPropertyProvider properties, // string startingDirectory = String.IsNullOrWhiteSpace(elementLocation.File) ? String.Empty : Path.GetDirectoryName(elementLocation.File); - args = new [] + args = new[] { args[0], startingDirectory, @@ -3852,7 +3846,7 @@ private bool TryExecuteWellKnownFunction(out object returnVal, object objectInst { if (ElementsOfType(args, typeof(string))) { - returnVal = IntrinsicFunctions.NormalizePath(Array.ConvertAll(args, o => (string) o)); + returnVal = IntrinsicFunctions.NormalizePath(Array.ConvertAll(args, o => (string)o)); return true; } } @@ -4158,7 +4152,7 @@ private bool TryExecuteWellKnownFunction(out object returnVal, object objectInst default: if (ElementsOfType(args, typeof(string))) { - returnVal = Path.Combine(Array.ConvertAll(args, o => (string) o)); + returnVal = Path.Combine(Array.ConvertAll(args, o => (string)o)); return true; } break; @@ -4320,8 +4314,7 @@ private bool TryGetArgs(object[] args, out string arg0, out string arg1, out str if (args[0] is string value0 && args[1] is string value1 && - args[2] is string value2 - ) + args[2] is string value2) { arg0 = value0; arg1 = value1; @@ -4348,8 +4341,7 @@ private bool TryGetArgs(object[] args, out string arg0, out string arg1, out str if (args[0] is string value0 && args[1] is string value1 && args[2] is string value2 && - args[3] is string value3 - ) + args[3] is string value3) { arg0 = value0; arg1 = value1; diff --git a/src/Build/Evaluation/ExpressionShredder.cs b/src/Build/Evaluation/ExpressionShredder.cs index a49654cefca..e7130f4b211 100644 --- a/src/Build/Evaluation/ExpressionShredder.cs +++ b/src/Build/Evaluation/ExpressionShredder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; diff --git a/src/Build/Evaluation/IEvaluatorData.cs b/src/Build/Evaluation/IEvaluatorData.cs index 497207e7024..2c534c608d2 100644 --- a/src/Build/Evaluation/IEvaluatorData.cs +++ b/src/Build/Evaluation/IEvaluatorData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Evaluation/IItem.cs b/src/Build/Evaluation/IItem.cs index 63ee0e41e3e..1365978c41d 100644 --- a/src/Build/Evaluation/IItem.cs +++ b/src/Build/Evaluation/IItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; diff --git a/src/Build/Evaluation/IItemDefinition.cs b/src/Build/Evaluation/IItemDefinition.cs index a1be67f9a98..eaf7a2b4778 100644 --- a/src/Build/Evaluation/IItemDefinition.cs +++ b/src/Build/Evaluation/IItemDefinition.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/Evaluation/IItemFactory.cs b/src/Build/Evaluation/IItemFactory.cs index e888059ee97..2125968bf6c 100644 --- a/src/Build/Evaluation/IItemFactory.cs +++ b/src/Build/Evaluation/IItemFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Construction; diff --git a/src/Build/Evaluation/IItemProvider.cs b/src/Build/Evaluation/IItemProvider.cs index cba344f2553..e4b2766c861 100644 --- a/src/Build/Evaluation/IItemProvider.cs +++ b/src/Build/Evaluation/IItemProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/Evaluation/IMetadataTable.cs b/src/Build/Evaluation/IMetadataTable.cs index 8dbc16dc63a..e7c20680216 100644 --- a/src/Build/Evaluation/IMetadataTable.cs +++ b/src/Build/Evaluation/IMetadataTable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Evaluation/IMetadatum.cs b/src/Build/Evaluation/IMetadatum.cs index 2c7618c22d1..46ed07eff3c 100644 --- a/src/Build/Evaluation/IMetadatum.cs +++ b/src/Build/Evaluation/IMetadatum.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; diff --git a/src/Build/Evaluation/IProjectMetadataParent.cs b/src/Build/Evaluation/IProjectMetadataParent.cs index 74c4ad1e2d8..ee1e954715c 100644 --- a/src/Build/Evaluation/IProjectMetadataParent.cs +++ b/src/Build/Evaluation/IProjectMetadataParent.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Evaluation/IProperty.cs b/src/Build/Evaluation/IProperty.cs index ed57eef4ea3..da311eb95dc 100644 --- a/src/Build/Evaluation/IProperty.cs +++ b/src/Build/Evaluation/IProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; diff --git a/src/Build/Evaluation/IPropertyProvider.cs b/src/Build/Evaluation/IPropertyProvider.cs index 715cf119a36..7be5736880a 100644 --- a/src/Build/Evaluation/IPropertyProvider.cs +++ b/src/Build/Evaluation/IPropertyProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Evaluation/IToolsetProvider.cs b/src/Build/Evaluation/IToolsetProvider.cs index 1b9e76836a4..0152533cac2 100644 --- a/src/Build/Evaluation/IToolsetProvider.cs +++ b/src/Build/Evaluation/IToolsetProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/Evaluation/IntrinsicFunctions.cs b/src/Build/Evaluation/IntrinsicFunctions.cs index ce0f37bbd56..be95a58ef1f 100644 --- a/src/Build/Evaluation/IntrinsicFunctions.cs +++ b/src/Build/Evaluation/IntrinsicFunctions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -594,7 +594,7 @@ public static bool IsRunningFromVisualStudio() return BuildEnvironmentHelper.Instance.Mode == BuildEnvironmentMode.VisualStudio; } -#region Debug only intrinsics + #region Debug only intrinsics /// /// returns if the string contains escaped wildcards @@ -604,7 +604,7 @@ internal static List __GetListTest() return new List { "A", "B", "C", "D" }; } -#endregion + #endregion /// /// Following function will parse a keyName and returns the basekey for it. diff --git a/src/Build/Evaluation/ItemDataCollectionValue.cs b/src/Build/Evaluation/ItemDataCollectionValue.cs index 5671a9d96ca..b380c7f9d95 100644 --- a/src/Build/Evaluation/ItemDataCollectionValue.cs +++ b/src/Build/Evaluation/ItemDataCollectionValue.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/Evaluation/ItemSpec.cs b/src/Build/Evaluation/ItemSpec.cs index d7f58c8088a..89b2ffd1938 100644 --- a/src/Build/Evaluation/ItemSpec.cs +++ b/src/Build/Evaluation/ItemSpec.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -145,7 +145,7 @@ private bool InitReferencedItemsIfNecessary() /// The expander needs to have a default item factory set. /// // todo Make this type immutable. Dealing with an Expander change is painful. See the ItemExpressionFragment - public Expander Expander { get; set; } + public Expander Expander { get; set; } /// /// The xml attribute where this itemspec comes from @@ -583,7 +583,7 @@ internal MetadataTrie(MatchOnMetadataOptions options, IEnumerable metada options == MatchOnMetadataOptions.CaseInsensitive || FileUtilities.PathComparison == StringComparison.OrdinalIgnoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _children = new Dictionary>(comparer); - _normalize = options == MatchOnMetadataOptions.PathLike ? (Func) (p => FileUtilities.NormalizePathForComparisonNoThrow(p, Environment.CurrentDirectory)) : p => p; + _normalize = options == MatchOnMetadataOptions.PathLike ? (Func)(p => FileUtilities.NormalizePathForComparisonNoThrow(p, Environment.CurrentDirectory)) : p => p; foreach (ItemSpec.ItemExpressionFragment frag in itemSpec.Fragments) { foreach (ItemSpec.ReferencedItem referencedItem in frag.ReferencedItems) diff --git a/src/Build/Evaluation/ItemsAndMetadataPair.cs b/src/Build/Evaluation/ItemsAndMetadataPair.cs index 9385d06ddd7..3348d1b1662 100644 --- a/src/Build/Evaluation/ItemsAndMetadataPair.cs +++ b/src/Build/Evaluation/ItemsAndMetadataPair.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Build/Evaluation/LazyItemEvaluator.EvaluatorData.cs b/src/Build/Evaluation/LazyItemEvaluator.EvaluatorData.cs index ecae588cd20..19290e8f921 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.EvaluatorData.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.EvaluatorData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Collections; using System; @@ -17,10 +17,10 @@ namespace Microsoft.Build.Evaluation { internal partial class LazyItemEvaluator { - class EvaluatorData : IEvaluatorData + private class EvaluatorData : IEvaluatorData { - IEvaluatorData _wrappedData; - Func> _itemGetter; + private IEvaluatorData _wrappedData; + private Func> _itemGetter; public EvaluatorData(IEvaluatorData wrappedData, Func> itemGetter) { diff --git a/src/Build/Evaluation/LazyItemEvaluator.IItemOperation.cs b/src/Build/Evaluation/LazyItemEvaluator.IItemOperation.cs index 7d9b469564a..a3fa31f7c78 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.IItemOperation.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.IItemOperation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Immutable; diff --git a/src/Build/Evaluation/LazyItemEvaluator.IncludeOperation.cs b/src/Build/Evaluation/LazyItemEvaluator.IncludeOperation.cs index cbbc06d0cef..4850ef44d0a 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.IncludeOperation.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.IncludeOperation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Eventing; @@ -18,15 +18,12 @@ namespace Microsoft.Build.Evaluation { internal partial class LazyItemEvaluator { - class IncludeOperation : LazyItemOperation + private class IncludeOperation : LazyItemOperation { - readonly int _elementOrder; - - readonly string _rootDirectory; - - readonly ImmutableSegmentedList _excludes; - - readonly ImmutableList _metadata; + private readonly int _elementOrder; + private readonly string _rootDirectory; + private readonly ImmutableSegmentedList _excludes; + private readonly ImmutableList _metadata; public IncludeOperation(IncludeOperationBuilder builder, LazyItemEvaluator lazyEvaluator) : base(builder, lazyEvaluator) @@ -170,7 +167,7 @@ protected override void SaveItems(ImmutableList items, OrderedItemDataCollect } } - class IncludeOperationBuilder : OperationBuilderWithMetadata + private class IncludeOperationBuilder : OperationBuilderWithMetadata { public int ElementOrder { get; set; } public string RootDirectory { get; set; } diff --git a/src/Build/Evaluation/LazyItemEvaluator.ItemFactoryWrapper.cs b/src/Build/Evaluation/LazyItemEvaluator.ItemFactoryWrapper.cs index 9bda1d32cdf..722d467c342 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.ItemFactoryWrapper.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.ItemFactoryWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -12,10 +12,10 @@ namespace Microsoft.Build.Evaluation { internal partial class LazyItemEvaluator { - class ItemFactoryWrapper : IItemFactory + private class ItemFactoryWrapper : IItemFactory { - ProjectItemElement _itemElement; - IItemFactory _wrappedItemFactory; + private ProjectItemElement _itemElement; + private IItemFactory _wrappedItemFactory; public ItemFactoryWrapper(ProjectItemElement itemElement, IItemFactory wrappedItemFactory) { @@ -23,7 +23,7 @@ public ItemFactoryWrapper(ProjectItemElement itemElement, IItemFactory wra _wrappedItemFactory = wrappedItemFactory; } - void SetItemElement() + private void SetItemElement() { _wrappedItemFactory.ItemElement = _itemElement; } diff --git a/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs b/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs index 2e0cf86d90d..9517f7c0542 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.LazyItemOperation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Eventing; @@ -32,7 +32,7 @@ private abstract class LazyItemOperation : IItemOperation // the items and then removes them protected readonly IItemFactory _itemFactory; internal ItemSpec Spec => _itemSpec; - + protected LazyItemOperation(OperationBuilder builder, LazyItemEvaluator lazyEvaluator) { _itemElement = builder.ItemElement; @@ -113,7 +113,7 @@ public ItemBatchingContext(I operationItem, Dictionary capturedItems public IMetadataTable GetMetadataTable() { return CapturedItems == null - ? (IMetadataTable) OperationItem + ? (IMetadataTable)OperationItem : new ItemOperationMetadataTable(OperationItem, CapturedItems); } @@ -255,8 +255,7 @@ protected void DecorateItemsWithMetadata(IEnumerable itemBa metadataExpansionOptions, ParserOptions.AllowAll, _expander, - _lazyEvaluator - )) + _lazyEvaluator)) { continue; } diff --git a/src/Build/Evaluation/LazyItemEvaluator.OrderedItemDataCollection.cs b/src/Build/Evaluation/LazyItemEvaluator.OrderedItemDataCollection.cs index 9459e49067d..ff6e6d700ee 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.OrderedItemDataCollection.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.OrderedItemDataCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -41,7 +41,7 @@ internal Builder(ImmutableList.Builder listBuilder) #region IEnumerable implementation - ImmutableList.Enumerator GetEnumerator() => _listBuilder.GetEnumerator(); + private ImmutableList.Enumerator GetEnumerator() => _listBuilder.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _listBuilder.GetEnumerator(); System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => _listBuilder.GetEnumerator(); diff --git a/src/Build/Evaluation/LazyItemEvaluator.RemoveOperation.cs b/src/Build/Evaluation/LazyItemEvaluator.RemoveOperation.cs index 8fbcc487daa..ddabfcf4e94 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.RemoveOperation.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.RemoveOperation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Framework; @@ -14,9 +14,9 @@ namespace Microsoft.Build.Evaluation { internal partial class LazyItemEvaluator { - class RemoveOperation : LazyItemOperation + private class RemoveOperation : LazyItemOperation { - readonly ImmutableList _matchOnMetadata; + private readonly ImmutableList _matchOnMetadata; private MetadataTrie _metadataSet; public RemoveOperation(RemoveOperationBuilder builder, LazyItemEvaluator lazyEvaluator) @@ -109,7 +109,7 @@ public ImmutableHashSet.Builder GetRemovedGlobs() } } - class RemoveOperationBuilder : OperationBuilder + private class RemoveOperationBuilder : OperationBuilder { public ImmutableList.Builder MatchOnMetadata { get; } = ImmutableList.CreateBuilder(); diff --git a/src/Build/Evaluation/LazyItemEvaluator.UpdateOperation.cs b/src/Build/Evaluation/LazyItemEvaluator.UpdateOperation.cs index 88c299dd571..bddbcaf8150 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.UpdateOperation.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.UpdateOperation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -14,7 +14,7 @@ namespace Microsoft.Build.Evaluation { internal partial class LazyItemEvaluator { - class UpdateOperation : LazyItemOperation + private class UpdateOperation : LazyItemOperation { private readonly ImmutableList _metadata; private ImmutableList.Builder _itemsToUpdate = null; @@ -27,7 +27,7 @@ public UpdateOperation(OperationBuilderWithMetadata builder, LazyItemEvaluator

CapturedItemsFromReferencedItemTypes { get; } @@ -39,7 +39,7 @@ public MatchResult(bool isMatch, Dictionary capturedItemsFromReferenc } } - delegate MatchResult ItemSpecMatchesItem(ItemSpec itemSpec, I itemToMatch); + private delegate MatchResult ItemSpecMatchesItem(ItemSpec itemSpec, I itemToMatch); protected override void ApplyImpl(OrderedItemDataCollection.Builder listBuilder, ImmutableHashSet globsToIgnore) { @@ -169,7 +169,7 @@ private bool QualifiedMetadataReferencesExist(ImmutableList itemSpec) { - return itemSpec.Fragments.Any(f => f is ItemSpec.ItemExpressionFragment); + return itemSpec.Fragments.Any(f => f is ItemSpec.ItemExpressionFragment); } } } diff --git a/src/Build/Evaluation/LazyItemEvaluator.cs b/src/Build/Evaluation/LazyItemEvaluator.cs index cddd1390eda..e02ef565869 100644 --- a/src/Build/Evaluation/LazyItemEvaluator.cs +++ b/src/Build/Evaluation/LazyItemEvaluator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd.Logging; using Microsoft.Build.Collections; @@ -79,8 +79,7 @@ private static bool EvaluateCondition( ExpanderOptions expanderOptions, ParserOptions parserOptions, Expander expander, - LazyItemEvaluator lazyEvaluator - ) + LazyItemEvaluator lazyEvaluator) { if (condition?.Length == 0) { @@ -90,8 +89,7 @@ LazyItemEvaluator lazyEvaluator using (lazyEvaluator._evaluationProfiler.TrackCondition(element.ConditionLocation, condition)) { - bool result = ConditionEvaluator.EvaluateCondition - ( + bool result = ConditionEvaluator.EvaluateCondition( condition, parserOptions, expander, @@ -101,8 +99,7 @@ LazyItemEvaluator lazyEvaluator lazyEvaluator._loggingContext.LoggingService, lazyEvaluator._loggingContext.BuildEventContext, lazyEvaluator.FileSystem, - loggingContext: lazyEvaluator._loggingContext - ); + loggingContext: lazyEvaluator._loggingContext); MSBuildEventSource.Log.EvaluateConditionStop(condition, result); return result; @@ -271,7 +268,9 @@ public ImmutableList GetMatchedItems(ImmutableHashSet globsToIgnore) foreach (ItemData data in GetItemData(globsToIgnore)) { if (data.ConditionResult) + { items.Add(data.Item); + } } return items.ToImmutable(); @@ -475,7 +474,7 @@ private class OperationBuilder public ProjectItemElement ItemElement { get; set; } public string ItemType { get; set; } - public ItemSpec ItemSpec { get; set; } + public ItemSpec ItemSpec { get; set; } public ImmutableDictionary.Builder ReferencedItemLists { get; } = Traits.Instance.EscapeHatches.UseCaseSensitiveItemNames ? ImmutableDictionary.CreateBuilder() : diff --git a/src/Build/Evaluation/MetadataReference.cs b/src/Build/Evaluation/MetadataReference.cs index c0cf9b33319..1c8e3b7b37e 100644 --- a/src/Build/Evaluation/MetadataReference.cs +++ b/src/Build/Evaluation/MetadataReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -28,11 +28,9 @@ internal struct MetadataReference ///

/// Name of the item /// Name of the metadata - internal MetadataReference - ( + internal MetadataReference( string itemName, - string metadataName - ) + string metadataName) { this.ItemName = itemName; this.MetadataName = metadataName; diff --git a/src/Build/Evaluation/Preprocessor.cs b/src/Build/Evaluation/Preprocessor.cs index 7655b5b0faa..0d38472e450 100644 --- a/src/Build/Evaluation/Preprocessor.cs +++ b/src/Build/Evaluation/Preprocessor.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -235,8 +235,7 @@ private void CloneChildrenResolvingImports(XmlNode source, XmlNode destination) child.NodeType == XmlNodeType.Element && sourceDocument.DocumentElement == child && // This is the root element, not some random element named 'Project' destinationDocument.DocumentElement != null && // Skip tag from the outer project - String.Equals(XMakeElements.project, child.Name, StringComparison.Ordinal) - ) + String.Equals(XMakeElements.project, child.Name, StringComparison.Ordinal)) { // But suffix any InitialTargets attribute string outerInitialTargets = destinationDocument.DocumentElement.GetAttribute(XMakeAttributes.initialTargets).Trim(); @@ -283,7 +282,7 @@ private void CloneChildrenResolvingImports(XmlNode source, XmlNode destination) string sdk = importSdk.Length > 0 ? $" {XMakeAttributes.sdk}=\"{importSdk}\"" : String.Empty; // Get the Sdk attribute of the Project element if specified - string projectSdk = source.NodeType == XmlNodeType.Element && String.Equals(XMakeElements.project, source.Name, StringComparison.Ordinal) ? ((XmlElement) source).GetAttribute(XMakeAttributes.sdk) : String.Empty; + string projectSdk = source.NodeType == XmlNodeType.Element && String.Equals(XMakeElements.project, source.Name, StringComparison.Ordinal) ? ((XmlElement)source).GetAttribute(XMakeAttributes.sdk) : String.Empty; IList resolvedList; if (!_importTable.TryGetValue((XmlElement)child, out resolvedList)) diff --git a/src/Build/Evaluation/Profiler/EvaluationLocationMarkdownPrettyPrinter.cs b/src/Build/Evaluation/Profiler/EvaluationLocationMarkdownPrettyPrinter.cs index bdb57bf9566..065f756fede 100644 --- a/src/Build/Evaluation/Profiler/EvaluationLocationMarkdownPrettyPrinter.cs +++ b/src/Build/Evaluation/Profiler/EvaluationLocationMarkdownPrettyPrinter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -41,7 +41,9 @@ protected override string NormalizeExpression(string description, EvaluationLoca text = text.Replace(Separator, "\\" + Separator); if (text.Length > 100) + { text = text.Remove(100) + "..."; + } return '`' + text + '`'; } diff --git a/src/Build/Evaluation/Profiler/EvaluationLocationPrettyPrinterBase.cs b/src/Build/Evaluation/Profiler/EvaluationLocationPrettyPrinterBase.cs index 6a849a6a95d..cdca2c31156 100644 --- a/src/Build/Evaluation/Profiler/EvaluationLocationPrettyPrinterBase.cs +++ b/src/Build/Evaluation/Profiler/EvaluationLocationPrettyPrinterBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/Build/Evaluation/Profiler/EvaluationLocationTabSeparatedPrettyPrinter.cs b/src/Build/Evaluation/Profiler/EvaluationLocationTabSeparatedPrettyPrinter.cs index 71ee33974d9..180d4565c72 100644 --- a/src/Build/Evaluation/Profiler/EvaluationLocationTabSeparatedPrettyPrinter.cs +++ b/src/Build/Evaluation/Profiler/EvaluationLocationTabSeparatedPrettyPrinter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/Build/Evaluation/Profiler/EvaluationProfiler.cs b/src/Build/Evaluation/Profiler/EvaluationProfiler.cs index bc7adaf312e..6f1385f421a 100644 --- a/src/Build/Evaluation/Profiler/EvaluationProfiler.cs +++ b/src/Build/Evaluation/Profiler/EvaluationProfiler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -145,12 +145,11 @@ public void Dispose() { previousTimeSpent = new ProfiledLocation(TimeSpan.Zero, TimeSpan.Zero, 0); } - + var updatedTimeSpent = new ProfiledLocation( previousTimeSpent.InclusiveTime + _inclusiveTime.Elapsed, previousTimeSpent.ExclusiveTime + _exclusiveTime.Elapsed, - 0 - ); + 0); _evaluationProfiler._timeSpent[Location] = updatedTimeSpent; } diff --git a/src/Build/Evaluation/Profiler/ProfilerResultPrettyPrinter.cs b/src/Build/Evaluation/Profiler/ProfilerResultPrettyPrinter.cs index bdc3a95ee28..edb38453997 100644 --- a/src/Build/Evaluation/Profiler/ProfilerResultPrettyPrinter.cs +++ b/src/Build/Evaluation/Profiler/ProfilerResultPrettyPrinter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Evaluation/ProjectChangedEventArgs.cs b/src/Build/Evaluation/ProjectChangedEventArgs.cs index 943697e432f..22b38271a1c 100644 --- a/src/Build/Evaluation/ProjectChangedEventArgs.cs +++ b/src/Build/Evaluation/ProjectChangedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; diff --git a/src/Build/Evaluation/ProjectParser.cs b/src/Build/Evaluation/ProjectParser.cs index fd9f087f7a9..9c38f01f962 100644 --- a/src/Build/Evaluation/ProjectParser.cs +++ b/src/Build/Evaluation/ProjectParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Eventing; using Microsoft.Build.Framework; @@ -427,14 +427,12 @@ private ProjectImportGroupElement ParseProjectImportGroupElement(XmlElementWithL foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( childElement.Name == XMakeElements.import, childElement.Location, "UnrecognizedChildElement", childElement.Name, - element.Name - ); + element.Name); ProjectImportElement item = ParseProjectImportElement(childElement, importGroup); @@ -449,14 +447,12 @@ private ProjectImportGroupElement ParseProjectImportGroupElement(XmlElementWithL ///
private ProjectImportElement ParseProjectImportElement(XmlElementWithLocation element, ProjectElementContainer parent) { - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( parent is ProjectRootElement || parent is ProjectImportGroupElement, element.Location, "UnrecognizedParentElement", parent, - element - ); + element); ProjectXmlUtilities.VerifyThrowProjectAttributes(element, ValidAttributesOnImport); ProjectXmlUtilities.VerifyThrowProjectRequiredAttribute(element, XMakeAttributes.project); @@ -518,15 +514,13 @@ private ProjectUsingTaskElement ParseProjectUsingTaskElement(XmlElementWithLocat string assemblyName = element.GetAttribute(XMakeAttributes.assemblyName); string assemblyFile = element.GetAttribute(XMakeAttributes.assemblyFile); - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( (assemblyName.Length > 0) ^ (assemblyFile.Length > 0), element.Location, "UsingTaskAssemblySpecification", XMakeElements.usingTask, XMakeAttributes.assemblyName, - XMakeAttributes.assemblyFile - ); + XMakeAttributes.assemblyFile); ProjectXmlUtilities.VerifyThrowProjectAttributeEitherMissingOrNotEmpty(element, XMakeAttributes.assemblyName); ProjectXmlUtilities.VerifyThrowProjectAttributeEitherMissingOrNotEmpty(element, XMakeAttributes.assemblyFile); @@ -635,7 +629,7 @@ private ProjectTargetElement ParseProjectTargetElement(XmlElementWithLocation el if (onError != null) { ProjectErrorUtilities.ThrowInvalidProject(onError.Location, "NodeMustBeLastUnderElement", XMakeElements.onError, XMakeElements.target, childElement.Name); - } + } if (ChangeWaves.AreFeaturesEnabled(ChangeWaves.Wave17_6)) { if (childElement.ChildNodes.Count == 1 && childElement.FirstChild.NodeType == XmlNodeType.Text) @@ -662,15 +656,13 @@ private ProjectTaskElement ParseProjectTaskElement(XmlElementWithLocation elemen { foreach (XmlAttributeWithLocation attribute in element.Attributes) { - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( !XMakeAttributes.IsBadlyCasedSpecialTaskAttribute(attribute.Name), attribute.Location, "BadlyCasedSpecialTaskAttribute", attribute.Name, element.Name, - element.Name - ); + element.Name); } ProjectTaskElement task = new ProjectTaskElement(element, parent, _project); @@ -699,13 +691,11 @@ private ProjectOutputElement ParseProjectOutputElement(XmlElementWithLocation el XmlAttributeWithLocation itemNameAttribute = element.GetAttributeWithLocation(XMakeAttributes.itemName); XmlAttributeWithLocation propertyNameAttribute = element.GetAttributeWithLocation(XMakeAttributes.propertyName); - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( (String.IsNullOrWhiteSpace(itemNameAttribute?.Value) && !String.IsNullOrWhiteSpace(propertyNameAttribute?.Value)) || (!String.IsNullOrWhiteSpace(itemNameAttribute?.Value) && String.IsNullOrWhiteSpace(propertyNameAttribute?.Value)), element.Location, "InvalidTaskOutputSpecification", - parent.Name - ); + parent.Name); ProjectXmlUtilities.VerifyThrowProjectAttributeEitherMissingOrNotEmpty(element, itemNameAttribute, XMakeAttributes.itemName); ProjectXmlUtilities.VerifyThrowProjectAttributeEitherMissingOrNotEmpty(element, propertyNameAttribute, XMakeAttributes.propertyName); diff --git a/src/Build/Evaluation/ProjectRootElementCache.cs b/src/Build/Evaluation/ProjectRootElementCache.cs index 208a43ed668..beb1d86e13e 100644 --- a/src/Build/Evaluation/ProjectRootElementCache.cs +++ b/src/Build/Evaluation/ProjectRootElementCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -215,11 +215,12 @@ internal override ProjectRootElement Get(string projectFile, OpenProjectRootElem s_getEntriesNumber++; ErrorUtilities.VerifyThrow( s_getEntriesNumber == 1, - "Reentrance to the ProjectRootElementCache.Get function detected." - ); + "Reentrance to the ProjectRootElementCache.Get function detected."); - try { + try + { #endif +#pragma warning disable format // the release configuration fails as try-catch block is conditioned only for Debug; making the formatting in correct in Release. // Should already have been canonicalized ErrorUtilities.VerifyThrowInternalRooted(projectFile); @@ -283,8 +284,7 @@ internal override ProjectRootElement Get(string projectFile, OpenProjectRootElem projectRootElement.FullPath.Equals(projectFile, StringComparison.OrdinalIgnoreCase), "Got project back with incorrect path. Expected path: {0}, received path: {1}.", projectFile, - projectRootElement.FullPath - ); + projectRootElement.FullPath); // An implicit load will never reset the explicit flag. if (isExplicitlyLoaded) @@ -303,8 +303,8 @@ internal override ProjectRootElement Get(string projectFile, OpenProjectRootElem DebugTraceCache("Satisfied from XML cache: ", projectFile); } - return projectRootElement; +#pragma warning restore format #if DEBUG } finally diff --git a/src/Build/Evaluation/ProjectRootElementCacheBase.cs b/src/Build/Evaluation/ProjectRootElementCacheBase.cs index 69f0fe3137c..97857fa0b6e 100644 --- a/src/Build/Evaluation/ProjectRootElementCacheBase.cs +++ b/src/Build/Evaluation/ProjectRootElementCacheBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Construction; diff --git a/src/Build/Evaluation/ProjectStringCache.cs b/src/Build/Evaluation/ProjectStringCache.cs index 92d0f42062e..f6fdd3733b0 100644 --- a/src/Build/Evaluation/ProjectStringCache.cs +++ b/src/Build/Evaluation/ProjectStringCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Evaluation/ProjectXmlChangedEventArgs.cs b/src/Build/Evaluation/ProjectXmlChangedEventArgs.cs index 135c97beb40..63b78917f24 100644 --- a/src/Build/Evaluation/ProjectXmlChangedEventArgs.cs +++ b/src/Build/Evaluation/ProjectXmlChangedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Build/Evaluation/PropertyTrackingEvaluatorDataWrapper.cs b/src/Build/Evaluation/PropertyTrackingEvaluatorDataWrapper.cs index b113e73a6ec..08ddb45cd60 100644 --- a/src/Build/Evaluation/PropertyTrackingEvaluatorDataWrapper.cs +++ b/src/Build/Evaluation/PropertyTrackingEvaluatorDataWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; @@ -165,7 +165,10 @@ private void TrackPropertyRead(string name, P property) // MSBuild looks up a property called "InnerBuildProperty". If that isn't present, // an empty string is returned and it then attempts to look up the value for that property // (which is an empty string). Thus this check. - if (string.IsNullOrEmpty(name)) return; + if (string.IsNullOrEmpty(name)) + { + return; + } // If a property matches the name of an environment variable, but has NOT been overwritten by a non-environment-variable property // track it as an environment variable read. @@ -185,7 +188,10 @@ private void TrackPropertyRead(string name, P property) /// The name of the environment variable read. private void TrackEnvironmentVariableRead(string name) { - if ((_settings & PropertyTrackingSetting.EnvironmentVariableRead) != PropertyTrackingSetting.EnvironmentVariableRead) return; + if ((_settings & PropertyTrackingSetting.EnvironmentVariableRead) != PropertyTrackingSetting.EnvironmentVariableRead) + { + return; + } var args = new EnvironmentVariableReadEventArgs( name, @@ -201,7 +207,10 @@ private void TrackEnvironmentVariableRead(string name) /// The name of the uninitialized property read. private void TrackUninitializedPropertyRead(string name) { - if ((_settings & PropertyTrackingSetting.UninitializedPropertyRead) != PropertyTrackingSetting.UninitializedPropertyRead) return; + if ((_settings & PropertyTrackingSetting.UninitializedPropertyRead) != PropertyTrackingSetting.UninitializedPropertyRead) + { + return; + } var args = new UninitializedPropertyReadEventArgs( name, @@ -240,14 +249,16 @@ private void TrackPropertyWrite(P predecessor, P property, string location, Prop /// The source of the property. private void TrackPropertyInitialValueSet(P property, PropertySource source) { - if ((_settings & PropertyTrackingSetting.PropertyInitialValueSet) != PropertyTrackingSetting.PropertyInitialValueSet) return; + if ((_settings & PropertyTrackingSetting.PropertyInitialValueSet) != PropertyTrackingSetting.PropertyInitialValueSet) + { + return; + } var args = new PropertyInitialValueSetEventArgs( property.Name, property.EvaluatedValue, source.ToString(), - ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("PropertyAssignment", property.Name, property.EvaluatedValue, source) - ); + ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("PropertyAssignment", property.Name, property.EvaluatedValue, source)); args.BuildEventContext = _evaluationLoggingContext.BuildEventContext; _evaluationLoggingContext.LogBuildEvent(args); diff --git a/src/Build/Evaluation/SemiColonTokenizer.cs b/src/Build/Evaluation/SemiColonTokenizer.cs index b5e9eadba70..6d00f63dff7 100644 --- a/src/Build/Evaluation/SemiColonTokenizer.cs +++ b/src/Build/Evaluation/SemiColonTokenizer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Evaluation/SimpleProjectRootElementCache.cs b/src/Build/Evaluation/SimpleProjectRootElementCache.cs index a5cb9278e33..f359d3cbd07 100644 --- a/src/Build/Evaluation/SimpleProjectRootElementCache.cs +++ b/src/Build/Evaluation/SimpleProjectRootElementCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -67,8 +67,7 @@ private ProjectRootElement GetFromOrAddToCache(string projectFile, OpenProjectRo rootElement.FullPath.Equals(key, StringComparison.OrdinalIgnoreCase), "Got project back with incorrect path. Expected path: {0}, received path: {1}.", key, - rootElement.FullPath - ); + rootElement.FullPath); AddEntry(rootElement); @@ -143,7 +142,7 @@ internal override void OnProjectDirtied(Project sender, ProjectChangedEventArgs protected override void RaiseProjectRootElementRemovedFromStrongCache(ProjectRootElement projectRootElement) { - throw new NotImplementedException(); + throw new NotImplementedException(); } } } diff --git a/src/Build/Evaluation/StringMetadataTable.cs b/src/Build/Evaluation/StringMetadataTable.cs index 0b2001450ea..0b0dd6b4e45 100644 --- a/src/Build/Evaluation/StringMetadataTable.cs +++ b/src/Build/Evaluation/StringMetadataTable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Evaluation/ToolsetProvider.cs b/src/Build/Evaluation/ToolsetProvider.cs index a9d1ad339e6..9309c78af57 100644 --- a/src/Build/Evaluation/ToolsetProvider.cs +++ b/src/Build/Evaluation/ToolsetProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/FileSystem/DirectoryCacheFileSystemWrapper.cs b/src/Build/FileSystem/DirectoryCacheFileSystemWrapper.cs index 71b55892b1c..d4b6a316964 100644 --- a/src/Build/FileSystem/DirectoryCacheFileSystemWrapper.cs +++ b/src/Build/FileSystem/DirectoryCacheFileSystemWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Microsoft.Build.Shared.FileSystem; @@ -103,9 +103,9 @@ private IEnumerable EnumerateFullFileSystemPaths(string path, string sea return Enumerable.Concat(directories, files); } -#endregion + #endregion -#region IFileSystem pass-through implementation + #region IFileSystem pass-through implementation public FileAttributes GetAttributes(string path) => _fileSystem.GetAttributes(path); @@ -119,6 +119,6 @@ private IEnumerable EnumerateFullFileSystemPaths(string path, string sea public byte[] ReadFileAllBytes(string path) => _fileSystem.ReadFileAllBytes(path); -#endregion + #endregion } } diff --git a/src/Build/FileSystem/IDirectoryCache.cs b/src/Build/FileSystem/IDirectoryCache.cs index 428cd3159e0..6cbecefbb6a 100644 --- a/src/Build/FileSystem/IDirectoryCache.cs +++ b/src/Build/FileSystem/IDirectoryCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/FileSystem/MSBuildFileSystemBase.cs b/src/Build/FileSystem/MSBuildFileSystemBase.cs index d007f600c23..a6be85df301 100644 --- a/src/Build/FileSystem/MSBuildFileSystemBase.cs +++ b/src/Build/FileSystem/MSBuildFileSystemBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared.FileSystem; using System; diff --git a/src/Build/Globbing/CompositeGlob.cs b/src/Build/Globbing/CompositeGlob.cs index b1dabb12741..546c590afd9 100644 --- a/src/Build/Globbing/CompositeGlob.cs +++ b/src/Build/Globbing/CompositeGlob.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -30,7 +30,7 @@ public class CompositeGlob : IMSBuildGlob /// Children globs. Input gets shallow cloned public CompositeGlob(IEnumerable globs) : this(globs.ToImmutableArray()) - {} + { } /// /// Constructor @@ -38,7 +38,7 @@ public CompositeGlob(IEnumerable globs) /// Children globs. Input gets shallow cloned public CompositeGlob(params IMSBuildGlob[] globs) : this(ImmutableArray.Create(globs)) - {} + { } /// /// Constructor @@ -47,7 +47,7 @@ public CompositeGlob(params IMSBuildGlob[] globs) /// Second child glob. internal CompositeGlob(IMSBuildGlob glob1, IMSBuildGlob glob2) : this(ImmutableArray.Create(glob1, glob2)) - {} + { } /// /// Constructor diff --git a/src/Build/Globbing/Extensions/MSBuildGlobExtensions.cs b/src/Build/Globbing/Extensions/MSBuildGlobExtensions.cs index 28623b14545..32f31bbe874 100644 --- a/src/Build/Globbing/Extensions/MSBuildGlobExtensions.cs +++ b/src/Build/Globbing/Extensions/MSBuildGlobExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Globbing.Visitor; diff --git a/src/Build/Globbing/IMSBuildGlob.cs b/src/Build/Globbing/IMSBuildGlob.cs index 59a683ace91..a101b9541de 100644 --- a/src/Build/Globbing/IMSBuildGlob.cs +++ b/src/Build/Globbing/IMSBuildGlob.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Globbing/MSBuildGlob.cs b/src/Build/Globbing/MSBuildGlob.cs index 92464daafd4..44fb19d4ab3 100644 --- a/src/Build/Globbing/MSBuildGlob.cs +++ b/src/Build/Globbing/MSBuildGlob.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Build/Globbing/MSBuildGlobWithGaps.cs b/src/Build/Globbing/MSBuildGlobWithGaps.cs index 5126a13744c..442000b8a46 100644 --- a/src/Build/Globbing/MSBuildGlobWithGaps.cs +++ b/src/Build/Globbing/MSBuildGlobWithGaps.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; @@ -68,7 +68,7 @@ public MSBuildGlobWithGaps(IMSBuildGlob mainGlob, IEnumerable gaps /// The main glob /// The gap glob public MSBuildGlobWithGaps(IMSBuildGlob mainGlob, params IMSBuildGlob[] gaps) : this(mainGlob, gaps.AsEnumerable()) - {} + { } /// public bool IsMatch(string stringToMatch) diff --git a/src/Build/Globbing/Visitor/GlobVisitor.cs b/src/Build/Globbing/Visitor/GlobVisitor.cs index aaae9a6d5c9..bd9c43623d9 100644 --- a/src/Build/Globbing/Visitor/GlobVisitor.cs +++ b/src/Build/Globbing/Visitor/GlobVisitor.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Globbing/Visitor/ParsedGlobCollector.cs b/src/Build/Globbing/Visitor/ParsedGlobCollector.cs index 76f85bb2d9c..79b519ca594 100644 --- a/src/Build/Globbing/Visitor/ParsedGlobCollector.cs +++ b/src/Build/Globbing/Visitor/ParsedGlobCollector.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System.Collections.Immutable; #nullable disable diff --git a/src/Build/Graph/GraphBuildRequestData.cs b/src/Build/Graph/GraphBuildRequestData.cs index 1477b097b63..c09a587b106 100644 --- a/src/Build/Graph/GraphBuildRequestData.cs +++ b/src/Build/Graph/GraphBuildRequestData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Execution; diff --git a/src/Build/Graph/GraphBuildResult.cs b/src/Build/Graph/GraphBuildResult.cs index 8ed172972e0..6df04a0c899 100644 --- a/src/Build/Graph/GraphBuildResult.cs +++ b/src/Build/Graph/GraphBuildResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Graph/GraphBuildSubmission.cs b/src/Build/Graph/GraphBuildSubmission.cs index 9da8e4e97bb..9c00b5bb0e4 100644 --- a/src/Build/Graph/GraphBuildSubmission.cs +++ b/src/Build/Graph/GraphBuildSubmission.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Build/Graph/GraphBuilder.cs b/src/Build/Graph/GraphBuilder.cs index 776514e4d7d..a226c96acdf 100644 --- a/src/Build/Graph/GraphBuilder.cs +++ b/src/Build/Graph/GraphBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -23,7 +23,7 @@ namespace Microsoft.Build.Graph internal class GraphBuilder { internal const string SolutionItemReference = "_SolutionReference"; - + /// /// The thread calling BuildGraph() will act as an implicit worker /// @@ -61,7 +61,7 @@ public GraphBuilder( _solutionDependencies = solutionDependencies; _entryPointConfigurationMetadata = AddGraphBuildPropertyToEntryPoints(actualEntryPoints); - + IEqualityComparer configComparer = EqualityComparer.Default; _graphWorkSet = new ParallelWorkSet( @@ -82,7 +82,7 @@ public void BuildGraph() } var allParsedProjects = FindGraphNodes(); - + AddEdges(allParsedProjects); EntryPointNodes = _entryPointConfigurationMetadata.Select(e => allParsedProjects[e].GraphNode).ToList(); @@ -154,8 +154,7 @@ private void AddEdgesFromProjectReferenceItems(Dictionary {project.Value.GraphNode}; + projectsByPath[projectPath] = new List { project.Value.GraphNode }; } } @@ -295,8 +294,7 @@ private static void AddEdgesFromSolution(IReadOnlyDictionary {node.ProjectInstance.FullPath, node.ProjectInstance.FullPath}); + FormatCircularDependencyError(new List { node.ProjectInstance.FullPath, node.ProjectInstance.FullPath }); throw new CircularDependencyException( string.Format( ResourceUtilities.GetResourceString("CircularDependencyInProjectGraph"), @@ -459,7 +457,7 @@ private void DetectCycles( // the project being evaluated has a circular dependency involving multiple projects // add this project to the list of projects involved in cycle - var projectsInCycle = new List {referenceNode.ProjectInstance.FullPath}; + var projectsInCycle = new List { referenceNode.ProjectInstance.FullPath }; return (false, projectsInCycle); } } @@ -527,10 +525,10 @@ private Dictionary FindGraphNodes() foreach (ConfigurationMetadata projectToEvaluate in _entryPointConfigurationMetadata) { SubmitProjectForParsing(projectToEvaluate); - /*todo: fix the following double check-then-act concurrency bug: one thread can pass the two checks, loose context, - meanwhile another thread passes the same checks with the same data and inserts its reference. The initial thread regains context - and duplicates the information, leading to wasted work - */ + /*todo: fix the following double check-then-act concurrency bug: one thread can pass the two checks, loose context, + meanwhile another thread passes the same checks with the same data and inserts its reference. The initial thread regains context + and duplicates the information, leading to wasted work + */ } _graphWorkSet.WaitForAllWorkAndComplete(); @@ -546,7 +544,7 @@ private void SubmitProjectForParsing(ConfigurationMetadata projectToEvaluate) private List ParseReferences(ProjectGraphNode parsedProject) { var referenceInfos = new List(); - + foreach (var referenceInfo in _projectInterpretation.GetReferences(parsedProject.ProjectInstance, _projectCollection, _projectInstanceFactory)) { @@ -555,10 +553,9 @@ private void SubmitProjectForParsing(ConfigurationMetadata projectToEvaluate) throw new InvalidOperationException(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword( "StaticGraphDoesNotSupportSlnReferences", referenceInfo.ReferenceConfiguration.ProjectFullPath, - referenceInfo.ReferenceConfiguration.ProjectFullPath - )); + referenceInfo.ReferenceConfiguration.ProjectFullPath)); } - + SubmitProjectForParsing(referenceInfo.ReferenceConfiguration); referenceInfos.Add(referenceInfo); @@ -670,8 +667,7 @@ public void RemoveEdge((ProjectGraphNode node, ProjectGraphNode reference) key) { return ReferenceItems.ToImmutableDictionary( kvp => (kvp.Key.Item1.ToConfigurationMetadata(), kvp.Key.Item2.ToConfigurationMetadata()), - kvp => kvp.Value - ); + kvp => kvp.Value); } } diff --git a/src/Build/Graph/ParallelWorkSet.cs b/src/Build/Graph/ParallelWorkSet.cs index 922d29fd39f..ed4ecb41537 100644 --- a/src/Build/Graph/ParallelWorkSet.cs +++ b/src/Build/Graph/ParallelWorkSet.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Build/Graph/ProjectGraph.cs b/src/Build/Graph/ProjectGraph.cs index b64b17cee58..1e1248865be 100644 --- a/src/Build/Graph/ProjectGraph.cs +++ b/src/Build/Graph/ProjectGraph.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -484,8 +484,7 @@ internal string ToDot(IReadOnlyDictionary nodeIdProvider, - IReadOnlyDictionary> targetsPerNode = null - ) + IReadOnlyDictionary> targetsPerNode = null) { ErrorUtilities.VerifyThrowArgumentNull(nodeIdProvider, nameof(nodeIdProvider)); diff --git a/src/Build/Graph/ProjectGraphEntryPoint.cs b/src/Build/Graph/ProjectGraphEntryPoint.cs index 6cda6173ac7..8e229b7bd61 100644 --- a/src/Build/Graph/ProjectGraphEntryPoint.cs +++ b/src/Build/Graph/ProjectGraphEntryPoint.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Shared; diff --git a/src/Build/Graph/ProjectGraphNode.cs b/src/Build/Graph/ProjectGraphNode.cs index 802378358f5..bb14d663c84 100644 --- a/src/Build/Graph/ProjectGraphNode.cs +++ b/src/Build/Graph/ProjectGraphNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Build/Graph/ProjectInterpretation.cs b/src/Build/Graph/ProjectInterpretation.cs index a293483551b..35b57e90b01 100644 --- a/src/Build/Graph/ProjectInterpretation.cs +++ b/src/Build/Graph/ProjectInterpretation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -233,8 +233,7 @@ private static IEnumerable ConstructInnerBuildReferences(Pr /// private static GlobalPropertyPartsForMSBuildTask ProjectReferenceGlobalPropertiesModifier( GlobalPropertyPartsForMSBuildTask defaultParts, - ProjectItemInstance projectReference - ) + ProjectItemInstance projectReference) { // ProjectReference defines yet another metadata name containing properties to undefine. Merge it in if non empty. var globalPropertiesToRemove = SplitPropertyNames(projectReference.GetMetadataValue(GlobalPropertiesToRemoveMetadataName)); @@ -294,7 +293,7 @@ public GlobalPropertyPartsForMSBuildTask AddPropertyToUndefine(string propertyTo } } - delegate GlobalPropertyPartsForMSBuildTask GlobalPropertiesModifier(GlobalPropertyPartsForMSBuildTask defaultParts, ProjectItemInstance projectReference); + private delegate GlobalPropertyPartsForMSBuildTask GlobalPropertiesModifier(GlobalPropertyPartsForMSBuildTask defaultParts, ProjectItemInstance projectReference); /// /// Gets the effective global properties for an item that will get passed to . diff --git a/src/Build/Instance/HostObjectException.cs b/src/Build/Instance/HostObjectException.cs index 14f8fecb9d6..a38d07726c0 100644 --- a/src/Build/Instance/HostObjectException.cs +++ b/src/Build/Instance/HostObjectException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -21,10 +21,8 @@ internal HostObjectException() : base() /// /// Creates an instance of this exception using the given message. /// - internal HostObjectException - ( - string message - ) : + internal HostObjectException( + string message) : base(ErrorMessagePrefix + message) { } @@ -34,13 +32,11 @@ string message /// Adds the inner exception's details to the exception message because most bug reporters don't bother /// to provide the inner exception details which is typically what we care about. /// - internal HostObjectException - ( + internal HostObjectException( string projectFile, string targetName, string taskName, - Exception innerException - ) : + Exception innerException) : base(ErrorMessagePrefix + string.Format(ErrorMessageProjectTargetTask, projectFile, targetName, taskName) + (innerException == null ? string.Empty : ("\n=============\n" + innerException.ToString() + "\n\n")), @@ -51,13 +47,11 @@ Exception innerException /// /// Creates an instance of this exception using projectFile, targetName, taskName and message. /// - internal HostObjectException - ( + internal HostObjectException( string projectFile, string targetName, string taskName, - string message - ) : + string message) : base(ErrorMessagePrefix + string.Format(ErrorMessageProjectTargetTask, projectFile, targetName, taskName) + message) { diff --git a/src/Build/Instance/HostServices.cs b/src/Build/Instance/HostServices.cs index 76a28c6c8fd..3bd49e0fe24 100644 --- a/src/Build/Instance/HostServices.cs +++ b/src/Build/Instance/HostServices.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Microsoft.Build.Framework; @@ -123,14 +123,14 @@ public ITaskHost GetHostObject(string projectFile, string targetName, string tas public void RegisterHostObject(string projectFile, string targetName, string taskName, ITaskHost hostObject) { -/* Unmerged change from project 'Microsoft.Build (netcoreapp2.1)' -Before: - ErrorUtilities.VerifyThrowArgumentNull(projectFile, "projectFile"); - ErrorUtilities.VerifyThrowArgumentNull(targetName, "targetName"); -After: - ErrorUtilities.VerifyThrowArgumentNull(projectFile, "projectFile)); - ErrorUtilities.VerifyThrowArgumentNull(targetName, "targetName)); -*/ + /* Unmerged change from project 'Microsoft.Build (netcoreapp2.1)' + Before: + ErrorUtilities.VerifyThrowArgumentNull(projectFile, "projectFile"); + ErrorUtilities.VerifyThrowArgumentNull(targetName, "targetName"); + After: + ErrorUtilities.VerifyThrowArgumentNull(projectFile, "projectFile)); + ErrorUtilities.VerifyThrowArgumentNull(targetName, "targetName)); + */ ErrorUtilities.VerifyThrowArgumentNull(projectFile, nameof(projectFile)); ErrorUtilities.VerifyThrowArgumentNull(targetName, nameof(targetName)); ErrorUtilities.VerifyThrowArgumentNull(taskName, nameof(taskName)); diff --git a/src/Build/Instance/IRunningObjectTableWrapper.cs b/src/Build/Instance/IRunningObjectTableWrapper.cs index 8007fa47c4a..33ef3afeada 100644 --- a/src/Build/Instance/IRunningObjectTableWrapper.cs +++ b/src/Build/Instance/IRunningObjectTableWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Build/Instance/ProjectInstance.cs b/src/Build/Instance/ProjectInstance.cs index d3cb5c170a7..763a09442b3 100644 --- a/src/Build/Instance/ProjectInstance.cs +++ b/src/Build/Instance/ProjectInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -1680,7 +1680,9 @@ public IEnumerable GetItemsByItemTypeAndEvaluatedInclude(st foreach (var item in GetItems(itemType)) { if (string.Equals(item.EvaluatedInclude, evaluatedInclude, StringComparison.OrdinalIgnoreCase)) + { yield return item; + } } } else @@ -1688,7 +1690,9 @@ public IEnumerable GetItemsByItemTypeAndEvaluatedInclude(st foreach (var item in GetItemsByEvaluatedInclude(evaluatedInclude)) { if (string.Equals(item.ItemType, itemType, StringComparison.OrdinalIgnoreCase)) + { yield return item; + } } } } @@ -2233,8 +2237,7 @@ internal static ProjectInstance[] LoadSolutionForBuild( if ( String.Equals(toolsVersion, "2.0", StringComparison.OrdinalIgnoreCase) || String.Equals(toolsVersion, "3.0", StringComparison.OrdinalIgnoreCase) || - String.Equals(toolsVersion, "3.5", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(toolsVersion, "3.5", StringComparison.OrdinalIgnoreCase)) { // Spawn the Orcas SolutionWrapperProject generator. loggingService.LogComment(projectBuildEventContext, MessageImportance.Low, "OldWrapperGeneratedExplicitToolsVersion", toolsVersion); @@ -2450,8 +2453,7 @@ internal ProjectTargetInstance AddTarget( ErrorUtilities.VerifyThrowInternalLength(targetName, nameof(targetName)); ErrorUtilities.VerifyThrow(!_actualTargets.ContainsKey(targetName), "Target {0} already exists.", targetName); - ProjectTargetInstance target = new ProjectTargetInstance - ( + ProjectTargetInstance target = new ProjectTargetInstance( targetName, condition ?? String.Empty, inputs ?? String.Empty, @@ -2472,8 +2474,7 @@ internal ProjectTargetInstance AddTarget( String.IsNullOrEmpty(afterTargets) ? null : ElementLocation.EmptyLocation, new ObjectModel.ReadOnlyCollection(new List()), new ObjectModel.ReadOnlyCollection(new List()), - parentProjectSupportsReturnsAttribute - ); + parentProjectSupportsReturnsAttribute); _actualTargets[targetName] = target; @@ -2511,9 +2512,8 @@ internal void VerifyThrowNotImmutable() /// /// /// The ProjectRootElement for the root traversal and each of the metaprojects. - private static ProjectInstance[] GenerateSolutionWrapper + private static ProjectInstance[] GenerateSolutionWrapper( - ( string projectFile, IDictionary globalProperties, string toolsVersion, @@ -2521,8 +2521,7 @@ private static ProjectInstance[] GenerateSolutionWrapper BuildEventContext projectBuildEventContext, IReadOnlyCollection targetNames, ISdkResolverService sdkResolverService, - int submissionId - ) + int submissionId) { SolutionFile sp = SolutionFile.Parse(projectFile); @@ -2566,8 +2565,8 @@ int submissionId /// /// An appropriate ProjectRootElement [MethodImpl(MethodImplOptions.NoInlining)] - private static ProjectInstance[] GenerateSolutionWrapperUsingOldOM - (string projectFile, + private static ProjectInstance[] GenerateSolutionWrapperUsingOldOM( + string projectFile, IDictionary globalProperties, string toolsVersion, ProjectRootElementCacheBase projectRootElementCache, @@ -2599,8 +2598,7 @@ private static ProjectInstance[] GenerateSolutionWrapperUsingOldOM if (environmentVariableName != null && (!XmlUtilities.IsValidElementName(environmentVariableName) || XMakeElements.ReservedItemNames.Contains(environmentVariableName) - || ReservedPropertyNames.IsReservedProperty(environmentVariableName)) - ) + || ReservedPropertyNames.IsReservedProperty(environmentVariableName))) { if (clearedVariables == null) { @@ -2724,14 +2722,12 @@ private void Initialize( toolsVersionLocation = xml.ToolsVersionLocation; } - var toolsVersionToUse = Utilities.GenerateToolsVersionToUse - ( + var toolsVersionToUse = Utilities.GenerateToolsVersionToUse( explicitToolsVersion, xml.ToolsVersion, buildParameters.GetToolset, buildParameters.DefaultToolsVersion, - out var usingDifferentToolsVersionFromProjectFile - ); + out var usingDifferentToolsVersionFromProjectFile); _usingDifferentToolsVersionFromProjectFile = usingDifferentToolsVersionFromProjectFile; diff --git a/src/Build/Instance/ProjectItemDefinitionInstance.cs b/src/Build/Instance/ProjectItemDefinitionInstance.cs index 8c9c1f0f26c..9bde7d2db83 100644 --- a/src/Build/Instance/ProjectItemDefinitionInstance.cs +++ b/src/Build/Instance/ProjectItemDefinitionInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -231,7 +231,7 @@ void ITranslatable.Translate(ITranslator translator) internal static ProjectItemDefinitionInstance FactoryForDeserialization(ITranslator translator) { var instance = new ProjectItemDefinitionInstance(); - ((ITranslatable) instance).Translate(translator); + ((ITranslatable)instance).Translate(translator); return instance; } diff --git a/src/Build/Instance/ProjectItemGroupTaskInstance.cs b/src/Build/Instance/ProjectItemGroupTaskInstance.cs index 8473f7559b5..6166df3ed20 100644 --- a/src/Build/Instance/ProjectItemGroupTaskInstance.cs +++ b/src/Build/Instance/ProjectItemGroupTaskInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; @@ -45,13 +45,11 @@ public class ProjectItemGroupTaskInstance : ProjectTargetInstanceChild, ITransla /// Constructor called by the Evaluator. /// Assumes ProjectItemGroupTaskItemInstance is an immutable type. /// - internal ProjectItemGroupTaskInstance - ( + internal ProjectItemGroupTaskInstance( string condition, ElementLocation location, ElementLocation conditionLocation, - List items - ) + List items) { ErrorUtilities.VerifyThrowInternalNull(condition, nameof(condition)); ErrorUtilities.VerifyThrowInternalNull(location, nameof(location)); diff --git a/src/Build/Instance/ProjectItemGroupTaskItemInstance.cs b/src/Build/Instance/ProjectItemGroupTaskItemInstance.cs index 2a984755992..e48abcebe21 100644 --- a/src/Build/Instance/ProjectItemGroupTaskItemInstance.cs +++ b/src/Build/Instance/ProjectItemGroupTaskItemInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; @@ -137,8 +137,7 @@ public class ProjectItemGroupTaskItemInstance : ITranslatable /// Metadata collection is ordered. /// Assumes ProjectItemGroupTaskMetadataInstance is an immutable type. /// - internal ProjectItemGroupTaskItemInstance - ( + internal ProjectItemGroupTaskItemInstance( string itemType, string include, string exclude, @@ -159,8 +158,7 @@ internal ProjectItemGroupTaskItemInstance ElementLocation removeMetadataLocation, ElementLocation keepDuplicatesLocation, ElementLocation conditionLocation, - List metadata - ) + List metadata) { ErrorUtilities.VerifyThrowInternalNull(itemType, nameof(itemType)); ErrorUtilities.VerifyThrowInternalNull(include, nameof(include)); diff --git a/src/Build/Instance/ProjectItemGroupTaskMetadataInstance.cs b/src/Build/Instance/ProjectItemGroupTaskMetadataInstance.cs index 4ee2e3a30a0..6c0a2915eff 100644 --- a/src/Build/Instance/ProjectItemGroupTaskMetadataInstance.cs +++ b/src/Build/Instance/ProjectItemGroupTaskMetadataInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.BackEnd; @@ -145,7 +145,7 @@ void ITranslatable.Translate(ITranslator translator) internal static ProjectItemGroupTaskMetadataInstance FactoryForDeserialization(ITranslator translator) { var instance = new ProjectItemGroupTaskMetadataInstance(); - ((ITranslatable) instance).Translate(translator); + ((ITranslatable)instance).Translate(translator); return instance; } diff --git a/src/Build/Instance/ProjectItemInstance.cs b/src/Build/Instance/ProjectItemInstance.cs index 4d5d9804805..05aa7f5e8c0 100644 --- a/src/Build/Instance/ProjectItemInstance.cs +++ b/src/Build/Instance/ProjectItemInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -602,7 +602,7 @@ internal static void SetMetadata(IEnumerable> metad /// /// Factory for deserialization. /// - static internal ProjectItemInstance FactoryForDeserialization(ITranslator translator, ProjectInstance projectInstance) + internal static ProjectItemInstance FactoryForDeserialization(ITranslator translator, ProjectInstance projectInstance) { ProjectItemInstance newItem = new ProjectItemInstance(projectInstance); ((ITranslatable)newItem).Translate(translator); @@ -706,8 +706,7 @@ private void CommonConstructor(ProjectInstance projectToUse, string itemTypeToUs inheritedItemDefinitions, _project.Directory, _project.IsImmutable, - definingFileEscaped - ); + definingFileEscaped); } /// @@ -797,8 +796,7 @@ internal TaskItem( List itemDefinitions, string projectDirectory, bool immutable, - string definingFileEscaped // the actual project file (or import) that defines this item. - ) + string definingFileEscaped) // the actual project file (or import) that defines this item. { ErrorUtilities.VerifyThrowArgumentLength(includeEscaped, nameof(includeEscaped)); ErrorUtilities.VerifyThrowArgumentLength(includeBeforeWildcardExpansionEscaped, nameof(includeBeforeWildcardExpansionEscaped)); @@ -1137,7 +1135,7 @@ internal CopyOnWritePropertyDictionary MetadataCollecti IEnumerable IItem.Metadata => MetadataCollection; -#region Operators + #region Operators /// /// This allows an explicit typecast from a "TaskItem" to a "string", returning the ItemSpec for this item. @@ -1178,7 +1176,7 @@ public static explicit operator string(TaskItem that) return !(left == right); } -#endregion + #endregion /// /// Produce a string representation. @@ -1200,7 +1198,7 @@ public override object InitializeLifetimeService() } #endif -#region IItem and ITaskItem2 Members + #region IItem and ITaskItem2 Members /// /// Returns the metadata with the specified key. @@ -1451,9 +1449,9 @@ IDictionary ITaskItem2.CloneCustomMetadataEscaped() return clonedMetadata; } -#endregion + #endregion -#region INodePacketTranslatable Members + #region INodePacketTranslatable Members /// /// Reads or writes the packet to the serializer. @@ -1483,9 +1481,9 @@ void ITranslatable.Translate(ITranslator translator) } } -#endregion + #endregion -#region IEquatable Members + #region IEquatable Members /// /// Override of GetHashCode. @@ -1578,13 +1576,10 @@ public bool Equals(TaskItem other) // This is case-insensitive, so that for example "en-US" and "en-us" match and are bucketed together. // In this respect, therefore, we have to consider item metadata value case as not significant. - if (!String.Equals - ( + if (!String.Equals( thisAsITaskItem2.GetMetadataValueEscaped(name), otherAsITaskItem2.GetMetadataValueEscaped(name), - StringComparison.OrdinalIgnoreCase - ) - ) + StringComparison.OrdinalIgnoreCase)) { return false; } @@ -1594,7 +1589,7 @@ public bool Equals(TaskItem other) return thisNames.Count == 0; } -#endregion + #endregion /// /// Returns true if a particular piece of metadata is defined on this item (even if @@ -1655,7 +1650,7 @@ private void WriteInternString(ITranslator translator, LookasideStringInterner i var key = interner.Intern(str); translator.Writer.Write(key); } - + private void ReadInternString(ITranslator translator, LookasideStringInterner interner, ref string str) { var val = translator.Reader.ReadInt32(); diff --git a/src/Build/Instance/ProjectMetadataInstance.cs b/src/Build/Instance/ProjectMetadataInstance.cs index b60c69b1cf0..e1cd5c22df6 100644 --- a/src/Build/Instance/ProjectMetadataInstance.cs +++ b/src/Build/Instance/ProjectMetadataInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Instance/ProjectOnErrorInstance.cs b/src/Build/Instance/ProjectOnErrorInstance.cs index 2b2a9f39147..f36b8407df7 100644 --- a/src/Build/Instance/ProjectOnErrorInstance.cs +++ b/src/Build/Instance/ProjectOnErrorInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.BackEnd; @@ -49,14 +49,12 @@ public sealed class ProjectOnErrorInstance : ProjectTargetInstanceChild, ITransl /// Constructor called by Evaluator. /// All parameters are in the unevaluated state. /// - internal ProjectOnErrorInstance - ( + internal ProjectOnErrorInstance( string executeTargets, string condition, ElementLocation location, ElementLocation executeTargetsLocation, - ElementLocation conditionLocation - ) + ElementLocation conditionLocation) { ErrorUtilities.VerifyThrowInternalLength(executeTargets, nameof(executeTargets)); ErrorUtilities.VerifyThrowInternalNull(condition, nameof(condition)); @@ -130,7 +128,7 @@ void ITranslatable.Translate(ITranslator translator) translator.Translate(ref _executeTargetsLocation, ElementLocation.FactoryForDeserialization); } - internal new static ProjectOnErrorInstance FactoryForDeserialization(ITranslator translator) + internal static new ProjectOnErrorInstance FactoryForDeserialization(ITranslator translator) { return translator.FactoryForDeserializingTypeWithName(); } diff --git a/src/Build/Instance/ProjectPropertyGroupTaskInstance.cs b/src/Build/Instance/ProjectPropertyGroupTaskInstance.cs index 77a2b30e416..428761765b5 100644 --- a/src/Build/Instance/ProjectPropertyGroupTaskInstance.cs +++ b/src/Build/Instance/ProjectPropertyGroupTaskInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; @@ -45,13 +45,11 @@ public class ProjectPropertyGroupTaskInstance : ProjectTargetInstanceChild, ITra /// Constructor called by the Evaluator. /// Assumes ProjectPropertyGroupTaskPropertyInstance is an immutable type. /// - internal ProjectPropertyGroupTaskInstance - ( + internal ProjectPropertyGroupTaskInstance( string condition, ElementLocation location, ElementLocation conditionLocation, - List properties - ) + List properties) { ErrorUtilities.VerifyThrowInternalNull(condition, nameof(condition)); ErrorUtilities.VerifyThrowInternalNull(location, nameof(location)); diff --git a/src/Build/Instance/ProjectPropertyGroupTaskPropertyInstance.cs b/src/Build/Instance/ProjectPropertyGroupTaskPropertyInstance.cs index 9fd8e974939..9f2640e0de9 100644 --- a/src/Build/Instance/ProjectPropertyGroupTaskPropertyInstance.cs +++ b/src/Build/Instance/ProjectPropertyGroupTaskPropertyInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using Microsoft.Build.BackEnd; @@ -143,7 +143,7 @@ void ITranslatable.Translate(ITranslator translator) internal static ProjectPropertyGroupTaskPropertyInstance FactoryForDeserialization(ITranslator translator) { var instance = new ProjectPropertyGroupTaskPropertyInstance(); - ((ITranslatable) instance).Translate(translator); + ((ITranslatable)instance).Translate(translator); return instance; } diff --git a/src/Build/Instance/ProjectPropertyInstance.cs b/src/Build/Instance/ProjectPropertyInstance.cs index ed7337062c5..300d6150226 100644 --- a/src/Build/Instance/ProjectPropertyInstance.cs +++ b/src/Build/Instance/ProjectPropertyInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Build/Instance/ProjectTargetInstance.cs b/src/Build/Instance/ProjectTargetInstance.cs index a10cb8456fb..b80dab1a593 100644 --- a/src/Build/Instance/ProjectTargetInstance.cs +++ b/src/Build/Instance/ProjectTargetInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -139,8 +139,7 @@ public sealed class ProjectTargetInstance : IImmutable, IKeyed, ITranslatable /// All parameters are in the unevaluated state. /// All location parameters may be null if not applicable, except for the main location parameter. /// - internal ProjectTargetInstance - ( + internal ProjectTargetInstance( string name, string condition, string inputs, @@ -161,8 +160,7 @@ internal ProjectTargetInstance ElementLocation afterTargetsLocation, ObjectModel.ReadOnlyCollection children, ObjectModel.ReadOnlyCollection onErrorChildren, - bool parentProjectSupportsReturnsAttribute - ) + bool parentProjectSupportsReturnsAttribute) { ErrorUtilities.VerifyThrowInternalLength(name, nameof(name)); ErrorUtilities.VerifyThrowInternalNull(condition, nameof(condition)); @@ -587,7 +585,7 @@ void ITranslatable.Translate(ITranslator translator) internal static ProjectTargetInstance FactoryForDeserialization(ITranslator translator) { var instance = new ProjectTargetInstance(); - var translatable = (ITranslatable) instance; + var translatable = (ITranslatable)instance; translatable.Translate(translator); diff --git a/src/Build/Instance/ProjectTargetInstanceChild.cs b/src/Build/Instance/ProjectTargetInstanceChild.cs index 9721855e030..7a2fa4c7240 100644 --- a/src/Build/Instance/ProjectTargetInstanceChild.cs +++ b/src/Build/Instance/ProjectTargetInstanceChild.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.Shared; diff --git a/src/Build/Instance/ProjectTaskInstance.cs b/src/Build/Instance/ProjectTaskInstance.cs index 541e5c1ada4..87fac8bd045 100644 --- a/src/Build/Instance/ProjectTaskInstance.cs +++ b/src/Build/Instance/ProjectTaskInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Construction; @@ -94,11 +94,9 @@ public sealed class ProjectTaskInstance : ProjectTargetInstanceChild, ITranslata /// All parameters are in the unevaluated state. /// Locations other than the main location may be null. /// - internal ProjectTaskInstance - ( + internal ProjectTaskInstance( ProjectTaskElement element, - IList outputs - ) + IList outputs) { ErrorUtilities.VerifyThrowInternalNull(element, nameof(element)); ErrorUtilities.VerifyThrowInternalNull(outputs, nameof(outputs)); @@ -133,8 +131,7 @@ internal ProjectTaskInstance( string condition, string continueOnError, string msbuildRuntime, - string msbuildArchitecture - ) : this( + string msbuildArchitecture) : this( name, condition, continueOnError, @@ -150,8 +147,7 @@ string msbuildArchitecture { } - internal ProjectTaskInstance - ( + internal ProjectTaskInstance( string name, string condition, string continueOnError, @@ -388,7 +384,7 @@ void ITranslatable.Translate(ITranslator translator) if (translator.Mode == TranslationDirection.ReadFromStream && localParameters != null) { - _parameters = (CopyOnWriteDictionary<(string, ElementLocation)>) localParameters; + _parameters = (CopyOnWriteDictionary<(string, ElementLocation)>)localParameters; } } @@ -419,7 +415,7 @@ private static void ParametersValueTranslator(ITranslator translator, ref (strin } } - internal new static ProjectTaskInstance FactoryForDeserialization(ITranslator translator) + internal static new ProjectTaskInstance FactoryForDeserialization(ITranslator translator) { return translator.FactoryForDeserializingTypeWithName(); } diff --git a/src/Build/Instance/ProjectTaskInstanceChild.cs b/src/Build/Instance/ProjectTaskInstanceChild.cs index cfd33563367..a4a94933f0a 100644 --- a/src/Build/Instance/ProjectTaskInstanceChild.cs +++ b/src/Build/Instance/ProjectTaskInstanceChild.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.Shared; diff --git a/src/Build/Instance/ProjectTaskOutputItemInstance.cs b/src/Build/Instance/ProjectTaskOutputItemInstance.cs index e1648addda9..e475c63cb23 100644 --- a/src/Build/Instance/ProjectTaskOutputItemInstance.cs +++ b/src/Build/Instance/ProjectTaskOutputItemInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.Shared; diff --git a/src/Build/Instance/ProjectTaskOutputPropertyInstance.cs b/src/Build/Instance/ProjectTaskOutputPropertyInstance.cs index 21bf266530d..01152bb2ed9 100644 --- a/src/Build/Instance/ProjectTaskOutputPropertyInstance.cs +++ b/src/Build/Instance/ProjectTaskOutputPropertyInstance.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.Shared; diff --git a/src/Build/Instance/ReflectableTaskPropertyInfo.cs b/src/Build/Instance/ReflectableTaskPropertyInfo.cs index 66c846646dc..bc23ef34303 100644 --- a/src/Build/Instance/ReflectableTaskPropertyInfo.cs +++ b/src/Build/Instance/ReflectableTaskPropertyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Linq; diff --git a/src/Build/Instance/RunningObjectTable.cs b/src/Build/Instance/RunningObjectTable.cs index bec9632885e..8a9812ec4ed 100644 --- a/src/Build/Instance/RunningObjectTable.cs +++ b/src/Build/Instance/RunningObjectTable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; diff --git a/src/Build/Instance/TaskFactories/AssemblyTaskFactory.cs b/src/Build/Instance/TaskFactories/AssemblyTaskFactory.cs index 41135bc767b..e6c0d6a2ef7 100644 --- a/src/Build/Instance/TaskFactories/AssemblyTaskFactory.cs +++ b/src/Build/Instance/TaskFactories/AssemblyTaskFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -244,8 +244,7 @@ public void CleanupTask(ITask task) /// /// Initialize the factory from the task registry /// - internal LoadedType InitializeFactory - ( + internal LoadedType InitializeFactory( AssemblyLoadInfo loadInfo, string taskName, IDictionary taskParameters, @@ -254,8 +253,7 @@ internal LoadedType InitializeFactory bool taskHostFactoryExplicitlyRequested, TargetLoggingContext targetLoggingContext, ElementLocation elementLocation, - string taskProjectFile - ) + string taskProjectFile) { ErrorUtilities.VerifyThrowArgumentNull(loadInfo, nameof(loadInfo)); VerifyThrowIdentityParametersValid(taskFactoryIdentityParameters, elementLocation, taskName, "Runtime", "Architecture"); @@ -356,11 +354,18 @@ internal ITask CreateTaskInstance(ElementLocation taskLocation, TaskLoggingConte mergedParameters[XMakeAttributes.architecture] = XMakeAttributes.GetCurrentMSBuildArchitecture(); } - TaskHostTask task = new TaskHostTask(taskLocation, taskLoggingContext, buildComponentHost, mergedParameters, _loadedType +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + TaskHostTask task = new TaskHostTask( + taskLocation, + taskLoggingContext, + buildComponentHost, + mergedParameters, + _loadedType #if FEATURE_APPDOMAIN , appDomainSetup #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter return task; } else @@ -369,15 +374,23 @@ internal ITask CreateTaskInstance(ElementLocation taskLocation, TaskLoggingConte AppDomain taskAppDomain = null; #endif - ITask taskInstance = TaskLoader.CreateTask(_loadedType, _taskName, taskLocation.File, taskLocation.Line, taskLocation.Column, new TaskLoader.LogError(ErrorLoggingDelegate) +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + ITask taskInstance = TaskLoader.CreateTask( + _loadedType, + _taskName, + taskLocation.File, + taskLocation.Line, + taskLocation.Column, + new TaskLoader.LogError(ErrorLoggingDelegate), #if FEATURE_APPDOMAIN - , appDomainSetup + appDomainSetup, #endif - , isOutOfProc + isOutOfProc #if FEATURE_APPDOMAIN , out taskAppDomain #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter #if FEATURE_APPDOMAIN if (taskAppDomain != null) @@ -456,8 +469,7 @@ private static void VerifyThrowIdentityParametersValid(IDictionary /// Constructor /// - public TaskHostTask(IElementLocation taskLocation, TaskLoggingContext taskLoggingContext, IBuildComponentHost buildComponentHost, IDictionary taskHostParameters, LoadedType taskType + /// +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + public TaskHostTask( + IElementLocation taskLocation, + TaskLoggingContext taskLoggingContext, + IBuildComponentHost buildComponentHost, + IDictionary taskHostParameters, + LoadedType taskType #if FEATURE_APPDOMAIN , AppDomainSetup appDomainSetup #endif ) +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter { ErrorUtilities.VerifyThrowInternalNull(taskType, nameof(taskType)); @@ -254,8 +262,7 @@ public bool Execute() } TaskHostConfiguration hostConfiguration = - new TaskHostConfiguration - ( + new TaskHostConfiguration( _buildComponentHost.BuildParameters.NodeId, NativeMethodsShared.GetCurrentDirectory(), CommunicationsUtilities.GetEnvironmentVariables(), @@ -275,9 +282,7 @@ public bool Execute() new Dictionary(_buildComponentHost.BuildParameters.GlobalProperties), _taskLoggingContext.GetWarningsAsErrors(), _taskLoggingContext.GetWarningsNotAsErrors(), - _taskLoggingContext.GetWarningsAsMessages() - - ); + _taskLoggingContext.GetWarningsAsMessages()); try { diff --git a/src/Build/Instance/TaskFactoryLoggingHost.cs b/src/Build/Instance/TaskFactoryLoggingHost.cs index ead6db61dc9..379987804ae 100644 --- a/src/Build/Instance/TaskFactoryLoggingHost.cs +++ b/src/Build/Instance/TaskFactoryLoggingHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Build/Instance/TaskFactoryWrapper.cs b/src/Build/Instance/TaskFactoryWrapper.cs index 72bf3ec5624..bcdf1286940 100644 --- a/src/Build/Instance/TaskFactoryWrapper.cs +++ b/src/Build/Instance/TaskFactoryWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; diff --git a/src/Build/Instance/TaskRegistry.cs b/src/Build/Instance/TaskRegistry.cs index 458c6956422..ced1b61e0fa 100644 --- a/src/Build/Instance/TaskRegistry.cs +++ b/src/Build/Instance/TaskRegistry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -218,8 +218,7 @@ internal IDictionary> TaskReg /// /// A type derived from IProperty /// A type derived from IItem - internal static void RegisterTasksFromUsingTaskElement - ( + internal static void RegisterTasksFromUsingTaskElement( ILoggingService loggingService, BuildEventContext buildEventContext, string directoryOfImportingFile, @@ -227,15 +226,13 @@ internal static void RegisterTasksFromUsingTaskElement TaskRegistry taskRegistry, Expander expander, ExpanderOptions expanderOptions, - IFileSystem fileSystem - ) + IFileSystem fileSystem) where P : class, IProperty where I : class, IItem { ErrorUtilities.VerifyThrowInternalNull(directoryOfImportingFile, nameof(directoryOfImportingFile)); - if (!ConditionEvaluator.EvaluateCondition - ( + if (!ConditionEvaluator.EvaluateCondition( projectUsingTaskXml.Condition, ParserOptions.AllowPropertiesAndItemLists, expander, @@ -244,8 +241,7 @@ IFileSystem fileSystem projectUsingTaskXml.ConditionLocation, loggingService, buildEventContext, - fileSystem - )) + fileSystem)) { return; } @@ -255,16 +251,14 @@ IFileSystem fileSystem string taskName = expander.ExpandIntoStringLeaveEscaped(projectUsingTaskXml.TaskName, expanderOptions, projectUsingTaskXml.TaskNameLocation); - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( taskName.Length > 0, projectUsingTaskXml.TaskNameLocation, "InvalidEvaluatedAttributeValue", taskName, projectUsingTaskXml.TaskName, XMakeAttributes.name, - XMakeElements.usingTask - ); + XMakeElements.usingTask); string taskFactory = expander.ExpandIntoStringLeaveEscaped(projectUsingTaskXml.TaskFactory, expanderOptions, projectUsingTaskXml.TaskFactoryLocation); @@ -282,27 +276,23 @@ IFileSystem fileSystem assemblyName = expander.ExpandIntoStringLeaveEscaped(projectUsingTaskXml.AssemblyName, expanderOptions, projectUsingTaskXml.AssemblyNameLocation); } - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( assemblyFile == null || assemblyFile.Length > 0, projectUsingTaskXml.AssemblyFileLocation, "InvalidEvaluatedAttributeValue", assemblyFile, projectUsingTaskXml.AssemblyFile, XMakeAttributes.assemblyFile, - XMakeElements.usingTask - ); + XMakeElements.usingTask); - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( assemblyName == null || assemblyName.Length > 0, projectUsingTaskXml.AssemblyNameLocation, "InvalidEvaluatedAttributeValue", assemblyName, projectUsingTaskXml.AssemblyName, XMakeAttributes.assemblyName, - XMakeElements.usingTask - ); + XMakeElements.usingTask); // Ensure the assembly file/path is relative to the project in which this node was defined -- we // don't want paths from imported projects being interpreted relative to the main project file. @@ -325,8 +315,7 @@ IFileSystem fileSystem if ( assemblyFile != null && (assemblyFile.EndsWith(s_tasksV4Filename, StringComparison.OrdinalIgnoreCase) || assemblyFile.EndsWith(s_tasksV12Filename, StringComparison.OrdinalIgnoreCase)) && - !FileUtilities.FileExistsNoThrow(assemblyFile, fileSystem) - ) + !FileUtilities.FileExistsNoThrow(assemblyFile, fileSystem)) { string replacedAssemblyFile = Path.Combine(Path.GetDirectoryName(assemblyFile), s_tasksCoreFilename); @@ -345,8 +334,7 @@ IFileSystem fileSystem ( assemblyName.Equals(s_tasksV4SimpleName, StringComparison.OrdinalIgnoreCase) && !FileUtilities.FileExistsNoThrow(s_potentialTasksV4Location, fileSystem) && - FileUtilities.FileExistsNoThrow(s_potentialTasksCoreLocation, fileSystem) - ) + FileUtilities.FileExistsNoThrow(s_potentialTasksCoreLocation, fileSystem)) { assemblyName = s_tasksCoreSimpleName; } @@ -354,8 +342,7 @@ IFileSystem fileSystem ( assemblyName.Equals(s_tasksV12SimpleName, StringComparison.OrdinalIgnoreCase) && !FileUtilities.FileExistsNoThrow(s_potentialTasksV12Location, fileSystem) && - FileUtilities.FileExistsNoThrow(s_potentialTasksCoreLocation, fileSystem) - ) + FileUtilities.FileExistsNoThrow(s_potentialTasksCoreLocation, fileSystem)) { assemblyName = s_tasksCoreSimpleName; } @@ -403,18 +390,16 @@ private static Dictionary CreateTaskFactoryParametersDictionary( /// Given a task name, this method retrieves the task class. If the task has been requested before, it will be found in /// the class cache; otherwise, <UsingTask> declarations will be used to search the appropriate assemblies. /// - internal TaskFactoryWrapper GetRegisteredTask - ( + internal TaskFactoryWrapper GetRegisteredTask( string taskName, string taskProjectFile, IDictionary taskIdentityParameters, bool exactMatchRequired, TargetLoggingContext targetLoggingContext, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { TaskFactoryWrapper taskFactory = null; - + // If there are no usingtask tags in the project don't bother caching or looking for tasks locally RegisteredTaskRecord record = GetTaskRegistrationRecord(taskName, taskProjectFile, taskIdentityParameters, exactMatchRequired, targetLoggingContext, elementLocation, out bool retrievedFromCache); @@ -458,16 +443,14 @@ ElementLocation elementLocation /// The location of the task element in the project file. /// True if the record was retrieved from the cache. /// The task registration record, or null if none was found. - internal RegisteredTaskRecord GetTaskRegistrationRecord - ( + internal RegisteredTaskRecord GetTaskRegistrationRecord( string taskName, string taskProjectFile, IDictionary taskIdentityParameters, bool exactMatchRequired, TargetLoggingContext targetLoggingContext, ElementLocation elementLocation, - out bool retrievedFromCache - ) + out bool retrievedFromCache) { RegisteredTaskRecord taskRecord = null; retrievedFromCache = false; @@ -656,14 +639,13 @@ private Dictionary> GetReleva // Create another set containing architecture-specific task entries. // Then when we look for them, check if the name exists in that. - Dictionary> overriddenTasks = new Dictionary>(); + private Dictionary> overriddenTasks = new Dictionary>(); /// /// Registers an evaluated using task tag for future /// consultation /// - private void RegisterTask - ( + private void RegisterTask( string taskName, AssemblyLoadInfo assemblyLoadInfo, string taskFactory, @@ -672,8 +654,7 @@ private void RegisterTask ILoggingService loggingService, BuildEventContext context, ProjectUsingTaskElement projectUsingTaskInXml, - bool overrideTask = false - ) + bool overrideTask = false) { ErrorUtilities.VerifyThrowInternalLength(taskName, nameof(taskName)); ErrorUtilities.VerifyThrowInternalNull(assemblyLoadInfo, nameof(assemblyLoadInfo)); @@ -740,15 +721,13 @@ private static Dictionary> Cr /// Given a task name and a list of records which may contain the task, this helper method will ask the records to see if the task name /// can be created by the factories which are wrapped by the records. (this is done by instantiating the task factory and asking it). /// - private RegisteredTaskRecord GetMatchingRegistration - ( + private RegisteredTaskRecord GetMatchingRegistration( string taskName, List taskRecords, string taskProjectFile, IDictionary taskIdentityParameters, TargetLoggingContext targetLoggingContext, - ElementLocation elementLocation - ) + ElementLocation elementLocation) { foreach (RegisteredTaskRecord record in taskRecords) { @@ -1360,8 +1339,7 @@ private bool GetTaskFactory(TargetLoggingContext targetLoggingContext, ElementLo ( s_forceTaskHostLaunch && !TypeLoader.IsPartialTypeNameMatch(RegisteredName, "MSBuild") && - !TypeLoader.IsPartialTypeNameMatch(RegisteredName, "CallTarget") - ); + !TypeLoader.IsPartialTypeNameMatch(RegisteredName, "CallTarget")); // Create an instance of the internal assembly task factory, it has the error handling built into its methods. AssemblyTaskFactory taskFactory = new AssemblyTaskFactory(); @@ -1433,7 +1411,7 @@ private bool GetTaskFactory(TargetLoggingContext targetLoggingContext, ElementLo #if FEATURE_APPDOMAIN factory = (ITaskFactory)AppDomain.CurrentDomain.CreateInstanceAndUnwrap(loadedType.Type.GetTypeInfo().Assembly.FullName, loadedType.Type.FullName); #else - factory = (ITaskFactory) Activator.CreateInstance(loadedType.Type); + factory = (ITaskFactory)Activator.CreateInstance(loadedType.Type); #endif TaskFactoryLoggingHost taskFactoryLoggingHost = new TaskFactoryLoggingHost(true /*I dont have the data at this point, the safest thing to do is make sure events are serializable*/, elementLocation, targetLoggingContext); @@ -1452,8 +1430,7 @@ private bool GetTaskFactory(TargetLoggingContext targetLoggingContext, ElementLo // TaskFactoryParameters will always be null unless specifically created to have runtime and architecture parameters. if (TaskFactoryParameters != null) { - targetLoggingContext.LogWarning - ( + targetLoggingContext.LogWarning( null, new BuildEventFileInfo(elementLocation), "TaskFactoryWillIgnoreTaskFactoryParameters", @@ -1492,14 +1469,12 @@ private bool GetTaskFactory(TargetLoggingContext targetLoggingContext, ElementLo message += e.Message; // Could get an invalid cast when Creating Instance and UnWrap due to the framework assembly not being the same. - targetLoggingContext.LogError - ( + targetLoggingContext.LogError( new BuildEventFileInfo(elementLocation.File, elementLocation.Line, elementLocation.Column), "TaskFactoryInstantiationFailureErrorInvalidCast", TaskFactoryAttributeName, taskFactoryLoadInfo.AssemblyLocation, - message - ); + message); return false; } @@ -1622,15 +1597,13 @@ private void EvaluateTaskBody(Expander expander, ProjectUsingTaskBod if (!Boolean.TryParse(expandedType, out evaluate)) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( taskElement.EvaluateLocation, "InvalidEvaluatedAttributeValue", expandedType, taskElement.Evaluate, XMakeAttributes.evaluate, - XMakeElements.usingTaskBody - ); + XMakeElements.usingTaskBody); } _taskBodyEvaluated = evaluate; @@ -1664,16 +1637,14 @@ private void ParseUsingTaskParameterGroupElement(UsingTaskParameterGroupEl string expandedType = expander.ExpandIntoStringLeaveEscaped(parameter.ParameterType, expanderOptions, parameter.ParameterTypeLocation); // Cannot have a null or empty name for the type after expansion. - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( !String.IsNullOrEmpty(expandedType), parameter.ParameterTypeLocation, "InvalidEvaluatedAttributeValue", expandedType, parameter.ParameterType, XMakeAttributes.parameterType, - XMakeElements.usingTaskParameter - ); + XMakeElements.usingTaskParameter); Type paramType; if (expandedType.StartsWith("Microsoft.Build.Framework.", StringComparison.OrdinalIgnoreCase) && !expandedType.Contains(",")) @@ -1691,46 +1662,39 @@ private void ParseUsingTaskParameterGroupElement(UsingTaskParameterGroupEl Type.GetType(expandedType + "," + typeof(ITaskItem).GetTypeInfo().Assembly.FullName, false /* don't throw on error */, true /* case-insensitive */); } - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( paramType != null, parameter.ParameterTypeLocation, "InvalidEvaluatedAttributeValue", expandedType, parameter.ParameterType, XMakeAttributes.parameterType, - XMakeElements.usingTaskParameter - ); + XMakeElements.usingTaskParameter); bool output; string expandedOutput = expander.ExpandIntoStringLeaveEscaped(parameter.Output, expanderOptions, parameter.OutputLocation); if (!Boolean.TryParse(expandedOutput, out output)) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameter.OutputLocation, "InvalidEvaluatedAttributeValue", expandedOutput, parameter.Output, XMakeAttributes.output, - XMakeElements.usingTaskParameter - ); + XMakeElements.usingTaskParameter); } if ( (!output && (!TaskParameterTypeVerifier.IsValidInputParameter(paramType))) || - (output && !TaskParameterTypeVerifier.IsValidOutputParameter(paramType)) - ) + (output && !TaskParameterTypeVerifier.IsValidOutputParameter(paramType))) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameter.Location, "UnsupportedTaskParameterTypeError", paramType.FullName, parameter.ParameterType, - parameter.Name - ); + parameter.Name); } bool required; @@ -1738,15 +1702,13 @@ private void ParseUsingTaskParameterGroupElement(UsingTaskParameterGroupEl if (!Boolean.TryParse(expandedRequired, out required)) { - ProjectErrorUtilities.ThrowInvalidProject - ( + ProjectErrorUtilities.ThrowInvalidProject( parameter.RequiredLocation, "InvalidEvaluatedAttributeValue", expandedRequired, parameter.Required, XMakeAttributes.required, - XMakeElements.usingTaskParameter - ); + XMakeElements.usingTaskParameter); } UsingTaskParameters.Add(parameter.Name, new TaskPropertyInfo(parameter.Name, paramType, output, required)); @@ -1811,7 +1773,7 @@ public void Translate(ITranslator translator) if (translator.Mode == TranslationDirection.ReadFromStream && localParameters != null) { - _taskFactoryParameters = (Dictionary) localParameters; + _taskFactoryParameters = (Dictionary)localParameters; } } @@ -1833,18 +1795,18 @@ public void Translate(ITranslator translator) if (translator.Mode == TranslationDirection.ReadFromStream) { - _taskRegistrations = (Dictionary>) copy; + _taskRegistrations = (Dictionary>)copy; } } // todo make nested after C# 7 - void TranslateTaskRegistrationKey(ITranslator translator, ref RegisteredTaskIdentity taskIdentity) + private void TranslateTaskRegistrationKey(ITranslator translator, ref RegisteredTaskIdentity taskIdentity) { translator.Translate(ref taskIdentity); } // todo make nested after C# 7 - void TranslateTaskRegistrationValue(ITranslator translator, ref List taskRecords) + private void TranslateTaskRegistrationValue(ITranslator translator, ref List taskRecords) { translator.Translate(ref taskRecords, RegisteredTaskRecord.FactoryForDeserialization); } diff --git a/src/Build/Logging/BaseConsoleLogger.cs b/src/Build/Logging/BaseConsoleLogger.cs index 5d5c32727de..67e6691aa4d 100644 --- a/src/Build/Logging/BaseConsoleLogger.cs +++ b/src/Build/Logging/BaseConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -75,11 +75,17 @@ internal abstract class BaseConsoleLogger : INodeLogger /// public void ParseParameters() { - if (Parameters == null) return; + if (Parameters == null) + { + return; + } foreach (string parameter in Parameters.Split(parameterDelimiters)) { - if (string.IsNullOrWhiteSpace(parameter)) continue; + if (string.IsNullOrWhiteSpace(parameter)) + { + continue; + } string[] parameterAndValue = parameter.Split(s_parameterValueSplitCharacter); ApplyParameter(parameterAndValue[0], parameterAndValue.Length > 1 ? parameterAndValue[1] : null); @@ -99,7 +105,7 @@ private DictionaryEntryKeyComparer() { } public int Compare(DictionaryEntry a, DictionaryEntry b) { - return string.Compare((string) a.Key, (string) b.Key, StringComparison.CurrentCultureIgnoreCase); + return string.Compare((string)a.Key, (string)b.Key, StringComparison.CurrentCultureIgnoreCase); } } @@ -127,7 +133,10 @@ public int Compare(Object a, Object b) internal string IndentString(string s, int indent) { // It's possible the event has a null message - if (s == null) return string.Empty; + if (s == null) + { + return string.Empty; + } // This will never return an empty array. The returned array will always // have at least one non-null element, even if "s" is totally empty. @@ -578,7 +587,10 @@ internal virtual void OutputProperties(List list) /// internal void WriteItems(SortedList itemTypes) { - if (Verbosity != LoggerVerbosity.Diagnostic || !showItemAndPropertyList || itemTypes.Count == 0) return; + if (Verbosity != LoggerVerbosity.Diagnostic || !showItemAndPropertyList || itemTypes.Count == 0) + { + return; + } // Write the banner setColor(ConsoleColor.Green); @@ -587,8 +599,8 @@ internal void WriteItems(SortedList itemTypes) // Write each item type and its itemspec, one per line foreach (DictionaryEntry entry in itemTypes) { - string itemType = (string) entry.Key; - ArrayList itemTypeList = (ArrayList) entry.Value; + string itemType = (string)entry.Key; + ArrayList itemTypeList = (ArrayList)entry.Value; if (itemTypeList.Count == 0) { @@ -961,7 +973,7 @@ public virtual void Initialize(IEventSource eventSource) if (eventSource != null) { eventSource.BuildStarted += BuildStartedHandler; - eventSource.BuildFinished +=BuildFinishedHandler; + eventSource.BuildFinished += BuildFinishedHandler; eventSource.ProjectStarted += ProjectStartedHandler; eventSource.ProjectFinished += ProjectFinishedHandler; eventSource.TargetStarted += TargetStartedHandler; diff --git a/src/Build/Logging/BinaryLogger/BinaryLogRecordKind.cs b/src/Build/Logging/BinaryLogger/BinaryLogRecordKind.cs index 46c583f3472..29dfb17f8f1 100644 --- a/src/Build/Logging/BinaryLogger/BinaryLogRecordKind.cs +++ b/src/Build/Logging/BinaryLogger/BinaryLogRecordKind.cs @@ -1,4 +1,7 @@ -#nullable disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable disable namespace Microsoft.Build.Logging { @@ -30,6 +33,6 @@ internal enum BinaryLogRecordKind NameValueList, String, TaskParameter, - ResponseFileUsed, + ResponseFileUsed, } } diff --git a/src/Build/Logging/BinaryLogger/BinaryLogReplayEventSource.cs b/src/Build/Logging/BinaryLogger/BinaryLogReplayEventSource.cs index 62f72ae2917..8bdcfbf09d9 100644 --- a/src/Build/Logging/BinaryLogger/BinaryLogReplayEventSource.cs +++ b/src/Build/Logging/BinaryLogger/BinaryLogReplayEventSource.cs @@ -1,4 +1,7 @@ -using System; +// 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.IO; using System.IO.Compression; using System.Threading; diff --git a/src/Build/Logging/BinaryLogger/BinaryLogger.cs b/src/Build/Logging/BinaryLogger/BinaryLogger.cs index 3e29b27e99e..35780421fb1 100644 --- a/src/Build/Logging/BinaryLogger/BinaryLogger.cs +++ b/src/Build/Logging/BinaryLogger/BinaryLogger.cs @@ -1,4 +1,7 @@ -using System; +// 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.IO; using System.IO.Compression; using Microsoft.Build.Framework; diff --git a/src/Build/Logging/BinaryLogger/BuildEventArgsDispatcher.cs b/src/Build/Logging/BinaryLogger/BuildEventArgsDispatcher.cs index bfb588a0275..4a50a3d8e8b 100644 --- a/src/Build/Logging/BinaryLogger/BuildEventArgsDispatcher.cs +++ b/src/Build/Logging/BinaryLogger/BuildEventArgsDispatcher.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Framework; #nullable disable diff --git a/src/Build/Logging/BinaryLogger/BuildEventArgsFieldFlags.cs b/src/Build/Logging/BinaryLogger/BuildEventArgsFieldFlags.cs index 9e9d1a9cd0f..65468da0972 100644 --- a/src/Build/Logging/BinaryLogger/BuildEventArgsFieldFlags.cs +++ b/src/Build/Logging/BinaryLogger/BuildEventArgsFieldFlags.cs @@ -1,4 +1,7 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; #nullable disable diff --git a/src/Build/Logging/BinaryLogger/BuildEventArgsFields.cs b/src/Build/Logging/BinaryLogger/BuildEventArgsFields.cs index 898ea06c5ca..f5aba4eb60c 100644 --- a/src/Build/Logging/BinaryLogger/BuildEventArgsFields.cs +++ b/src/Build/Logging/BinaryLogger/BuildEventArgsFields.cs @@ -1,4 +1,7 @@ -using System; +// 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 Microsoft.Build.Framework; #nullable disable diff --git a/src/Build/Logging/BinaryLogger/BuildEventArgsReader.cs b/src/Build/Logging/BinaryLogger/BuildEventArgsReader.cs index a93e2074044..ee7f201ba25 100644 --- a/src/Build/Logging/BinaryLogger/BuildEventArgsReader.cs +++ b/src/Build/Logging/BinaryLogger/BuildEventArgsReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Build/Logging/BinaryLogger/BuildEventArgsWriter.cs b/src/Build/Logging/BinaryLogger/BuildEventArgsWriter.cs index 79dac4ce124..67a2005c284 100644 --- a/src/Build/Logging/BinaryLogger/BuildEventArgsWriter.cs +++ b/src/Build/Logging/BinaryLogger/BuildEventArgsWriter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -139,41 +139,41 @@ public void Write(BuildEventArgs e) currentRecordStream.SetLength(0); } -/* -Base types and inheritance ("EventArgs" suffix omitted): - -Build - Telemetry - LazyFormattedBuild - BuildMessage - CriticalBuildMessage - EnvironmentVariableRead - MetaprojectGenerated - ProjectImported - PropertyInitialValueSet - PropertyReassignment - TargetSkipped - TaskCommandLine - TaskParameter - UninitializedPropertyRead - BuildStatus - TaskStarted - TaskFinished - TargetStarted - TargetFinished - ProjectStarted - ProjectFinished - BuildStarted - BuildFinished - ProjectEvaluationStarted - ProjectEvaluationFinished - BuildError - BuildWarning - CustomBuild - ExternalProjectStarted - ExternalProjectFinished - -*/ + /* + Base types and inheritance ("EventArgs" suffix omitted): + + Build + Telemetry + LazyFormattedBuild + BuildMessage + CriticalBuildMessage + EnvironmentVariableRead + MetaprojectGenerated + ProjectImported + PropertyInitialValueSet + PropertyReassignment + TargetSkipped + TaskCommandLine + TaskParameter + UninitializedPropertyRead + BuildStatus + TaskStarted + TaskFinished + TargetStarted + TargetFinished + ProjectStarted + ProjectFinished + BuildStarted + BuildFinished + ProjectEvaluationStarted + ProjectEvaluationFinished + BuildError + BuildWarning + CustomBuild + ExternalProjectStarted + ExternalProjectFinished + + */ private void WriteCore(BuildEventArgs e) { diff --git a/src/Build/Logging/BinaryLogger/ProjectImportsCollector.cs b/src/Build/Logging/BinaryLogger/ProjectImportsCollector.cs index 15f5a816ccf..41fa9daa780 100644 --- a/src/Build/Logging/BinaryLogger/ProjectImportsCollector.cs +++ b/src/Build/Logging/BinaryLogger/ProjectImportsCollector.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.IO; using System.IO.Compression; diff --git a/src/Build/Logging/ConsoleConfiguration.cs b/src/Build/Logging/ConsoleConfiguration.cs index a826d0c24e5..2db3ebdab83 100644 --- a/src/Build/Logging/ConsoleConfiguration.cs +++ b/src/Build/Logging/ConsoleConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; diff --git a/src/Build/Logging/ConsoleLogger.cs b/src/Build/Logging/ConsoleLogger.cs index d4320ced186..6cd217dc48a 100644 --- a/src/Build/Logging/ConsoleLogger.cs +++ b/src/Build/Logging/ConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -85,13 +85,11 @@ public ConsoleLogger(LoggerVerbosity verbosity) : /// /// /// - public ConsoleLogger - ( + public ConsoleLogger( LoggerVerbosity verbosity, WriteHandler write, ColorSetter colorSet, - ColorResetter colorReset - ) + ColorResetter colorReset) { _verbosity = verbosity; _write = write; @@ -105,7 +103,10 @@ ColorResetter colorReset /// private void InitializeBaseConsoleLogger() { - if (_consoleLogger != null) return; + if (_consoleLogger != null) + { + return; + } bool useMPLogger = false; bool disableConsoleColor = false; @@ -116,7 +117,10 @@ private void InitializeBaseConsoleLogger() string[] parameterComponents = _parameters.Split(BaseConsoleLogger.parameterDelimiters); foreach (string param in parameterComponents) { - if (param.Length <= 0) continue; + if (param.Length <= 0) + { + continue; + } if (string.Equals(param, "ENABLEMPLOGGING", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Build/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs b/src/Build/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs index 64b994b85e2..277352b56a0 100644 --- a/src/Build/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs +++ b/src/Build/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Logging/DistributedLoggers/DistributedFileLogger.cs b/src/Build/Logging/DistributedLoggers/DistributedFileLogger.cs index 7318a086b81..4df6b2830f9 100644 --- a/src/Build/Logging/DistributedLoggers/DistributedFileLogger.cs +++ b/src/Build/Logging/DistributedLoggers/DistributedFileLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build/Logging/EvaluationLocationIdAgnosticComparer.cs b/src/Build/Logging/EvaluationLocationIdAgnosticComparer.cs index c5bcc3c61ad..85824638836 100644 --- a/src/Build/Logging/EvaluationLocationIdAgnosticComparer.cs +++ b/src/Build/Logging/EvaluationLocationIdAgnosticComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Logging/FancyLogger/ANSIBuilder.cs b/src/Build/Logging/FancyLogger/ANSIBuilder.cs index 4bd20820b46..b735859d666 100644 --- a/src/Build/Logging/FancyLogger/ANSIBuilder.cs +++ b/src/Build/Logging/FancyLogger/ANSIBuilder.cs @@ -1,6 +1,5 @@ // 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.Collections.Generic; @@ -25,7 +24,10 @@ public static int ANSIBreakpoint(string text, int position) } public static int ANSIBreakpoint(string text, int position, int initialPosition) { - if (position >= text.Length) return text.Length; + if (position >= text.Length) + { + return text.Length; + } int nonAnsiIndex = 0; // Match nextMatch = Regex.Match(text, ANSIRegex); Match nextMatch = ANSIRegexRegex.Match(text, initialPosition); @@ -66,7 +68,11 @@ public static string Center(string text) { string result = String.Empty; string noFormatString = ANSIRemove(text); - if (noFormatString.Length > Console.BufferWidth) return text; + if (noFormatString.Length > Console.BufferWidth) + { + return text; + } + int space = (Console.BufferWidth - noFormatString.Length) / 2; result += new string(' ', space); result += text; @@ -78,7 +84,11 @@ public static string Right(string text) { string result = String.Empty; string noFormatString = ANSIRemove(text); - if (noFormatString.Length > Console.BufferWidth) return text; + if (noFormatString.Length > Console.BufferWidth) + { + return text; + } + int space = Console.BufferWidth - noFormatString.Length; result += new string(' ', space); result += text; @@ -89,7 +99,11 @@ public static string Left(string text) { string result = String.Empty; string noFormatString = ANSIRemove(text); - if (noFormatString.Length > Console.BufferWidth) return text; + if (noFormatString.Length > Console.BufferWidth) + { + return text; + } + int space = Console.BufferWidth - noFormatString.Length; result += text; result += new string(' ', space); @@ -101,7 +115,11 @@ public static string SpaceBetween(string leftText, string rightText, int width) string result = String.Empty; string leftNoFormatString = ANSIRemove(leftText); string rightNoFormatString = ANSIRemove(rightText); - if (leftNoFormatString.Length + rightNoFormatString.Length > Console.BufferWidth) return leftText + rightText; + if (leftNoFormatString.Length + rightNoFormatString.Length > Console.BufferWidth) + { + return leftText + rightText; + } + int space = Console.BufferWidth - (leftNoFormatString.Length + rightNoFormatString.Length); result += leftText; result += new string(' ', space - 1); @@ -242,7 +260,8 @@ public static string Up(int n = 1) public static string UpAndScroll(int n) { string result = ""; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { result += "\x1bM"; } return result; @@ -278,7 +297,8 @@ public static string SavePosition() return String.Format("\x1b[s"); } - public static string RestorePosition() { + public static string RestorePosition() + { return String.Format("\x1b[u"); } @@ -302,7 +322,11 @@ public static string SetStop() public static string ForwardTab(int n) { - if (n == 0) return ""; + if (n == 0) + { + return ""; + } + return String.Format("\x1b[{0}I", n); } @@ -393,7 +417,7 @@ public static string Spinner() public static string Spinner(int n) { - char[] chars = { '\\', '|', '/', '-'}; + char[] chars = { '\\', '|', '/', '-' }; return chars[n % (chars.Length - 1)].ToString(); } diff --git a/src/Build/Logging/FancyLogger/FancyLogger.cs b/src/Build/Logging/FancyLogger/FancyLogger.cs index a364ee13cb9..477e5466123 100644 --- a/src/Build/Logging/FancyLogger/FancyLogger.cs +++ b/src/Build/Logging/FancyLogger/FancyLogger.cs @@ -9,7 +9,7 @@ namespace Microsoft.Build.Logging.FancyLogger { public class FancyLogger : ILogger - { + { private Dictionary projects = new Dictionary(); private bool Succeeded; @@ -17,7 +17,7 @@ public class FancyLogger : ILogger private float existingTasks = 1; private float completedTasks = 0; - public string Parameters { get; set; } + public string Parameters { get; set; } public LoggerVerbosity Verbosity { get; set; } @@ -45,14 +45,14 @@ public void Initialize(IEventSource eventSource) eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised); // Cancelled Console.CancelKeyPress += new ConsoleCancelEventHandler(console_CancelKeyPressed); - + Task.Run(() => { Render(); }); } - void Render() + private void Render() { // Initialize FancyLoggerBuffer FancyLoggerBuffer.Initialize(); @@ -70,7 +70,10 @@ void Render() Task.Delay((i / 60) * 1_000).ContinueWith((t) => { // Rerender projects only when needed - foreach (var project in projects) project.Value.Log(); + foreach (var project in projects) + { + project.Value.Log(); + } // Rerender buffer FancyLoggerBuffer.Render(); }); @@ -81,7 +84,10 @@ void Render() switch (key) { case ConsoleKey.UpArrow: - if (FancyLoggerBuffer.TopLineIndex > 0) FancyLoggerBuffer.TopLineIndex--; + if (FancyLoggerBuffer.TopLineIndex > 0) + { + FancyLoggerBuffer.TopLineIndex--; + } FancyLoggerBuffer.ShouldRerender = true; break; case ConsoleKey.DownArrow: @@ -96,22 +102,25 @@ void Render() } // Build - void eventSource_BuildStarted(object sender, BuildStartedEventArgs e) + private void eventSource_BuildStarted(object sender, BuildStartedEventArgs e) { } - void eventSource_BuildFinished(object sender, BuildFinishedEventArgs e) + private void eventSource_BuildFinished(object sender, BuildFinishedEventArgs e) { Succeeded = e.Succeeded; } // Project - void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e) + private void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; // If id already exists... - if (projects.ContainsKey(id)) return; + if (projects.ContainsKey(id)) + { + return; + } // Add project FancyLoggerProjectNode node = new FancyLoggerProjectNode(e); projects[id] = node; @@ -119,11 +128,14 @@ void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e) node.ShouldRerender = true; } - void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e) + private void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update line node.Finished = true; // Log @@ -131,22 +143,28 @@ void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e) } // Target - void eventSource_TargetStarted(object sender, TargetStartedEventArgs e) + private void eventSource_TargetStarted(object sender, TargetStartedEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update node.AddTarget(e); // Log node.ShouldRerender = true; } - void eventSource_TargetFinished(object sender, TargetFinishedEventArgs e) + private void eventSource_TargetFinished(object sender, TargetFinishedEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update node.FinishedTargets++; // Log @@ -154,11 +172,14 @@ void eventSource_TargetFinished(object sender, TargetFinishedEventArgs e) } // Task - void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) + private void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update node.AddTask(e); existingTasks++; @@ -166,46 +187,59 @@ void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) node.ShouldRerender = true; } - void eventSource_TaskFinished(object sender, TaskFinishedEventArgs e) + private void eventSource_TaskFinished(object sender, TaskFinishedEventArgs e) { completedTasks++; } // Raised messages, warnings and errors - void eventSource_MessageRaised(object sender, BuildMessageEventArgs e) + private void eventSource_MessageRaised(object sender, BuildMessageEventArgs e) { - if (e is TaskCommandLineEventArgs) return; + if (e is TaskCommandLineEventArgs) + { + return; + } // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update node.AddMessage(e); // Log node.ShouldRerender = true; } - void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) + private void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update node.AddWarning(e); // Log node.ShouldRerender = true; } - void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e) + + private void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e) { // Get project id int id = e.BuildEventContext!.ProjectInstanceId; - if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) return; + if (!projects.TryGetValue(id, out FancyLoggerProjectNode? node)) + { + return; + } // Update node.AddError(e); // Log node.ShouldRerender = true; } - void console_CancelKeyPressed(object? sender, ConsoleCancelEventArgs eventArgs) + private void console_CancelKeyPressed(object? sender, ConsoleCancelEventArgs eventArgs) { // Shutdown logger Shutdown(); diff --git a/src/Build/Logging/FancyLogger/FancyLoggerBuffer.cs b/src/Build/Logging/FancyLogger/FancyLoggerBuffer.cs index 04923ba5461..d18c7f02c47 100644 --- a/src/Build/Logging/FancyLogger/FancyLoggerBuffer.cs +++ b/src/Build/Logging/FancyLogger/FancyLoggerBuffer.cs @@ -1,6 +1,5 @@ // 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.Collections.Generic; @@ -23,8 +22,14 @@ public string Text { // Set text value and get wrapped lines _text = value; - if (ShouldWrapLines) WrappedText = ANSIBuilder.ANSIWrap(value, Console.BufferWidth); - else WrappedText = new List { value }; + if (ShouldWrapLines) + { + WrappedText = ANSIBuilder.ANSIWrap(value, Console.BufferWidth); + } + else + { + WrappedText = new List { value }; + } // Buffer should rerender FancyLoggerBuffer.ShouldRerender = true; } @@ -86,7 +91,11 @@ public static void Terminate() #region Rendering public static void Render() { - if (IsTerminated || !ShouldRerender) return; + if (IsTerminated || !ShouldRerender) + { + return; + } + ShouldRerender = false; Console.Write( // Write header @@ -95,9 +104,12 @@ public static void Render() // Write footer ANSIBuilder.Eraser.LineCursorToEnd() + ANSIBuilder.Cursor.Position(Console.BufferHeight - 1, 0) + // TODO: Remove and replace with actual footer - new string('-', Console.BufferWidth) +$"\nBuild progress: XX%\tTopLineIndex={TopLineIndex}" - ); - if (Lines.Count == 0) return; + new string('-', Console.BufferWidth) + $"\nBuild progress: XX%\tTopLineIndex={TopLineIndex}"); + + if (Lines.Count == 0) + { + return; + } // Iterate over lines and display on terminal string contents = string.Empty; @@ -106,17 +118,28 @@ public static void Render() foreach (FancyLoggerBufferLine line in Lines) { // Continue if accum line count + next lines < scrolling area - if (accumulatedLineCount + line.WrappedText.Count < TopLineIndex) { + if (accumulatedLineCount + line.WrappedText.Count < TopLineIndex) + { accumulatedLineCount += line.WrappedText.Count; continue; } + // Break if exceeds scrolling area - if (accumulatedLineCount - TopLineIndex > ScrollableAreaHeight) break; - foreach (string s in line.WrappedText) { + if (accumulatedLineCount - TopLineIndex > ScrollableAreaHeight) + { + break; + } + + foreach (string s in line.WrappedText) + { // Get line index relative to scroll area lineIndex = accumulatedLineCount - TopLineIndex; // Print if line in scrolling area - if (lineIndex >= 0 && lineIndex < ScrollableAreaHeight) contents += ANSIBuilder.Cursor.Position(lineIndex + 2, 0) + ANSIBuilder.Eraser.LineCursorToEnd() + s; + if (lineIndex >= 0 && lineIndex < ScrollableAreaHeight) + { + contents += ANSIBuilder.Cursor.Position(lineIndex + 2, 0) + ANSIBuilder.Eraser.LineCursorToEnd() + s; + } + accumulatedLineCount++; } } @@ -137,7 +160,11 @@ public static int GetLineIndexById(int lineId) public static FancyLoggerBufferLine? GetLineById(int lineId) { int index = GetLineIndexById(lineId); - if (index == -1) return null; + if (index == -1) + { + return null; + } + return Lines[index]; } #endregion @@ -159,7 +186,10 @@ public static int GetLineIndexById(int lineId) { // Get line index int lineIndex = GetLineIndexById(lineId); - if (lineIndex == -1) return null; + if (lineIndex == -1) + { + return null; + } // Get line end index Lines.Insert(lineIndex, line); } @@ -196,7 +226,10 @@ public static void DeleteLine(int lineId) { // Get line index int lineIndex = GetLineIndexById(lineId); - if (lineIndex == -1) return; + if (lineIndex == -1) + { + return; + } // Delete Lines.RemoveAt(lineIndex); ShouldRerender = true; diff --git a/src/Build/Logging/FancyLogger/FancyLoggerMessageNode.cs b/src/Build/Logging/FancyLogger/FancyLoggerMessageNode.cs index f31f56d213c..0b4d7b3a326 100644 --- a/src/Build/Logging/FancyLogger/FancyLoggerMessageNode.cs +++ b/src/Build/Logging/FancyLogger/FancyLoggerMessageNode.cs @@ -1,12 +1,11 @@ // 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 Microsoft.Build.Framework; namespace Microsoft.Build.Logging.FancyLogger -{ +{ public class FancyLoggerMessageNode { @@ -28,7 +27,10 @@ public enum MessageType public FancyLoggerMessageNode(LazyFormattedBuildEventArgs args) { Message = args.Message ?? string.Empty; - if (Message.Length > MAX_LENGTH) Message = Message.Substring(0, MAX_LENGTH - 1) + "…"; + if (Message.Length > MAX_LENGTH) + { + Message = Message.Substring(0, MAX_LENGTH - 1) + "…"; + } // Get type switch (args) { @@ -73,7 +75,11 @@ public string ToANSIString() // TODO: Rename to Log after FancyLogger's API becomes internal public void Log() { - if (Line == null) return; + if (Line == null) + { + return; + } + Line.Text = $" └── {ToANSIString()}"; } } diff --git a/src/Build/Logging/FancyLogger/FancyLoggerProjectNode.cs b/src/Build/Logging/FancyLogger/FancyLoggerProjectNode.cs index 46553f529f2..00e1cd8090a 100644 --- a/src/Build/Logging/FancyLogger/FancyLoggerProjectNode.cs +++ b/src/Build/Logging/FancyLogger/FancyLoggerProjectNode.cs @@ -1,6 +1,5 @@ // 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.Collections.Generic; @@ -9,7 +8,7 @@ using Microsoft.Build.Framework; namespace Microsoft.Build.Logging.FancyLogger -{ +{ internal class FancyLoggerProjectNode { /// @@ -59,7 +58,11 @@ public FancyLoggerProjectNode(ProjectStartedEventArgs args) // TODO: Rename to Render() after FancyLogger's API becomes internal public void Log() { - if (!ShouldRerender) return; + if (!ShouldRerender) + { + return; + } + ShouldRerender = false; // Project details string lineContents = ANSIBuilder.Alignment.SpaceBetween( @@ -68,37 +71,72 @@ public void Log() // Project ANSIBuilder.Formatting.Dim("Project: ") + // Project file path with color - $"{ANSIBuilder.Formatting.Color(ANSIBuilder.Formatting.Bold(GetUnambiguousPath(ProjectPath)), Finished ? ANSIBuilder.Formatting.ForegroundColor.Green : ANSIBuilder.Formatting.ForegroundColor.Default )} [{TargetFramework ?? "*"}]", + $"{ANSIBuilder.Formatting.Color(ANSIBuilder.Formatting.Bold(GetUnambiguousPath(ProjectPath)), Finished ? ANSIBuilder.Formatting.ForegroundColor.Green : ANSIBuilder.Formatting.ForegroundColor.Default)} [{TargetFramework ?? "*"}]", $"({MessageCount} Messages, {WarningCount} Warnings, {ErrorCount} Errors)", - Console.WindowWidth - ); + Console.WindowWidth); + // Create or update line - if (Line is null) Line = FancyLoggerBuffer.WriteNewLine(lineContents, false); - else Line.Text = lineContents; + if (Line is null) + { + Line = FancyLoggerBuffer.WriteNewLine(lineContents, false); + } + else + { + Line.Text = lineContents; + } // For finished projects if (Finished) { - if (CurrentTargetLine is not null) FancyLoggerBuffer.DeleteLine(CurrentTargetLine.Id); + if (CurrentTargetLine is not null) + { + FancyLoggerBuffer.DeleteLine(CurrentTargetLine.Id); + } + foreach (FancyLoggerMessageNode node in AdditionalDetails.ToList()) { // Only delete high priority messages - if (node.Type != FancyLoggerMessageNode.MessageType.HighPriorityMessage) continue; - if (node.Line is not null) FancyLoggerBuffer.DeleteLine(node.Line.Id); + if (node.Type != FancyLoggerMessageNode.MessageType.HighPriorityMessage) + { + continue; + } + + if (node.Line is not null) + { + FancyLoggerBuffer.DeleteLine(node.Line.Id); + } } } // Current target details - if (CurrentTargetNode is null) return; + if (CurrentTargetNode is null) + { + return; + } + string currentTargetLineContents = $" └── {CurrentTargetNode.TargetName} : {CurrentTargetNode.CurrentTaskNode?.TaskName ?? String.Empty}"; - if (CurrentTargetLine is null) CurrentTargetLine = FancyLoggerBuffer.WriteNewLineAfter(Line!.Id, currentTargetLineContents); - else CurrentTargetLine.Text = currentTargetLineContents; + if (CurrentTargetLine is null) + { + CurrentTargetLine = FancyLoggerBuffer.WriteNewLineAfter(Line!.Id, currentTargetLineContents); + } + else + { + CurrentTargetLine.Text = currentTargetLineContents; + } // Messages, warnings and errors foreach (FancyLoggerMessageNode node in AdditionalDetails) { - if (Finished && node.Type == FancyLoggerMessageNode.MessageType.HighPriorityMessage) continue; - if (node.Line is null) node.Line = FancyLoggerBuffer.WriteNewLineAfter(Line!.Id, "Message"); + if (Finished && node.Type == FancyLoggerMessageNode.MessageType.HighPriorityMessage) + { + continue; + } + + if (node.Line is null) + { + node.Line = FancyLoggerBuffer.WriteNewLineAfter(Line!.Id, "Message"); + } + node.Log(); } } @@ -112,12 +150,22 @@ public FancyLoggerTargetNode AddTarget(TargetStartedEventArgs args) { // Get target id int targetId = args.BuildEventContext!.TargetId; - if (CurrentTargetNode?.Id == targetId) return CurrentTargetNode.AddTask(args); - else return null; + if (CurrentTargetNode?.Id == targetId) + { + return CurrentTargetNode.AddTask(args); + } + else + { + return null; + } } public FancyLoggerMessageNode? AddMessage(BuildMessageEventArgs args) { - if (args.Importance != MessageImportance.High) return null; + if (args.Importance != MessageImportance.High) + { + return null; + } + MessageCount++; FancyLoggerMessageNode node = new FancyLoggerMessageNode(args); AdditionalDetails.Add(node); diff --git a/src/Build/Logging/FancyLogger/FancyLoggerTargetNode.cs b/src/Build/Logging/FancyLogger/FancyLoggerTargetNode.cs index 0c5ad00ed4f..40084364fe4 100644 --- a/src/Build/Logging/FancyLogger/FancyLoggerTargetNode.cs +++ b/src/Build/Logging/FancyLogger/FancyLoggerTargetNode.cs @@ -1,11 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// using Microsoft.Build.Framework; namespace Microsoft.Build.Logging.FancyLogger -{ +{ public class FancyLoggerTargetNode { diff --git a/src/Build/Logging/FancyLogger/FancyLoggerTaskNode.cs b/src/Build/Logging/FancyLogger/FancyLoggerTaskNode.cs index d645a5daedc..e91704b5476 100644 --- a/src/Build/Logging/FancyLogger/FancyLoggerTaskNode.cs +++ b/src/Build/Logging/FancyLogger/FancyLoggerTaskNode.cs @@ -1,11 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// using Microsoft.Build.Framework; namespace Microsoft.Build.Logging.FancyLogger -{ +{ public class FancyLoggerTaskNode { diff --git a/src/Build/Logging/FileLogger.cs b/src/Build/Logging/FileLogger.cs index 100370273f7..156ee0c58e5 100644 --- a/src/Build/Logging/FileLogger.cs +++ b/src/Build/Logging/FileLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -163,11 +163,17 @@ public override void Shutdown() /// private void ParseFileLoggerParameters() { - if (Parameters == null) return; + if (Parameters == null) + { + return; + } foreach (string parameter in Parameters.Split(s_fileLoggerParameterDelimiters)) { - if (parameter.Length <= 0) continue; + if (parameter.Length <= 0) + { + continue; + } var parameterAndValue = parameter.Split(s_fileLoggerParameterValueSplitCharacter); diff --git a/src/Build/Logging/IConsoleConfiguration.cs b/src/Build/Logging/IConsoleConfiguration.cs index 86ff9c4ea47..bfbf415b9c2 100644 --- a/src/Build/Logging/IConsoleConfiguration.cs +++ b/src/Build/Logging/IConsoleConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; diff --git a/src/Build/Logging/InProcessConsoleConfiguration.cs b/src/Build/Logging/InProcessConsoleConfiguration.cs index d070e246773..06bbc8f3e55 100644 --- a/src/Build/Logging/InProcessConsoleConfiguration.cs +++ b/src/Build/Logging/InProcessConsoleConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; diff --git a/src/Build/Logging/LogFormatter.cs b/src/Build/Logging/LogFormatter.cs index 5dfc1207455..280feeedc1f 100644 --- a/src/Build/Logging/LogFormatter.cs +++ b/src/Build/Logging/LogFormatter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -12,7 +12,7 @@ namespace Microsoft.Build.BackEnd.Logging /// /// Utility helper functions for formatting logger output. /// - static internal class LogFormatter + internal static class LogFormatter { /// /// Formats the timestamp in the log as Hours:Minutes:Seconds.Milliseconds diff --git a/src/Build/Logging/LoggerDescription.cs b/src/Build/Logging/LoggerDescription.cs index 560d96c4c30..3f9dff7f034 100644 --- a/src/Build/Logging/LoggerDescription.cs +++ b/src/Build/Logging/LoggerDescription.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -31,14 +31,12 @@ internal LoggerDescription() /// /// Creates a logger description from given data /// - public LoggerDescription - ( + public LoggerDescription( string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, - LoggerVerbosity verbosity - ) : this(loggerClassName, + LoggerVerbosity verbosity) : this(loggerClassName, loggerAssemblyName, loggerAssemblyFile, loggerSwitchParameters, @@ -50,15 +48,13 @@ LoggerVerbosity verbosity /// /// Creates a logger description from given data /// - public LoggerDescription - ( + public LoggerDescription( string loggerClassName, string loggerAssemblyName, string loggerAssemblyFile, string loggerSwitchParameters, LoggerVerbosity verbosity, - bool isOptional - ) + bool isOptional) { _loggerClassName = loggerClassName; @@ -353,7 +349,7 @@ void ITranslatable.Translate(ITranslator translator) translator.Translate(ref _loggerId); } - static internal LoggerDescription FactoryForTranslation(ITranslator translator) + internal static LoggerDescription FactoryForTranslation(ITranslator translator) { LoggerDescription description = new LoggerDescription(); ((ITranslatable)description).Translate(translator); diff --git a/src/Build/Logging/NullCentralLogger.cs b/src/Build/Logging/NullCentralLogger.cs index 5946cb57a13..86c1ef56a51 100644 --- a/src/Build/Logging/NullCentralLogger.cs +++ b/src/Build/Logging/NullCentralLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Build/Logging/ParallelLogger/ConsoleOutputAligner.cs b/src/Build/Logging/ParallelLogger/ConsoleOutputAligner.cs index 2e92c39751e..204ed5ceee8 100644 --- a/src/Build/Logging/ParallelLogger/ConsoleOutputAligner.cs +++ b/src/Build/Logging/ParallelLogger/ConsoleOutputAligner.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs b/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs index 8d7cf63540a..6fc7b7e6702 100644 --- a/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs +++ b/src/Build/Logging/ParallelLogger/ParallelConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -50,8 +50,7 @@ public ParallelConsoleLogger(LoggerVerbosity verbosity) verbosity, new WriteHandler(Console.Out.Write), new ColorSetter(SetColor), - new ColorResetter(ResetColor) - ) + new ColorResetter(ResetColor)) { // do nothing } @@ -59,13 +58,11 @@ public ParallelConsoleLogger(LoggerVerbosity verbosity) /// /// Initializes the logger, with alternate output handlers. /// - public ParallelConsoleLogger - ( + public ParallelConsoleLogger( LoggerVerbosity verbosity, WriteHandler write, ColorSetter colorSet, - ColorResetter colorReset - ) + ColorResetter colorReset) { InitializeConsoleMethods(verbosity, write, colorSet, colorReset); _deferredMessages = new Dictionary>(s_compareContextNodeId); @@ -224,7 +221,10 @@ public override void BuildStartedHandler(object sender, BuildStartedEventArgs e) buildStarted = e.Timestamp; _hasBuildStarted = true; - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } if (IsVerbosityAtLeast(LoggerVerbosity.Normal)) { @@ -345,12 +345,18 @@ public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs /// private void ShowFlatErrorWarningSummary() { - if (warningList.Count == 0 && errorList.Count == 0) return; + if (warningList.Count == 0 && errorList.Count == 0) + { + return; + } // If we're showing only warnings and/or errors, don't summarize. // This is the buildc.err case. There's no point summarizing since we'd just // repeat the entire log content again. - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } // Make some effort to distinguish this summary from the output above, since otherwise // it's not clear in lower verbosities @@ -384,12 +390,18 @@ private void ShowFlatErrorWarningSummary() /// private void ShowNestedErrorWarningSummary() { - if (warningList.Count == 0 && errorList.Count == 0) return; + if (warningList.Count == 0 && errorList.Count == 0) + { + return; + } // If we're showing only warnings and/or errors, don't summarize. // This is the buildc.err case. There's no point summarizing since we'd just // repeat the entire log content again. - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } if (warningCount > 0) { @@ -602,7 +614,7 @@ private string ReadProjectConfigurationDescription(IEnumerable items) // Add the item value to the string to be printed in error/warning messages. if (!descriptionEmpty) { - projectConfigurationDescription.Append(" "); + projectConfigurationDescription.Append(" "); } projectConfigurationDescription.Append(itemSpec); @@ -720,7 +732,11 @@ public override void ProjectFinishedHandler(object sender, ProjectFinishedEventA /// List of properties internal void WriteProperties(BuildEventArgs e, IEnumerable properties) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } + var propertyList = ExtractPropertyList(properties); // if there are no properties to display return out of the method and dont print out anything related to displaying @@ -783,7 +799,11 @@ internal override void OutputEnvironment(IDictionary environment /// List of items internal void WriteItems(BuildEventArgs e, IEnumerable items) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } + SortedList itemList = ExtractItemList(items); // If there are no Items to display return out of the method and don't print out anything related to displaying @@ -1099,7 +1119,10 @@ public override void WarningHandler(object sender, BuildWarningEventArgs e) /// public override void MessageHandler(object sender, BuildMessageEventArgs e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); bool print = false; @@ -1127,8 +1150,7 @@ public override void MessageHandler(object sender, BuildMessageEventArgs e) _hasBuildStarted && e.BuildEventContext.ProjectContextId != BuildEventContext.InvalidProjectContextId && _buildEventManager.GetProjectStartedEvent(e.BuildEventContext) == null - && IsVerbosityAtLeast(LoggerVerbosity.Normal) - ) + && IsVerbosityAtLeast(LoggerVerbosity.Normal)) { if (!_deferredMessages.TryGetValue(e.BuildEventContext, out List messageList)) { @@ -1189,7 +1211,10 @@ public override void StatusEventHandler(object sender, BuildStatusEventArgs e) private void DisplayDeferredStartedEvents(BuildEventContext e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } // Display any project started events which were deferred until a visible // message from their project is displayed @@ -1388,7 +1413,10 @@ private void WriteBasedOnPrefix(string nonNullMessage, bool prefixAlreadyWritten /// private void DisplayDeferredTargetStartedEvent(BuildEventContext e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } // Get the deferred target started event TargetStartedEventMinimumFields targetStartedEvent = _buildEventManager.GetTargetStartedEvent(e); @@ -1460,7 +1488,10 @@ private void DisplayDeferredTargetStartedEvent(BuildEventContext e) /// private void DisplayDeferredProjectStartedEvent(BuildEventContext e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } if (!SkipProjectStartedText) { @@ -1530,7 +1561,10 @@ private void DisplayDeferredProjectStartedEvent(BuildEventContext e) /// public override void CustomEventHandler(object sender, CustomBuildEventArgs e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); if (IsVerbosityAtLeast(LoggerVerbosity.Detailed)) @@ -1616,7 +1650,7 @@ private ProjectFullKey GetFullProjectKey(BuildEventContext e) /// /// Task name or target name. /// Table that has tasks or targets. - internal new static MPPerformanceCounter GetPerformanceCounter(string scopeName, ref Dictionary table) + internal static new MPPerformanceCounter GetPerformanceCounter(string scopeName, ref Dictionary table) { // Lazily construct the performance counter table. if (table == null) diff --git a/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs b/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs index 5603b9480f1..0774ad98fbd 100644 --- a/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs +++ b/src/Build/Logging/ParallelLogger/ParallelLoggerHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Build/Logging/ProfilerLogger.cs b/src/Build/Logging/ProfilerLogger.cs index a2338b8f051..a67d513a099 100644 --- a/src/Build/Logging/ProfilerLogger.cs +++ b/src/Build/Logging/ProfilerLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -271,8 +271,7 @@ private static ProfiledLocation AggregateProfiledLocation(ProfiledLocation locat return new ProfiledLocation( location.InclusiveTime + otherLocation.InclusiveTime, location.ExclusiveTime + otherLocation.ExclusiveTime, - location.NumberOfHits + 1 - ); + location.NumberOfHits + 1); } /// diff --git a/src/Build/Logging/SerialConsoleLogger.cs b/src/Build/Logging/SerialConsoleLogger.cs index abb9c752d78..f5f8127a5c2 100644 --- a/src/Build/Logging/SerialConsoleLogger.cs +++ b/src/Build/Logging/SerialConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -42,8 +42,7 @@ public SerialConsoleLogger(LoggerVerbosity verbosity) verbosity, new WriteHandler(Console.Out.Write), new ColorSetter(SetColor), - new ColorResetter(ResetColor) - ) + new ColorResetter(ResetColor)) { // do nothing } @@ -55,13 +54,11 @@ public SerialConsoleLogger(LoggerVerbosity verbosity) /// /// /// - public SerialConsoleLogger - ( + public SerialConsoleLogger( LoggerVerbosity verbosity, WriteHandler write, ColorSetter colorSet, - ColorResetter colorReset - ) + ColorResetter colorReset) { InitializeConsoleMethods(verbosity, write, colorSet, colorReset); } @@ -192,7 +189,10 @@ public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs /// private void ShowErrorWarningSummary() { - if (warningCount == 0 && errorCount == 0) return; + if (warningCount == 0 && errorCount == 0) + { + return; + } // Make some effort to distinguish the summary from the previous output WriteNewLine(); @@ -793,12 +793,10 @@ private void SetErrorsOrWarningsOnCurrentFrame() /// /// /// - private void VerifyStack - ( + private void VerifyStack( bool condition, string unformattedMessage, - params object[] args - ) + params object[] args) { if (!condition && !ignoreLoggerErrors) { @@ -836,16 +834,14 @@ internal struct Frame /// targets to execute, in the case of a project frame /// the file name where the target is defined /// parent project file - internal Frame - ( + internal Frame( FrameType t, bool d, int indent, string s, string targets, string fileOfTarget, - string parent - ) + string parent) { type = t; displayed = d; diff --git a/src/Build/Logging/TargetConsoleConfiguration.cs b/src/Build/Logging/TargetConsoleConfiguration.cs index 57f92dad1c5..ffe1dd5a34b 100644 --- a/src/Build/Logging/TargetConsoleConfiguration.cs +++ b/src/Build/Logging/TargetConsoleConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementContainerLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementContainerLink.cs index 680ab19717c..2c9b41a85ab 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementContainerLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementContainerLink.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using Microsoft.Build.Construction; #nullable disable @@ -66,7 +67,7 @@ public abstract class ProjectElementContainerLink : ProjectElementLink /// External projects support. /// Allow for creating a local representation to external object of type /// - public abstract class ProjectChooseElementLink : ProjectElementContainerLink { } + public abstract class ProjectChooseElementLink : ProjectElementContainerLink { } /// /// External projects support. diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementLink.cs index 4a244d9e504..ea54456f041 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Xml; @@ -130,7 +130,7 @@ public abstract class ProjectElementLink : ILinkedXml public static string GetAttributeValue(ProjectElement xml, string attributeName, bool nullIfNotExists) => xml.GetAttributeValue(attributeName, nullIfNotExists); public static void SetOrRemoveAttribute(ProjectElement xml, string name, string value, bool clearAttributeCache, string reason, string param) => xml.SetOrRemoveAttributeForLink(name, value, clearAttributeCache, reason, param); public static void MarkDirty(ProjectElement xml, string reason, string param) => xml.MarkDirty(reason, param); - public static ProjectElement CreateNewInstance(ProjectElement xml, ProjectRootElement owner) => ProjectElement.CreateNewInstance(xml, owner); + public static ProjectElement CreateNewInstance(ProjectElement xml, ProjectRootElement owner) => ProjectElement.CreateNewInstance(xml, owner); public static string GetPureText(ProjectElement xml) { diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectExtensionsElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectExtensionsElementLink.cs index 73aa5b17d8f..6ef6184f13d 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectExtensionsElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectExtensionsElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectImportElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectImportElementLink.cs index 2f86d8d8722..66c7e0dae36 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectImportElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectImportElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectItemElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectItemElementLink.cs index 42e6a9220e6..5e73b38ee71 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectItemElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectItemElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectMetadataElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectMetadataElementLink.cs index 61acf75ae4b..9f866a5e636 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectMetadataElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectMetadataElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectPropertyElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectPropertyElementLink.cs index 6350b741c79..e922425729b 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectPropertyElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectPropertyElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectRootElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectRootElementLink.cs index 1408fbfe666..d45cc3f213d 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectRootElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectRootElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTargetElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTargetElementLink.cs index 5e1e0b7e430..2d194f3ce43 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTargetElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTargetElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTaskElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTaskElementLink.cs index eb51368004b..c48206524df 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTaskElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectTaskElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskBodyElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskBodyElementLink.cs index 3d8a20ff82b..142d4905c7b 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskBodyElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskBodyElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskParameterElementLink.cs b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskParameterElementLink.cs index 21dd119b625..7f56973cba1 100644 --- a/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskParameterElementLink.cs +++ b/src/Build/ObjectModelRemoting/ConstructionObjectLinks/ProjectUsingTaskParameterElementLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; diff --git a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemDefinitionLink.cs b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemDefinitionLink.cs index 7c24d5e39b7..ea9a88049be 100644 --- a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemDefinitionLink.cs +++ b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemDefinitionLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System.Collections.Generic; diff --git a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemLink.cs b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemLink.cs index d19126d1c41..6f21870c95d 100644 --- a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemLink.cs +++ b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectItemLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; diff --git a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectLink.cs b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectLink.cs index 03f7a8795a5..e2191fe7ea1 100644 --- a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectLink.cs +++ b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; @@ -68,7 +68,7 @@ public abstract class ProjectLink /// /// Access to remote . /// - public abstract ICollection ItemsIgnoringCondition { get; } + public abstract ICollection ItemsIgnoringCondition { get; } /// /// Access to remote . diff --git a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectMetadataLink.cs b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectMetadataLink.cs index b26bdcf2f47..3de25352558 100644 --- a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectMetadataLink.cs +++ b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectMetadataLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; diff --git a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectPropertyLink.cs b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectPropertyLink.cs index a51ba9ad286..871e816cd37 100644 --- a/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectPropertyLink.cs +++ b/src/Build/ObjectModelRemoting/DefinitionObjectsLinks/ProjectPropertyLink.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; diff --git a/src/Build/ObjectModelRemoting/ExternalProjectsProvider.cs b/src/Build/ObjectModelRemoting/ExternalProjectsProvider.cs index 745c21994a2..beec7af47b9 100644 --- a/src/Build/ObjectModelRemoting/ExternalProjectsProvider.cs +++ b/src/Build/ObjectModelRemoting/ExternalProjectsProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Evaluation; diff --git a/src/Build/ObjectModelRemoting/LinkedObjectFactory.cs b/src/Build/ObjectModelRemoting/LinkedObjectFactory.cs index b6b534637e0..76b3a0a5f4c 100644 --- a/src/Build/ObjectModelRemoting/LinkedObjectFactory.cs +++ b/src/Build/ObjectModelRemoting/LinkedObjectFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; @@ -107,7 +107,7 @@ public ProjectMetadata Create(ProjectMetadataLink link, object parent = null) return new LinkedProjectMetadata(parent, link); } - public ProjectProperty Create(ProjectPropertyLink link, Project project = null ) + public ProjectProperty Create(ProjectPropertyLink link, Project project = null) { project ??= link.Project; diff --git a/src/Build/Resources/AssemblyResources.cs b/src/Build/Resources/AssemblyResources.cs index 76db7b0f1b2..f6113241bf7 100644 --- a/src/Build/Resources/AssemblyResources.cs +++ b/src/Build/Resources/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/Build/Resources/Constants.cs b/src/Build/Resources/Constants.cs index 211f8cd00fa..fb8c9b64a74 100644 --- a/src/Build/Resources/Constants.cs +++ b/src/Build/Resources/Constants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build/Resources/MSBuildAssemblyFileVersion.cs b/src/Build/Resources/MSBuildAssemblyFileVersion.cs index be8d883559e..14b044481eb 100644 --- a/src/Build/Resources/MSBuildAssemblyFileVersion.cs +++ b/src/Build/Resources/MSBuildAssemblyFileVersion.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; diff --git a/src/Build/Utilities/EngineFileUtilities.cs b/src/Build/Utilities/EngineFileUtilities.cs index fbe306e3632..997b6c29c0c 100644 --- a/src/Build/Utilities/EngineFileUtilities.cs +++ b/src/Build/Utilities/EngineFileUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -54,13 +54,11 @@ internal static void CaptureLazyWildcardRegexes() /// and EvaluationLoggingContext. /// Location of Exclude element in file, used after drive enumeration detection. /// Array of file paths, unescaped. - internal static string[] GetFileListUnescaped - ( + internal static string[] GetFileListUnescaped( string directoryEscaped, string filespecEscaped, object loggingMechanism = null, - IElementLocation excludeLocation = null - ) + IElementLocation excludeLocation = null) { return GetFileList( directoryEscaped, @@ -99,8 +97,7 @@ internal static string[] GetFileListUnescaped /// Flag used to detect when to properly log a warning /// for the Exclude attribute after detecting a drive enumerating wildcard. /// Array of file paths, escaped. - internal static string[] GetFileListEscaped - ( + internal static string[] GetFileListEscaped( string directoryEscaped, string filespecEscaped, IEnumerable excludeSpecsEscaped = null, @@ -112,8 +109,7 @@ internal static string[] GetFileListEscaped IElementLocation importLocation = null, BuildEventContext buildEventContext = null, string buildEventFileInfoFullPath = null, - bool disableExcludeDriveEnumerationWarning = false - ) + bool disableExcludeDriveEnumerationWarning = false) { return GetFileList( directoryEscaped, @@ -172,8 +168,7 @@ internal static bool FilespecHasWildcards(string filespecEscaped) /// Flag used to detect when to properly log a warning /// for the Exclude attribute after detecting a drive enumerating wildcard. /// Array of file paths. - private static string[] GetFileList - ( + private static string[] GetFileList( string directoryEscaped, string filespecEscaped, bool returnEscaped, @@ -186,8 +181,7 @@ private static string[] GetFileList IElementLocation importLocation = null, BuildEventContext buildEventContext = null, string buildEventFileInfoFullPath = null, - bool disableExcludeDriveEnumerationWarning = false - ) + bool disableExcludeDriveEnumerationWarning = false) { ErrorUtilities.VerifyThrowInternalLength(filespecEscaped, nameof(filespecEscaped)); @@ -240,7 +234,7 @@ private static string[] GetFileList includeLocation, excludeLocation, excludeFileSpecIsEmpty, - disableExcludeDriveEnumerationWarning, + disableExcludeDriveEnumerationWarning, fileSpec); break; diff --git a/src/Build/Utilities/FileSpecMatchTester.cs b/src/Build/Utilities/FileSpecMatchTester.cs index f3c56d13061..977655e7fa2 100644 --- a/src/Build/Utilities/FileSpecMatchTester.cs +++ b/src/Build/Utilities/FileSpecMatchTester.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using System; diff --git a/src/Build/Utilities/NuGetFrameworkWrapper.cs b/src/Build/Utilities/NuGetFrameworkWrapper.cs index 9d3546fcf37..52f72bca45c 100644 --- a/src/Build/Utilities/NuGetFrameworkWrapper.cs +++ b/src/Build/Utilities/NuGetFrameworkWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Build/Utilities/ReaderWriterLockSlimExtensions.cs b/src/Build/Utilities/ReaderWriterLockSlimExtensions.cs index d837ef7630c..b9c06e9905e 100644 --- a/src/Build/Utilities/ReaderWriterLockSlimExtensions.cs +++ b/src/Build/Utilities/ReaderWriterLockSlimExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Threading; diff --git a/src/Build/Utilities/RegistryKeyWrapper.cs b/src/Build/Utilities/RegistryKeyWrapper.cs index e8f386c6f61..32934034dee 100644 --- a/src/Build/Utilities/RegistryKeyWrapper.cs +++ b/src/Build/Utilities/RegistryKeyWrapper.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #if FEATURE_WIN32_REGISTRY using System; @@ -173,7 +174,9 @@ public virtual RegistryKeyWrapper OpenSubKey(string name) catch (Exception ex) { if (ExceptionHandling.NotExpectedRegistryException(ex)) + { throw; + } throw new RegistryException(ex.Message, wrapper.Name + "\\" + keyNames[i], ex); } diff --git a/src/Build/Utilities/SimpleVersion.cs b/src/Build/Utilities/SimpleVersion.cs index dd665af000e..82f23426a39 100644 --- a/src/Build/Utilities/SimpleVersion.cs +++ b/src/Build/Utilities/SimpleVersion.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using System; @@ -166,12 +166,12 @@ private static bool ParseComponent(ref ReadOnlySpan span, out int value) private static int ParseComponent(ReadOnlySpan span) { - #if NETFRAMEWORK +#if NETFRAMEWORK // Cannot parse int from span on .NET Framework, so allocate the substring var spanOrString = span.ToString(); - #else +#else var spanOrString = span; - #endif +#endif if (!int.TryParse(spanOrString, NumberStyles.None, CultureInfo.InvariantCulture, out int value)) { diff --git a/src/Build/Utilities/Utilities.cs b/src/Build/Utilities/Utilities.cs index 3e8d07e7846..12e73b4806b 100644 --- a/src/Build/Utilities/Utilities.cs +++ b/src/Build/Utilities/Utilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -24,7 +24,7 @@ namespace Microsoft.Build.Internal /// /// This class contains utility methods for the MSBuild engine. /// - static internal class Utilities + internal static class Utilities { /// /// Save off the contents of the environment variable that specifies whether we should treat higher toolsversions as the current @@ -355,7 +355,7 @@ internal static string GenerateToolsVersionToUse(string explicitToolsVersion, st // This is higher than the 'legacy' toolsversion values. // Therefore we need to enter best effort mode and // present the current one. - if (toolsVersionAsVersion > new Version(15,0)) + if (toolsVersionAsVersion > new Version(15, 0)) { toolsVersionToUse = MSBuildConstants.CurrentToolsVersion; } diff --git a/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs b/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs index 022027b249a..d0ea43ec76e 100644 --- a/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs +++ b/src/Build/Xml/ProjectXmlUtilities.XmlElementChildIterator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -10,7 +10,7 @@ namespace Microsoft.Build.Internal { - partial class ProjectXmlUtilities + internal partial class ProjectXmlUtilities { // Iterating an element's nodes allocates an non-trivial amount of data in certain // large solutions with lots of targets, so we have our own struct-based iterator diff --git a/src/Build/Xml/ProjectXmlUtilities.cs b/src/Build/Xml/ProjectXmlUtilities.cs index 40c33d8c30b..e9c01d6bd13 100644 --- a/src/Build/Xml/ProjectXmlUtilities.cs +++ b/src/Build/Xml/ProjectXmlUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -128,15 +128,13 @@ internal static void VerifyThrowProjectAttributeEitherMissingOrNotEmpty(XmlEleme /// internal static void VerifyThrowProjectAttributeEitherMissingOrNotEmpty(XmlElementWithLocation xmlElement, XmlAttributeWithLocation attribute, string attributeName) { - ProjectErrorUtilities.VerifyThrowInvalidProject - ( + ProjectErrorUtilities.VerifyThrowInvalidProject( attribute == null || attribute.Value.Length > 0, attribute?.Location, "InvalidAttributeValue", String.Empty, attributeName, - xmlElement.Name - ); + xmlElement.Name); } /// diff --git a/src/Build/Xml/XmlReaderExtension.cs b/src/Build/Xml/XmlReaderExtension.cs index 8cfd9b6497e..d0cf997b9c7 100644 --- a/src/Build/Xml/XmlReaderExtension.cs +++ b/src/Build/Xml/XmlReaderExtension.cs @@ -1,4 +1,7 @@ -using System; +// 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.IO; using System.Text; using System.Xml; @@ -83,7 +86,7 @@ private static XmlReader GetXmlReader(string file, StreamReader input, bool load { string uri = new UriBuilder(Uri.UriSchemeFile, string.Empty) { Path = file }.ToString(); - + // Ignore loadAsReadOnly for now; using XmlReader.Create results in whitespace changes // of attribute text, specifically newline removal. // https://github.com/dotnet/msbuild/issues/4210 diff --git a/src/Deprecated/Conversion/AdditionalOptionsParser.cs b/src/Deprecated/Conversion/AdditionalOptionsParser.cs index 1695918ddb2..13ef74e260c 100644 --- a/src/Deprecated/Conversion/AdditionalOptionsParser.cs +++ b/src/Deprecated/Conversion/AdditionalOptionsParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -247,7 +247,8 @@ private string[] TokenizeAdditionalOptionsValue(string additionalOptionsValue) { switch (c) { - case '\t': case ' ': + case '\t': + case ' ': if (inQuotes) { option.Append(c); @@ -260,15 +261,15 @@ private string[] TokenizeAdditionalOptionsValue(string additionalOptionsValue) option.Length = 0; } } - break; + break; case '"': inQuotes = !inQuotes; - break; + break; default: option.Append(c); - break; + break; } } @@ -291,7 +292,7 @@ private bool ExtractSwitchInfo(CompSwitchInfo compSwitchInfo, string compSwitch) { string matchedID = null; // First see if we have a match... - for (int i=0; i /// SumedhK - static internal class AssemblyResources + internal static class AssemblyResources { /// /// Loads the specified resource string, either from the assembly's primary resources, or its shared resources. diff --git a/src/Deprecated/Conversion/Constants.cs b/src/Deprecated/Conversion/Constants.cs index a757f51f37c..5a7c52a3c3b 100644 --- a/src/Deprecated/Conversion/Constants.cs +++ b/src/Deprecated/Conversion/Constants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; @@ -9,10 +9,10 @@ namespace Microsoft.Build.Conversion /// Contains strings identifying hint paths that we should remove /// /// AJenner - static internal class LegacyFrameworkPaths + internal static class LegacyFrameworkPaths { - internal const string RTMFrameworkPath = "MICROSOFT.NET\\FRAMEWORK\\V1.0.3705"; - internal const string EverettFrameworkPath = "MICROSOFT.NET\\FRAMEWORK\\V1.1.4322"; + internal const string RTMFrameworkPath = "MICROSOFT.NET\\FRAMEWORK\\V1.0.3705"; + internal const string EverettFrameworkPath = "MICROSOFT.NET\\FRAMEWORK\\V1.1.4322"; internal const string JSharpRTMFrameworkPath = "MICROSOFT VISUAL JSHARP .NET\\FRAMEWORK\\V1.0.4205"; } @@ -20,182 +20,182 @@ static internal class LegacyFrameworkPaths /// Contains the names of the known elements in the VS.NET project file. /// /// RGoel - static internal class VSProjectElements + internal static class VSProjectElements { internal const string visualStudioProject = "VisualStudioProject"; - internal const string visualJSharp = "VISUALJSHARP"; - internal const string cSharp = "CSHARP"; - internal const string visualBasic = "VisualBasic"; - internal const string ECSharp = "ECSHARP"; - internal const string EVisualBasic = "EVisualBasic"; - internal const string build = "Build"; - internal const string settings = "Settings"; - internal const string config = "Config"; - internal const string platform = "Platform"; + internal const string visualJSharp = "VISUALJSHARP"; + internal const string cSharp = "CSHARP"; + internal const string visualBasic = "VisualBasic"; + internal const string ECSharp = "ECSHARP"; + internal const string EVisualBasic = "EVisualBasic"; + internal const string build = "Build"; + internal const string settings = "Settings"; + internal const string config = "Config"; + internal const string platform = "Platform"; internal const string interopRegistration = "InteropRegistration"; - internal const string references = "References"; - internal const string reference = "Reference"; - internal const string files = "Files"; - internal const string imports = "Imports"; - internal const string import = "Import"; - internal const string include = "Include"; - internal const string exclude = "Exclude"; - internal const string file = "File"; - internal const string folder = "Folder"; - internal const string startupServices = "StartupServices"; - internal const string service = "Service"; - internal const string userProperties = "UserProperties"; - internal const string otherProjectSettings= "OtherProjectSettings"; - internal const string PocketPC = "Pocket PC"; - internal const string WindowsCE = "Windows CE"; - internal const string Smartphone = "Smartphone"; - internal const string SystemDataCommon = "System.Data.Common"; - internal const string SystemSR = "System.SR"; - internal const string MSCorLib = "MSCorLib"; + internal const string references = "References"; + internal const string reference = "Reference"; + internal const string files = "Files"; + internal const string imports = "Imports"; + internal const string import = "Import"; + internal const string include = "Include"; + internal const string exclude = "Exclude"; + internal const string file = "File"; + internal const string folder = "Folder"; + internal const string startupServices = "StartupServices"; + internal const string service = "Service"; + internal const string userProperties = "UserProperties"; + internal const string otherProjectSettings = "OtherProjectSettings"; + internal const string PocketPC = "Pocket PC"; + internal const string WindowsCE = "Windows CE"; + internal const string Smartphone = "Smartphone"; + internal const string SystemDataCommon = "System.Data.Common"; + internal const string SystemSR = "System.SR"; + internal const string MSCorLib = "MSCorLib"; } /// /// Contains the names of the known elements in the VS.NET project file. /// /// RGoel - static internal class VSProjectAttributes + internal static class VSProjectAttributes { - internal const string relPath = "RelPath"; - internal const string name = "Name"; - internal const string guid = "Guid"; - internal const string project = "Project"; - internal const string projectType = "ProjectType"; - internal const string local = "Local"; - internal const string assemblyName = "AssemblyName"; - internal const string importNamespace = "Namespace"; - internal const string id = "ID"; - internal const string link = "Link"; - internal const string buildAction = "BuildAction"; - internal const string buildActionNone = "None"; + internal const string relPath = "RelPath"; + internal const string name = "Name"; + internal const string guid = "Guid"; + internal const string project = "Project"; + internal const string projectType = "ProjectType"; + internal const string local = "Local"; + internal const string assemblyName = "AssemblyName"; + internal const string importNamespace = "Namespace"; + internal const string id = "ID"; + internal const string link = "Link"; + internal const string buildAction = "BuildAction"; + internal const string buildActionNone = "None"; internal const string buildActionResource = "EmbeddedResource"; - internal const string webReferences = "WebReferences"; - internal const string webReferenceUrl = "WebReferenceUrl"; - internal const string projectGuid = "ProjectGuid"; - internal const string preBuildEvent = "PreBuildEvent"; - internal const string postBuildEvent = "PostBuildEvent"; - internal const string productVersion = "ProductVersion"; - internal const string schemaVersion = "SchemaVersion"; - internal const string outputPath = "OutputPath"; - internal const string officeDocumentPath = "OfficeDocumentPath"; - internal const string officeDocumentType = "OfficeProjectType"; - internal const string officeProject = "OfficeProject"; - internal const string additionalOptions = "AdditionalOptions"; - internal const string platform = "Platform"; - internal const string selectedDevice = "SelectedDevice"; - internal const string deploymentPlatform = "DeploymentPlatform"; - internal const string incrementalBuild = "IncrementalBuild"; - internal const string hintPath = "HintPath"; - internal const string documentationFile = "DocumentationFile"; - internal const string debugType = "DebugType"; - internal const string debugTypeNone = "none"; - internal const string debugTypeFull = "full"; - internal const string errorReport = "ErrorReport"; - internal const string errorReportPrompt = "prompt"; + internal const string webReferences = "WebReferences"; + internal const string webReferenceUrl = "WebReferenceUrl"; + internal const string projectGuid = "ProjectGuid"; + internal const string preBuildEvent = "PreBuildEvent"; + internal const string postBuildEvent = "PostBuildEvent"; + internal const string productVersion = "ProductVersion"; + internal const string schemaVersion = "SchemaVersion"; + internal const string outputPath = "OutputPath"; + internal const string officeDocumentPath = "OfficeDocumentPath"; + internal const string officeDocumentType = "OfficeProjectType"; + internal const string officeProject = "OfficeProject"; + internal const string additionalOptions = "AdditionalOptions"; + internal const string platform = "Platform"; + internal const string selectedDevice = "SelectedDevice"; + internal const string deploymentPlatform = "DeploymentPlatform"; + internal const string incrementalBuild = "IncrementalBuild"; + internal const string hintPath = "HintPath"; + internal const string documentationFile = "DocumentationFile"; + internal const string debugType = "DebugType"; + internal const string debugTypeNone = "none"; + internal const string debugTypeFull = "full"; + internal const string errorReport = "ErrorReport"; + internal const string errorReportPrompt = "prompt"; } /// /// Contains the names of some of the hard-coded strings we'll be inserting into the newly converted MSBuild project file. /// /// RGoel - static internal class XMakeProjectStrings + internal static class XMakeProjectStrings { - internal const string project = "Project"; - internal const string defaultTargets = "Build"; - internal const string msbuildVersion = "MSBuildVersion"; - internal const string xmlns = "xmlns"; - internal const string importPrefix = "$(MSBuildToolsPath)\\"; - internal const string importSuffix = ".targets"; - internal const string targetsFilenamePrefix = "Microsoft."; - internal const string csharpTargets = "CSharp"; - internal const string visualBasicTargets = "VisualBasic"; - internal const string visualJSharpTargets = "VisualJSharp"; - internal const string triumphImport = "$(MSBuildExtensionsPath)\\Microsoft\\VisualStudio\\v9.0\\OfficeTools\\Microsoft.VisualStudio.OfficeTools.targets"; - internal const string officeTargetsVS2005Import = @"$(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools.targets"; - internal const string officeTargetsVS2005Import2 = @"$(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools2.targets"; - internal const string officeTargetsVS2005Repair = @"OfficeTools\Microsoft.VisualStudio.Tools.Office.targets"; - internal const string configurationPrefix = " '$(Configuration)' == '"; - internal const string configurationSuffix = "' "; - internal const string configuration = "Configuration"; - internal const string platformPrefix = " '$(Platform)' == '"; - internal const string platformSuffix = "' "; - internal const string platform = "Platform"; - internal const string configplatformPrefix = " '$(Configuration)|$(Platform)' == '"; - internal const string configplatformSeparator = "|"; - internal const string configplatformSuffix = "' "; - internal const string defaultConfiguration = "Debug"; - internal const string defaultPlatform = "AnyCPU"; - internal const string x86Platform = "x86"; - internal const string debugSymbols = "DebugSymbols"; - internal const string reference = "Reference"; - internal const string comReference = "COMReference"; - internal const string projectReference = "ProjectReference"; - internal const string import = "Import"; - internal const string service = "Service"; - internal const string folder = "Folder"; - internal const string link = "Link"; - internal const string autogen = "AutoGen"; - internal const string webReferences = "WebReferences"; - internal const string webReferenceUrl = "WebReferenceUrl"; - internal const string relPath = "RelPath"; - internal const string visualStudio = "VisualStudio"; - internal const string webRefEnableProperties = "WebReference_EnableProperties"; - internal const string webRefEnableSqlTypes = "WebReference_EnableSQLTypes"; - internal const string webRefEnableLegacyEventing = "WebReference_EnableLegacyEventingModel"; - internal const string xmlNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; + internal const string project = "Project"; + internal const string defaultTargets = "Build"; + internal const string msbuildVersion = "MSBuildVersion"; + internal const string xmlns = "xmlns"; + internal const string importPrefix = "$(MSBuildToolsPath)\\"; + internal const string importSuffix = ".targets"; + internal const string targetsFilenamePrefix = "Microsoft."; + internal const string csharpTargets = "CSharp"; + internal const string visualBasicTargets = "VisualBasic"; + internal const string visualJSharpTargets = "VisualJSharp"; + internal const string triumphImport = "$(MSBuildExtensionsPath)\\Microsoft\\VisualStudio\\v9.0\\OfficeTools\\Microsoft.VisualStudio.OfficeTools.targets"; + internal const string officeTargetsVS2005Import = @"$(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools.targets"; + internal const string officeTargetsVS2005Import2 = @"$(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools2.targets"; + internal const string officeTargetsVS2005Repair = @"OfficeTools\Microsoft.VisualStudio.Tools.Office.targets"; + internal const string configurationPrefix = " '$(Configuration)' == '"; + internal const string configurationSuffix = "' "; + internal const string configuration = "Configuration"; + internal const string platformPrefix = " '$(Platform)' == '"; + internal const string platformSuffix = "' "; + internal const string platform = "Platform"; + internal const string configplatformPrefix = " '$(Configuration)|$(Platform)' == '"; + internal const string configplatformSeparator = "|"; + internal const string configplatformSuffix = "' "; + internal const string defaultConfiguration = "Debug"; + internal const string defaultPlatform = "AnyCPU"; + internal const string x86Platform = "x86"; + internal const string debugSymbols = "DebugSymbols"; + internal const string reference = "Reference"; + internal const string comReference = "COMReference"; + internal const string projectReference = "ProjectReference"; + internal const string import = "Import"; + internal const string service = "Service"; + internal const string folder = "Folder"; + internal const string link = "Link"; + internal const string autogen = "AutoGen"; + internal const string webReferences = "WebReferences"; + internal const string webReferenceUrl = "WebReferenceUrl"; + internal const string relPath = "RelPath"; + internal const string visualStudio = "VisualStudio"; + internal const string webRefEnableProperties = "WebReference_EnableProperties"; + internal const string webRefEnableSqlTypes = "WebReference_EnableSQLTypes"; + internal const string webRefEnableLegacyEventing = "WebReference_EnableLegacyEventingModel"; + internal const string xmlNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; - internal const string cSharpGuid = "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; - internal const string visualBasicGuid = "F184B08F-C81C-45F6-A57F-5ABD9991F28F"; - internal const string visualJSharpGuid = "E6FDF86B-F3D1-11D4-8576-0002A516ECE8"; - internal const string triumphProjectTypeGuid = "BAA0C2D2-18E2-41B9-852F-F413020CAA33"; - internal const string VSDCSProjectTypeGuid = "4D628B5B-2FBC-4AA6-8C16-197242AEB884"; - internal const string VSDVBProjectTypeGuid = "68B1623D-7FB9-47D8-8664-7ECEA3297D4F"; - internal const string wpfFlavorGuid = "60dc8134-eba5-43b8-bcc9-bb4bc16c2548"; - internal const string projectTypeGuids = "ProjectTypeGuids"; - internal const string platformID = "PlatformID"; - internal const string platformFamilyName = "PlatformFamilyName"; - internal const string deployTargetSuffix = "DeployDirSuffix"; - internal const string disableCSHostProc = "\n\n"; - internal const string disableVBHostProc = "\n\n"; - internal const string SDECSTargets = "Microsoft.CompactFramework.CSharp.targets"; - internal const string SDEVBTargets = "Microsoft.CompactFramework.VisualBasic.targets"; - internal const string TargetFrameworkVersion = "TargetFrameworkVersion"; - internal const string TargetFrameworkSubset = "TargetFrameworkSubset"; - internal const string TargetFrameworkProfile = "TargetFrameworkProfile"; - internal const string ClientProfile = "Client"; - internal const string vOne = "v1.0"; - internal const string vTwo = "v2.0"; - internal const string noWarn = "NoWarn"; - internal const string disabledVBWarnings = "42016,42017,42018,42019,42032,42353,42354,42355"; - internal const string xmlFileExtension = ".xml"; - internal const string csdprojFileExtension = ".csdproj"; - internal const string vbdprojFileExtension = ".vbdproj"; - internal const string csprojFileExtension = ".csproj"; - internal const string vbprojFileExtension = ".vbproj"; - internal const string myType = "MyType"; - internal const string web = "Web"; + internal const string cSharpGuid = "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC"; + internal const string visualBasicGuid = "F184B08F-C81C-45F6-A57F-5ABD9991F28F"; + internal const string visualJSharpGuid = "E6FDF86B-F3D1-11D4-8576-0002A516ECE8"; + internal const string triumphProjectTypeGuid = "BAA0C2D2-18E2-41B9-852F-F413020CAA33"; + internal const string VSDCSProjectTypeGuid = "4D628B5B-2FBC-4AA6-8C16-197242AEB884"; + internal const string VSDVBProjectTypeGuid = "68B1623D-7FB9-47D8-8664-7ECEA3297D4F"; + internal const string wpfFlavorGuid = "60dc8134-eba5-43b8-bcc9-bb4bc16c2548"; + internal const string projectTypeGuids = "ProjectTypeGuids"; + internal const string platformID = "PlatformID"; + internal const string platformFamilyName = "PlatformFamilyName"; + internal const string deployTargetSuffix = "DeployDirSuffix"; + internal const string disableCSHostProc = "\n\n"; + internal const string disableVBHostProc = "\n\n"; + internal const string SDECSTargets = "Microsoft.CompactFramework.CSharp.targets"; + internal const string SDEVBTargets = "Microsoft.CompactFramework.VisualBasic.targets"; + internal const string TargetFrameworkVersion = "TargetFrameworkVersion"; + internal const string TargetFrameworkSubset = "TargetFrameworkSubset"; + internal const string TargetFrameworkProfile = "TargetFrameworkProfile"; + internal const string ClientProfile = "Client"; + internal const string vOne = "v1.0"; + internal const string vTwo = "v2.0"; + internal const string noWarn = "NoWarn"; + internal const string disabledVBWarnings = "42016,42017,42018,42019,42032,42353,42354,42355"; + internal const string xmlFileExtension = ".xml"; + internal const string csdprojFileExtension = ".csdproj"; + internal const string vbdprojFileExtension = ".vbdproj"; + internal const string csprojFileExtension = ".csproj"; + internal const string vbprojFileExtension = ".vbproj"; + internal const string myType = "MyType"; + internal const string web = "Web"; internal const string windowsFormsWithCustomSubMain = "WindowsFormsWithCustomSubMain"; - internal const string windows = "Windows"; - internal const string codeAnalysisRuleAssemblies = "CodeAnalysisRuleAssemblies"; - internal const string console = "Console"; - internal const string empty = "Empty"; - internal const string exe = "Exe"; - internal const string library = "Library"; - internal const string winExe = "WinExe"; - internal const string outputType = "OutputType"; - internal const string fileUpgradeFlags = "FileUpgradeFlags"; - internal const string content = "Content"; - internal const string copytooutput = "CopyToOutputDirectory"; - internal const string preservenewest = "PreserveNewest"; - internal const string toolsVersion = MSBuildConstants.CurrentToolsVersion; - internal const string vbTargetsVS2008 = @"$(MSBuildToolsPath)\Microsoft.VisualBasic.targets"; - internal const string vbTargetsVS2005 = @"$(MSBuildBinPath)\Microsoft.VisualBasic.targets"; - internal const string vsToolsPath = @"VSToolsPath"; - internal const string visualStudioVersion = @"VisualStudioVersion"; + internal const string windows = "Windows"; + internal const string codeAnalysisRuleAssemblies = "CodeAnalysisRuleAssemblies"; + internal const string console = "Console"; + internal const string empty = "Empty"; + internal const string exe = "Exe"; + internal const string library = "Library"; + internal const string winExe = "WinExe"; + internal const string outputType = "OutputType"; + internal const string fileUpgradeFlags = "FileUpgradeFlags"; + internal const string content = "Content"; + internal const string copytooutput = "CopyToOutputDirectory"; + internal const string preservenewest = "PreserveNewest"; + internal const string toolsVersion = MSBuildConstants.CurrentToolsVersion; + internal const string vbTargetsVS2008 = @"$(MSBuildToolsPath)\Microsoft.VisualBasic.targets"; + internal const string vbTargetsVS2005 = @"$(MSBuildBinPath)\Microsoft.VisualBasic.targets"; + internal const string vsToolsPath = @"VSToolsPath"; + internal const string visualStudioVersion = @"VisualStudioVersion"; internal const string toRepairPatternForAssetCompat = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\"; internal const string toRepairPatternForAssetCompatBeforeV10 = @"$(MSBuildExtensionsPath)\Microsoft\VisualStudio\"; internal const string toRepairPatternForAssetCompatV10 = @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\"; diff --git a/src/Deprecated/Conversion/OldVSProjectFileReader.cs b/src/Deprecated/Conversion/OldVSProjectFileReader.cs index cbfce91cf0b..93d3a29f1dd 100644 --- a/src/Deprecated/Conversion/OldVSProjectFileReader.cs +++ b/src/Deprecated/Conversion/OldVSProjectFileReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -33,18 +33,18 @@ internal sealed class OldVSProjectFileReader : TextReader { // This is the underlying text file where we will be reading the raw text // from. - private StreamReader oldVSProjectFile; - + private StreamReader oldVSProjectFile; + // We will be reading one line at a time out of the text file, and caching // it here. - private StringBuilder singleLine; - + private StringBuilder singleLine; + // The "TextReader" interface that we are implementing only allows // forward access through the file. You cannot seek to a random location // or read backwards. This variable is the index into the "singleLine" // string above, which indicates how far the caller has read. Once we // reach the end of "singleLine", we'll go read a new line from the file. - private int currentReadPositionWithinSingleLine; + private int currentReadPositionWithinSingleLine; /// /// Constructor, initialized using the filename of an existing old format @@ -58,7 +58,7 @@ string filename ) { this.oldVSProjectFile = new StreamReader(filename, Encoding.Default); // HIGHCHAR: Default means ANSI, ANSI is what VS .NET 2003 wrote. Without this, the project would be read as ASCII. - + this.singleLine = new StringBuilder(); this.currentReadPositionWithinSingleLine = 0; } @@ -131,9 +131,9 @@ public override int Read /// rgoel public override int Read ( - char[] bufferToReadInto, // The buffer to read the data into. - int startIndexIntoBuffer, // The index into "bufferToReadInto" - int charactersToRead // The number of characters to read. + char[] bufferToReadInto, // The buffer to read the data into. + int startIndexIntoBuffer, // The index into "bufferToReadInto" + int charactersToRead // The number of characters to read. ) { // Make sure there's enough room in the caller's buffer for what he's @@ -169,7 +169,7 @@ int charactersToRead // The number of characters to read. } // Copy characters from our cached "singleLine" to the caller's buffer. - this.singleLine.ToString().CopyTo(this.currentReadPositionWithinSingleLine, bufferToReadInto, + this.singleLine.ToString().CopyTo(this.currentReadPositionWithinSingleLine, bufferToReadInto, startIndexIntoBuffer, charactersToCopy); // Update all counts and indices. @@ -197,9 +197,9 @@ int charactersToRead // The number of characters to read. /// rgoel public override int ReadBlock ( - char[] bufferToReadInto, - int startIndexIntoBuffer, - int charactersToRead + char[] bufferToReadInto, + int startIndexIntoBuffer, + int charactersToRead ) { throw new NotImplementedException(); @@ -235,7 +235,7 @@ public override string ReadLine this.currentReadPositionWithinSingleLine = this.singleLine.Length; // Strip off the line endings before returning to caller. - char[] lineEndingCharacters = new char[] {'\r', '\n'}; + char[] lineEndingCharacters = new char[] { '\r', '\n' }; return result.Trim(lineEndingCharacters); } @@ -264,7 +264,7 @@ public override string ReadToEnd } // Append the line of text to the resulting output. - result.Append(this.singleLine.ToString(this.currentReadPositionWithinSingleLine, + result.Append(this.singleLine.ToString(this.currentReadPositionWithinSingleLine, this.singleLine.Length - this.currentReadPositionWithinSingleLine)); this.currentReadPositionWithinSingleLine = this.singleLine.Length; @@ -314,11 +314,11 @@ private bool ReadLineIntoInternalBuffer // Take the line of text just read, and replace all special characters // with the escaped XML-friendly string equivalents. this.singleLine = new StringBuilder(this.ReplaceSpecialCharacters(lineFromProjectFile)); - + // The underlying StreamReader.ReadLine method doesn't give us the // trailing line endings, so add them back ourselves. this.singleLine.Append(Environment.NewLine); - + // So now we have a new cached "singleLine". Reset the read pointer // to the beginning of the new line just read. this.currentReadPositionWithinSingleLine = 0; @@ -346,17 +346,17 @@ string originalLine // the special characters. Regex attributeValueInsideDoubleQuotesPattern = new Regex("= *\"[^\"]*\""); - string replacedStuffInsideDoubleQuotes = attributeValueInsideDoubleQuotesPattern.Replace(originalLine, + string replacedStuffInsideDoubleQuotes = attributeValueInsideDoubleQuotesPattern.Replace(originalLine, new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute)); - + // Find the stuff within single-quotes, and send it off to the // "ReplaceSpecialCharactersInXmlAttribute" for proper replacement of // the special characters. Regex attributeValueInsideSingleQuotesPattern = new Regex("= *'[^']*'"); - string replacedStuffInsideSingleQuotes = attributeValueInsideSingleQuotesPattern.Replace(replacedStuffInsideDoubleQuotes, + string replacedStuffInsideSingleQuotes = attributeValueInsideSingleQuotesPattern.Replace(replacedStuffInsideDoubleQuotes, new MatchEvaluator(this.ReplaceSpecialCharactersInXmlAttribute)); - + return replacedStuffInsideSingleQuotes; } @@ -400,7 +400,7 @@ string xmlAttributeText xmlAttributeText = xmlAttributeText.Replace("<", "<"); xmlAttributeText = xmlAttributeText.Replace(">", ">"); xmlAttributeText = ReplaceNonEscapingAmpersands(xmlAttributeText); - + return xmlAttributeText; } @@ -429,7 +429,7 @@ string xmlAttributeText // aaa&bbb should be replaced with aaa&bbb // But: // aaa<bbb should not be touched. - + // Loop through each instance of "&" int indexOfAmpersand = xmlAttributeText.IndexOf('&'); while (indexOfAmpersand != -1) @@ -448,7 +448,7 @@ string xmlAttributeText { // We found the semicolon. Capture the characters between (but not // including) the "&" and ";". - string entityName = xmlAttributeText.Substring(indexOfAmpersand + 1, + string entityName = xmlAttributeText.Substring(indexOfAmpersand + 1, indexOfNextSemicolon - indexOfAmpersand - 1); // Perf note: Here we are walking through the entire list of entities, and @@ -456,7 +456,7 @@ string xmlAttributeText // should only get executed in fairly rare circumstances. It's not very // common for people to have these embedded into their project files. bool foundEntity = false; - for (int i = 0 ; i < entities.Length ; i++) + for (int i = 0; i < entities.Length; i++) { // Case-sensitive comparison to see if the entity name matches any of // the well-known ones that were emitted by the XML writer in the VS.NET @@ -478,7 +478,7 @@ string xmlAttributeText { // At this point, we know entityName is something like "#1234" or "#x1234abcd" bool isNumber = false; - + // A lower-case "x" in the second position indicates a hexadecimal value. if ((entityName.Length > 2) && (entityName[1] == 'x')) { @@ -562,7 +562,7 @@ int indexOfAmpersand // This is the complete list of well-known entity names that were written out // by the XML writer in the VS.NET 2002/2003 project system. This list was // taken directly from the source code. - private static readonly string[] entities = + private static readonly string[] entities = { "quot", // "amp", // & - ampersand diff --git a/src/Deprecated/Conversion/ProjectFileConverter.cs b/src/Deprecated/Conversion/ProjectFileConverter.cs index 6877edb8f72..f8c13eceb4d 100644 --- a/src/Deprecated/Conversion/ProjectFileConverter.cs +++ b/src/Deprecated/Conversion/ProjectFileConverter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -185,7 +185,7 @@ public sealed class ProjectFileConverter private ArrayList conversionWarnings = null; // A list of property names whose values we need to escape when converting to Whidbey. - private Dictionary propertiesToEscape = null; + private Dictionary propertiesToEscape = null; /// /// Default constructor. We need a constructor that takes zero parameters, @@ -300,7 +300,7 @@ public string[] ConversionWarnings { get { - return (string[]) conversionWarnings.ToArray(typeof(string)); + return (string[])conversionWarnings.ToArray(typeof(string)); } } @@ -400,7 +400,7 @@ private void Initialize() this.isMyTypeAlreadySetInOriginalProject = false; this.conversionWarnings = new ArrayList(); - this.propertiesToEscape = new Dictionary(StringComparer.OrdinalIgnoreCase); + this.propertiesToEscape = new Dictionary(StringComparer.OrdinalIgnoreCase); this.propertiesToEscape.Add("ApplicationIcon", null); this.propertiesToEscape.Add("AssemblyKeyContainerName", null); this.propertiesToEscape.Add("AssemblyName", null); @@ -464,13 +464,13 @@ private void ConvertInMemoryToMSBuildProject() // but since XML comments may appear outside of the scope, // it's possible to get more than one child node. Just find the first // non-comment node. That should be the element. - foreach(XmlNode childNode in rootNodes) + foreach (XmlNode childNode in rootNodes) { if ((childNode.NodeType != XmlNodeType.Comment) && (childNode.NodeType != XmlNodeType.XmlDeclaration) && (childNode.NodeType != XmlNodeType.Whitespace)) { - visualStudioProjectElement = (XmlElementWithLocation) childNode; + visualStudioProjectElement = (XmlElementWithLocation)childNode; break; } } @@ -814,9 +814,9 @@ private IEnumerable RequiresRepairForAssetCompat() { // check if the project has the to-repair pattern in the Imports // pattern: $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\ - var toRepairImports = from import in xmakeProject.Imports - where HasRepairPattern(import) - select import; + var toRepairImports = from import in xmakeProject.Imports + where HasRepairPattern(import) + select import; return toRepairImports; } @@ -861,7 +861,9 @@ private bool HasRepairPattern(ProjectImportElement importElement) // $(MSBuildExtensionsPath)\Microsoft.VisualStudio.OfficeTools.targets if (importElement.Project.Equals(XMakeProjectStrings.officeTargetsVS2005Import, StringComparison.OrdinalIgnoreCase) || importElement.Project.Equals(XMakeProjectStrings.officeTargetsVS2005Import2, StringComparison.OrdinalIgnoreCase)) + { bHasRepairPattern = true; + } } } @@ -880,13 +882,13 @@ private bool FixTargetFrameworkSubset() foreach (ProjectPropertyElement propertyElement in xmakeProject.Properties) { - if (String.Equals(propertyElement.Name , XMakeProjectStrings.TargetFrameworkSubset, StringComparison.OrdinalIgnoreCase)) + if (String.Equals(propertyElement.Name, XMakeProjectStrings.TargetFrameworkSubset, StringComparison.OrdinalIgnoreCase)) { // For the Client profile, which was the only profile supported in Orcas SP1, we want to replace // with . if (String.Equals(propertyElement.Value, XMakeProjectStrings.ClientProfile, StringComparison.OrdinalIgnoreCase)) { - ProjectPropertyGroupElement parentGroup = (ProjectPropertyGroupElement) propertyElement.Parent; + ProjectPropertyGroupElement parentGroup = (ProjectPropertyGroupElement)propertyElement.Parent; parentGroup.SetProperty(XMakeProjectStrings.TargetFrameworkProfile, XMakeProjectStrings.ClientProfile); changedProject = true; } @@ -993,7 +995,7 @@ public bool FSharpSpecificConversions(bool actuallyMakeChanges) else if (equals(importElement.Project, fsharpPortableDev11TargetsPath)) { fsharpTargetsDev11PortableImport = importElement; - isAtLeastDev10Project= true; + isAtLeastDev10Project = true; } } @@ -1005,10 +1007,14 @@ public bool FSharpSpecificConversions(bool actuallyMakeChanges) // no other F# imports - do nothing if (fsharpTargetsFS10Import == null && fsharpTargetsFS40Import == null && fsharpTargetsFS45Import == null && fsharpTargetsDev11PortableImport == null) + { return false; + } if (!actuallyMakeChanges) + { return true; + } // both branches adds this elements to the project var chooseElement = xmakeProject.CreateChooseElement(); // (1) @@ -1085,13 +1091,24 @@ public bool FSharpSpecificConversions(bool actuallyMakeChanges) chooseElement.Parent.InsertAfterChild(dev12PlusImportElement, chooseElement); if (fsharpTargetsFS10Import != null) + { xmakeProject.RemoveChild(fsharpTargetsFS10Import); + } + if (fsharpTargetsFS40Import != null) + { xmakeProject.RemoveChild(fsharpTargetsFS40Import); + } + if (fsharpTargetsFS45Import != null) + { xmakeProject.RemoveChild(fsharpTargetsFS45Import); + } + if (fsharpTargetsDev11PortableImport != null) + { xmakeProject.RemoveChild(fsharpTargetsDev11PortableImport); + } const string ReferenceItemType = "Reference"; @@ -1188,7 +1205,7 @@ public bool FSharpSpecificConversions(bool actuallyMakeChanges) const string MinimumVisualStudioVersionProperty = "MinimumVisualStudioVersion"; var hasMinimumVSVersion = xmakeProject.Properties.Any(prop => prop.Name == MinimumVisualStudioVersionProperty); - foreach(var group in xmakeProject.PropertyGroups) + foreach (var group in xmakeProject.PropertyGroups) { // find first non-conditional property group to add TargetFSharpCoreVersion property if (string.IsNullOrEmpty(group.Condition)) @@ -1391,7 +1408,7 @@ ProjectLoadSettings projectLoadSettings private void AddXMakePropertiesFromXMLAttributes ( ProjectPropertyGroupElement propertyGroup, - XmlElement xmlElement + XmlElement xmlElement ) { error.VerifyThrow(propertyGroup != null, "Expected valid ProjectPropertyElementGroup to add properties to."); @@ -1417,7 +1434,7 @@ XmlElement xmlElement /// RGoel private void ProcessVisualStudioProjectElement ( - XmlElementWithLocation visualStudioProjectElement + XmlElementWithLocation visualStudioProjectElement ) { // Make sure this is the element. @@ -1442,7 +1459,7 @@ XmlElementWithLocation visualStudioProjectElement bool languageFound = false; // Loop through all the direct children of the element. - foreach(XmlNode visualStudioProjectChildNode in visualStudioProjectElement) + foreach (XmlNode visualStudioProjectChildNode in visualStudioProjectElement) { // Handle XML comments under the node (just ignore them) if ((visualStudioProjectChildNode.NodeType == XmlNodeType.Comment) || @@ -1493,7 +1510,7 @@ XmlElementWithLocation visualStudioProjectElement /// RGoel private void ProcessLanguageElement ( - XmlElementWithLocation languageElement + XmlElementWithLocation languageElement ) { // Make sure we have a valid XML element to process. @@ -1593,24 +1610,24 @@ XmlElementWithLocation languageElement { if (languageElement.Name == VSProjectElements.ECSharp) { - this.globalPropertyGroup.AddProperty ( XMakeProjectStrings.projectTypeGuids, + this.globalPropertyGroup.AddProperty(XMakeProjectStrings.projectTypeGuids, "{" + XMakeProjectStrings.VSDCSProjectTypeGuid + "};{" + XMakeProjectStrings.cSharpGuid + - "}" ); - string visualStudioProjectExtensions = GetProjectExtensionsString(XMakeProjectStrings.visualStudio); + "}"); + string visualStudioProjectExtensions = GetProjectExtensionsString(XMakeProjectStrings.visualStudio); visualStudioProjectExtensions += XMakeProjectStrings.disableCSHostProc; SetProjectExtensionsString(XMakeProjectStrings.visualStudio, visualStudioProjectExtensions); } else if (languageElement.Name == VSProjectElements.EVisualBasic) { - this.globalPropertyGroup.AddProperty ( XMakeProjectStrings.projectTypeGuids, + this.globalPropertyGroup.AddProperty(XMakeProjectStrings.projectTypeGuids, "{" + XMakeProjectStrings.VSDVBProjectTypeGuid + "};{" + XMakeProjectStrings.visualBasicGuid + - "}" ); + "}"); string visualStudioProjectExtensions = GetProjectExtensionsString(XMakeProjectStrings.visualStudio); visualStudioProjectExtensions += XMakeProjectStrings.disableVBHostProc; SetProjectExtensionsString(XMakeProjectStrings.visualStudio, visualStudioProjectExtensions); @@ -1618,7 +1635,7 @@ XmlElementWithLocation languageElement } // Loop through all the direct child elements of the language element. - foreach(XmlNode languageChildNode in languageElement) + foreach (XmlNode languageChildNode in languageElement) { // Handle XML comments under the the language node (just ignore them). if ((languageChildNode.NodeType == XmlNodeType.Comment) || @@ -1807,7 +1824,7 @@ private void AddFinalPropertiesAndImports(XmlElementWithLocation languageElement /// RGoel private void ProcessBuildElement ( - XmlElementWithLocation buildElement + XmlElementWithLocation buildElement ) { // Make sure this is the element. @@ -1824,7 +1841,7 @@ XmlElementWithLocation buildElement "NoAttributesExpected", VSProjectElements.build); // Loop through all the direct child elements of the element. - foreach(XmlNode buildChildNode in buildElement) + foreach (XmlNode buildChildNode in buildElement) { // Handle XML comments under the the node (just ignore them). if ((buildChildNode.NodeType == XmlNodeType.Comment) || @@ -1874,7 +1891,7 @@ XmlElementWithLocation buildElement /// RGoel private void ProcessSettingsElement ( - XmlElementWithLocation settingsElement + XmlElementWithLocation settingsElement ) { // Make sure this is the element. @@ -1953,7 +1970,7 @@ XmlElementWithLocation settingsElement this.AddXMakePropertiesFromXMLAttributes(this.globalPropertyGroup, settingsElement); // Loop through all the direct child elements of the element. - foreach(XmlNode settingsChildNode in settingsElement) + foreach (XmlNode settingsChildNode in settingsElement) { // Handle XML comments under the the node (just ignore them). if ((settingsChildNode.NodeType == XmlNodeType.Comment) || @@ -1999,7 +2016,7 @@ XmlElementWithLocation settingsElement /// RGoel private void ProcessConfigElement ( - XmlElementWithLocation configElement + XmlElementWithLocation configElement ) { // Make sure this is the element. @@ -2066,14 +2083,14 @@ XmlElementWithLocation configElement // In the case of VSD projects, the "Name" attribute will have a pipe in it, // followed by the device platform. This last part needs to be removed, // leaving just the config name. - if ( ( this.language == VSProjectElements.ECSharp ) || - ( this.language == VSProjectElements.EVisualBasic ) ) + if ((this.language == VSProjectElements.ECSharp) || + (this.language == VSProjectElements.EVisualBasic)) { - int pipeLocation = configName.IndexOf ( '|' ); - if ( pipeLocation != -1 ) + int pipeLocation = configName.IndexOf('|'); + if (pipeLocation != -1) { - configName = configName.Remove ( pipeLocation, - configName.Length - pipeLocation ); + configName = configName.Remove(pipeLocation, + configName.Length - pipeLocation); } } @@ -2100,8 +2117,10 @@ XmlElementWithLocation configElement string outputPath = configElement.GetAttribute(VSProjectAttributes.outputPath); if (!string.IsNullOrEmpty(outputPath)) { - if (outputPath[outputPath.Length-1] != Path.DirectorySeparatorChar) + if (outputPath[outputPath.Length - 1] != Path.DirectorySeparatorChar) + { outputPath += Path.DirectorySeparatorChar; + } configElement.RemoveAttribute(VSProjectAttributes.outputPath); configPropertyGroup.AddProperty(VSProjectAttributes.outputPath, ProjectCollection.Escape(outputPath)); @@ -2109,23 +2128,23 @@ XmlElementWithLocation configElement // If the "SelectedDevice" or "DeploymentPlatform" attributes exist in the per-user // project file, we should get rid of them. - string selectedDevice = configElement.GetAttribute ( VSProjectAttributes.selectedDevice ); + string selectedDevice = configElement.GetAttribute(VSProjectAttributes.selectedDevice); if (isUserFile && (selectedDevice?.Length > 0)) { - configElement.RemoveAttribute ( VSProjectAttributes.selectedDevice ); + configElement.RemoveAttribute(VSProjectAttributes.selectedDevice); } - string deploymentPlatform = configElement.GetAttribute ( VSProjectAttributes.deploymentPlatform ); + string deploymentPlatform = configElement.GetAttribute(VSProjectAttributes.deploymentPlatform); if (isUserFile && (deploymentPlatform?.Length > 0)) { - configElement.RemoveAttribute ( VSProjectAttributes.deploymentPlatform ); + configElement.RemoveAttribute(VSProjectAttributes.deploymentPlatform); } // Get rid of the "IncrementalBuild" attribute - string incrementalBuild = configElement.GetAttribute ( VSProjectAttributes.incrementalBuild ); + string incrementalBuild = configElement.GetAttribute(VSProjectAttributes.incrementalBuild); if (!string.IsNullOrEmpty(incrementalBuild)) { - configElement.RemoveAttribute ( VSProjectAttributes.incrementalBuild ); + configElement.RemoveAttribute(VSProjectAttributes.incrementalBuild); } // VSWhidbey bug 261464. For VB projects migrated from VS7/Everett, the VB team would @@ -2168,11 +2187,11 @@ XmlElementWithLocation configElement if (String.IsNullOrEmpty(debugType)) { string debugSymbols = configElement.GetAttribute(XMakeProjectStrings.debugSymbols); - if ( String.Equals ( debugSymbols, "true", StringComparison.OrdinalIgnoreCase ) ) + if (String.Equals(debugSymbols, "true", StringComparison.OrdinalIgnoreCase)) { configPropertyGroup.AddProperty(VSProjectAttributes.debugType, VSProjectAttributes.debugTypeFull); } - else if ( String.Equals(debugSymbols, "false", StringComparison.OrdinalIgnoreCase) ) + else if (String.Equals(debugSymbols, "false", StringComparison.OrdinalIgnoreCase)) { configPropertyGroup.AddProperty(VSProjectAttributes.debugType, VSProjectAttributes.debugTypeNone); } @@ -2181,7 +2200,7 @@ XmlElementWithLocation configElement // VSWhidbey bug 472064. For all VC# projects that are converted, we add an ErrorReport // property, always set to "prompt" - if ( !this.isUserFile && this.language == VSProjectElements.cSharp ) + if (!this.isUserFile && this.language == VSProjectElements.cSharp) { configPropertyGroup.AddProperty(VSProjectAttributes.errorReport, VSProjectAttributes.errorReportPrompt); } @@ -2197,7 +2216,7 @@ XmlElementWithLocation configElement ProjectCollection.Escape(platform) + XMakeProjectStrings.configplatformSuffix; // Loop through all the direct child elements of the element. - foreach(XmlNode configChildNode in configElement) + foreach (XmlNode configChildNode in configElement) { // Handle XML comments under the the node (just ignore them). if ((configChildNode.NodeType == XmlNodeType.Comment) || @@ -2238,10 +2257,10 @@ XmlElementWithLocation configElement /// BCham private void ProcessPlatformElement ( - XmlElementWithLocation platformElement + XmlElementWithLocation platformElement ) { - if ( !IsUserFile ) + if (!IsUserFile) { // Make sure this is the element. error.VerifyThrow((platformElement?.Name == VSProjectElements.platform), @@ -2279,7 +2298,7 @@ XmlElementWithLocation platformElement frameworkVersionForVSD = XMakeProjectStrings.vOne; - switch ( platformForVSD ) + switch (platformForVSD) { case VSProjectElements.PocketPC: platformID = "3C41C503-53EF-4c2a-8DD4-A8217CAD115E"; @@ -2314,7 +2333,7 @@ XmlElementWithLocation platformElement // add a property for the deployment target path. Note, we only need a suffix. // The prefix will be defaulted to based on the selected device. - platformPropertyGroup.AddProperty(XMakeProjectStrings.deployTargetSuffix, "$(AssemblyName)" ); + platformPropertyGroup.AddProperty(XMakeProjectStrings.deployTargetSuffix, "$(AssemblyName)"); // And, we should also set the Target Framework version. For // VSD projects, we want to stay with v1.0 @@ -2331,7 +2350,7 @@ XmlElementWithLocation platformElement /// RGoel private void ProcessInteropRegistrationElement ( - XmlElementWithLocation interopRegistrationElement, + XmlElementWithLocation interopRegistrationElement, ProjectPropertyGroupElement configPropertyGroup ) { @@ -2388,7 +2407,7 @@ ProjectPropertyGroupElement configPropertyGroup /// RGoel private void ProcessReferencesElement ( - XmlElementWithLocation referencesElement + XmlElementWithLocation referencesElement ) { // Make sure this is the element. @@ -2426,7 +2445,7 @@ XmlElementWithLocation referencesElement ProjectItemGroupElement referencesItemGroup = null; // Loop through all the direct child elements of the element. - foreach(XmlNode referencesChildNode in referencesElement) + foreach (XmlNode referencesChildNode in referencesElement) { // Handle XML comments under the the node (just ignore them). if ((referencesChildNode.NodeType == XmlNodeType.Comment) || @@ -2471,7 +2490,7 @@ XmlElementWithLocation referencesElement /// RGoel private void ProcessReferenceElement ( - XmlElementWithLocation referenceElement, + XmlElementWithLocation referenceElement, ProjectItemGroupElement referencesItemGroup ) { @@ -2495,7 +2514,7 @@ ProjectItemGroupElement referencesItemGroup return; } - referenceElement.RemoveAttribute ( VSProjectAttributes.platform ); + referenceElement.RemoveAttribute(VSProjectAttributes.platform); } ProjectItemElement newReferenceItem; @@ -2511,23 +2530,23 @@ ProjectItemGroupElement referencesItemGroup if ((this.language == VSProjectElements.ECSharp) || (this.language == VSProjectElements.EVisualBasic)) { - if ( ( this.frameworkVersionForVSD == XMakeProjectStrings.vTwo ) && - ( String.Equals ( referenceName, VSProjectElements.SystemDataCommon, StringComparison.OrdinalIgnoreCase ) ) ) + if ((this.frameworkVersionForVSD == XMakeProjectStrings.vTwo) && + (String.Equals(referenceName, VSProjectElements.SystemDataCommon, StringComparison.OrdinalIgnoreCase))) { // We need to remove all references to "System.Data.Common" for VSD projects only. // Note : We only want to do this for projects that will be updated to v2.0 // System.Data.Common is still valid for v1.0 upgraded projects. return; } - else if ( String.Equals ( referenceName, VSProjectElements.SystemSR, StringComparison.OrdinalIgnoreCase ) ) + else if (String.Equals(referenceName, VSProjectElements.SystemSR, StringComparison.OrdinalIgnoreCase)) { // We always want to remove all references to "System.SR" return; } } - if ( ( this.language == VSProjectElements.EVisualBasic ) && - ( String.Equals ( referenceName, VSProjectElements.MSCorLib, StringComparison.OrdinalIgnoreCase ) ) ) + if ((this.language == VSProjectElements.EVisualBasic) && + (String.Equals(referenceName, VSProjectElements.MSCorLib, StringComparison.OrdinalIgnoreCase))) { // We also want to get rid of all 'mscorlib' references for VB projects only. return; @@ -2920,7 +2939,7 @@ string referencedProjectGuid /// RGoel private void ProcessImportsElement ( - XmlElementWithLocation importsElement + XmlElementWithLocation importsElement ) { // Make sure this is the element. @@ -2938,7 +2957,7 @@ XmlElementWithLocation importsElement ProjectItemGroupElement importsItemGroup = null; // Loop through all the direct child elements of the element. - foreach(XmlNode importsChildNode in importsElement) + foreach (XmlNode importsChildNode in importsElement) { // Handle XML comments under the the node (just ignore them). if ((importsChildNode.NodeType == XmlNodeType.Comment) || @@ -3036,7 +3055,7 @@ ProjectItemGroupElement importsItemGroup /// RGoel private void ProcessFilesElement ( - XmlElementWithLocation filesElement + XmlElementWithLocation filesElement ) { // Make sure this is the element. @@ -3052,7 +3071,7 @@ XmlElementWithLocation filesElement "NoAttributesExpected", VSProjectElements.files); // Loop through all the direct child elements of the element. - foreach(XmlNode filesChildNode in filesElement) + foreach (XmlNode filesChildNode in filesElement) { // Handle XML comments under the the node (just ignore them). if ((filesChildNode.NodeType == XmlNodeType.Comment) || @@ -3102,7 +3121,7 @@ XmlElementWithLocation filesElement /// RGoel private void ProcessIncludeElement ( - XmlElementWithLocation includeElement + XmlElementWithLocation includeElement ) { // Make sure this is the element. @@ -3120,7 +3139,7 @@ XmlElementWithLocation includeElement ProjectItemGroupElement filesItemGroup = null; // Loop through all the direct child elements of the element. - foreach(XmlNode includeChildNode in includeElement) + foreach (XmlNode includeChildNode in includeElement) { // Handle XML comments under the the node (just ignore them). if ((includeChildNode.NodeType == XmlNodeType.Comment) || @@ -3170,7 +3189,7 @@ XmlElementWithLocation includeElement /// RGoel private void ProcessFileElement ( - XmlElementWithLocation fileElement, + XmlElementWithLocation fileElement, ProjectItemGroupElement filesItemGroup ) { @@ -3279,12 +3298,12 @@ ProjectItemGroupElement filesItemGroup // If this is a VSD(devices) project and we're dealing with a content file, // mark it to copy if newer. - if ( ((this.language == VSProjectElements.ECSharp) || + if (((this.language == VSProjectElements.ECSharp) || (this.language == VSProjectElements.EVisualBasic)) && - ( String.Equals ( buildAction, XMakeProjectStrings.content, StringComparison.OrdinalIgnoreCase ) ) ) + (String.Equals(buildAction, XMakeProjectStrings.content, StringComparison.OrdinalIgnoreCase))) { - newFileItem.AddMetadata ( XMakeProjectStrings.copytooutput, - XMakeProjectStrings.preservenewest ); + newFileItem.AddMetadata(XMakeProjectStrings.copytooutput, + XMakeProjectStrings.preservenewest); } } else @@ -3342,7 +3361,9 @@ private bool IsFilePresentButEmpty(string relPath, string linkPath) catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } // if we can't say for sure it's empty, play safe and return false return false; } @@ -3357,7 +3378,7 @@ private bool IsFilePresentButEmpty(string relPath, string linkPath) /// RGoel private void ProcessFolderElement ( - XmlElementWithLocation folderElement, + XmlElementWithLocation folderElement, ProjectItemGroupElement filesItemGroup ) { @@ -3506,7 +3527,7 @@ ProjectItemGroupElement filesItemGroup /// RGoel private void ProcessStartupServicesElement ( - XmlElementWithLocation startupServicesElement + XmlElementWithLocation startupServicesElement ) { // Make sure this is the element. @@ -3524,7 +3545,7 @@ XmlElementWithLocation startupServicesElement ProjectItemGroupElement startupServicesItemGroup = null; // Loop through all the direct child elements of the element. - foreach(XmlNode startupServicesChildNode in startupServicesElement) + foreach (XmlNode startupServicesChildNode in startupServicesElement) { // Handle XML comments under the the node (just ignore them). if ((startupServicesChildNode.NodeType == XmlNodeType.Comment) || @@ -3569,7 +3590,7 @@ XmlElementWithLocation startupServicesElement /// RGoel private void ProcessServiceElement ( - XmlElementWithLocation serviceElement, + XmlElementWithLocation serviceElement, ProjectItemGroupElement startupServicesItemGroup ) { @@ -3622,7 +3643,7 @@ ProjectItemGroupElement startupServicesItemGroup /// RGoel private void ProcessOtherProjectSettingsElement ( - XmlElementWithLocation otherProjectSettingsElement + XmlElementWithLocation otherProjectSettingsElement ) { // Make sure this is the element. @@ -3677,8 +3698,8 @@ XmlElementWithLocation otherProjectSettingsElement /// rgoel private void ProcessUserPropertiesElement ( - XmlElementWithLocation userPropertiesElement, - out bool isTriumphProject + XmlElementWithLocation userPropertiesElement, + out bool isTriumphProject ) { // Make sure this is the element. diff --git a/src/Deprecated/Engine/AssemblyInfo.cs b/src/Deprecated/Engine/AssemblyInfo.cs index bf94342c24e..1fdb6408e1e 100644 --- a/src/Deprecated/Engine/AssemblyInfo.cs +++ b/src/Deprecated/Engine/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Resources; diff --git a/src/Deprecated/Engine/Caching/BuildItemCacheEntry.cs b/src/Deprecated/Engine/Caching/BuildItemCacheEntry.cs index 63edec11783..c2822f4fc16 100644 --- a/src/Deprecated/Engine/Caching/BuildItemCacheEntry.cs +++ b/src/Deprecated/Engine/Caching/BuildItemCacheEntry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Deprecated/Engine/Caching/BuildResultCacheEntry.cs b/src/Deprecated/Engine/Caching/BuildResultCacheEntry.cs index 268d491019f..3cf94253502 100644 --- a/src/Deprecated/Engine/Caching/BuildResultCacheEntry.cs +++ b/src/Deprecated/Engine/Caching/BuildResultCacheEntry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; diff --git a/src/Deprecated/Engine/Caching/CacheEntry.cs b/src/Deprecated/Engine/Caching/CacheEntry.cs index 42300b27188..69c10aaccb2 100644 --- a/src/Deprecated/Engine/Caching/CacheEntry.cs +++ b/src/Deprecated/Engine/Caching/CacheEntry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; diff --git a/src/Deprecated/Engine/Caching/CacheEntryCustomSerializer.cs b/src/Deprecated/Engine/Caching/CacheEntryCustomSerializer.cs index 2538722be84..c77668154c6 100644 --- a/src/Deprecated/Engine/Caching/CacheEntryCustomSerializer.cs +++ b/src/Deprecated/Engine/Caching/CacheEntryCustomSerializer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -38,7 +38,7 @@ internal static void WriteToStream(CacheEntry entry, BinaryWriter writer) internal static CacheEntry CreateFromStream(BinaryReader reader) { - CacheEntryTypes entryType = (CacheEntryTypes) reader.ReadByte(); + CacheEntryTypes entryType = (CacheEntryTypes)reader.ReadByte(); CacheEntry entry = null; switch (entryType) diff --git a/src/Deprecated/Engine/Caching/PropertyCacheEntry.cs b/src/Deprecated/Engine/Caching/PropertyCacheEntry.cs index 319ecfb9bb5..2ee0f811477 100644 --- a/src/Deprecated/Engine/Caching/PropertyCacheEntry.cs +++ b/src/Deprecated/Engine/Caching/PropertyCacheEntry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; diff --git a/src/Deprecated/Engine/Choose/Choose.cs b/src/Deprecated/Engine/Choose/Choose.cs index ae079cf01bf..b3fb2c7c79f 100644 --- a/src/Deprecated/Engine/Choose/Choose.cs +++ b/src/Deprecated/Engine/Choose/Choose.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Collections; diff --git a/src/Deprecated/Engine/Choose/GroupEnumeratorHelper.cs b/src/Deprecated/Engine/Choose/GroupEnumeratorHelper.cs index 70360f67a3d..6ca1f091fb0 100644 --- a/src/Deprecated/Engine/Choose/GroupEnumeratorHelper.cs +++ b/src/Deprecated/Engine/Choose/GroupEnumeratorHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -74,11 +74,11 @@ ListType type /// /// DavidLe /// IEnumerator - public IEnumerator GetEnumerator( ) + public IEnumerator GetEnumerator() { foreach (IItemPropertyGrouping group in this.groupingCollection) { - if ((group is BuildItemGroup) && + if ((group is BuildItemGroup) && ((this.type == ListType.ItemGroupsTopLevel) || (this.type == ListType.ItemGroupsTopLevelAndChoose) || (this.type == ListType.ItemGroupsAll))) { yield return group; diff --git a/src/Deprecated/Engine/Choose/GroupingCollection.cs b/src/Deprecated/Engine/Choose/GroupingCollection.cs index 89ebe3363b9..6751aec4eea 100644 --- a/src/Deprecated/Engine/Choose/GroupingCollection.cs +++ b/src/Deprecated/Engine/Choose/GroupingCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -77,7 +77,7 @@ internal int PropertyGroupCount return this.propertyGroupCount; } } - + /// /// internal object SyncRoot @@ -448,7 +448,9 @@ IItemPropertyGrouping insertionPoint ChangePropertyGroupCount(1); } else if (newGroup is Choose) + { this.chooseCount++; + } } /// @@ -478,7 +480,9 @@ IItemPropertyGrouping newGroup ChangePropertyGroupCount(1); } else if (newGroup is Choose) + { this.chooseCount++; + } } /// @@ -559,7 +563,7 @@ internal void RemoveAllPropertyGroupsByCondition(string condition, bool includeI ArrayList propertiesToRemove = new ArrayList(); foreach (BuildPropertyGroup propertyGroup in this.PropertyGroupsAll) { - if (String.Equals(condition.Trim(), propertyGroup.Condition.Trim(), StringComparison.OrdinalIgnoreCase) + if (String.Equals(condition.Trim(), propertyGroup.Condition.Trim(), StringComparison.OrdinalIgnoreCase) && (!propertyGroup.IsImported || includeImportedPropertyGroups)) { propertiesToRemove.Add(propertyGroup); @@ -619,7 +623,7 @@ internal void RemoveAllItemGroupsByCondition(string condition) foreach (BuildItemGroup itemGroup in this.ItemGroupsAll) { - if (String.Equals(condition.Trim(), itemGroup.Condition.Trim(), StringComparison.OrdinalIgnoreCase) + if (String.Equals(condition.Trim(), itemGroup.Condition.Trim(), StringComparison.OrdinalIgnoreCase) && !itemGroup.IsImported) { itemsToRemove.Add(itemGroup); diff --git a/src/Deprecated/Engine/Choose/When.cs b/src/Deprecated/Engine/Choose/When.cs index 83f85fc5505..00ede41125f 100644 --- a/src/Deprecated/Engine/Choose/When.cs +++ b/src/Deprecated/Engine/Choose/When.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -73,7 +73,7 @@ int nestingDepth if (options == Options.ProcessWhen) { conditionAttribute = ProjectXmlUtilities.GetConditionAttribute(whenElement, /*verify sole attribute*/ true); - ProjectErrorUtilities.VerifyThrowInvalidProject(conditionAttribute != null, whenElement, "MissingCondition", XMakeElements.when); + ProjectErrorUtilities.VerifyThrowInvalidProject(conditionAttribute != null, whenElement, "MissingCondition", XMakeElements.when); } else { @@ -207,7 +207,7 @@ int nestingDepth } } - /// + /// /// Evaluates a When clause. Checks if the condition is true, and if it is, /// applies all of the contained property group, item lists, and import statements. /// Returns true if the When clause is process (because the condition is true), false @@ -225,9 +225,9 @@ internal bool EvaluateCondition Hashtable conditionedPropertiesTable ) { - if ( - (this.Condition != null) - && + if ( + (this.Condition != null) + && !Utilities.EvaluateCondition(this.Condition, this.ConditionAttribute, new Expander(parentPropertyBag, parentProject.EvaluatedItemsByName), conditionedPropertiesTable, ParserOptions.AllowProperties, this.parentProject.ParentEngine.LoggingServices, this.parentProject.ProjectBuildEventContext) @@ -269,16 +269,16 @@ ProcessingPass pass if (propOrItem is BuildPropertyGroup && pass == ProcessingPass.Pass1) { - ((BuildPropertyGroup) propOrItem).Evaluate(parentPropertyBag, conditionedPropertiesTable, pass); + ((BuildPropertyGroup)propOrItem).Evaluate(parentPropertyBag, conditionedPropertiesTable, pass); } else if (propOrItem is BuildItemGroup && pass == ProcessingPass.Pass2) { - ((BuildItemGroup) propOrItem).Evaluate(parentPropertyBag, parentProject.EvaluatedItemsByName, ignoreCondition, honorCondition, pass); + ((BuildItemGroup)propOrItem).Evaluate(parentPropertyBag, parentProject.EvaluatedItemsByName, ignoreCondition, honorCondition, pass); } else if (propOrItem is Choose) { - ((Choose) propOrItem).Evaluate(parentPropertyBag, ignoreCondition, honorCondition, conditionedPropertiesTable, pass); + ((Choose)propOrItem).Evaluate(parentPropertyBag, ignoreCondition, honorCondition, conditionedPropertiesTable, pass); } } } diff --git a/src/Deprecated/Engine/Collections/CopyOnWriteHashtable.cs b/src/Deprecated/Engine/Collections/CopyOnWriteHashtable.cs index 57fc959a2fc..4fcde96fdfe 100644 --- a/src/Deprecated/Engine/Collections/CopyOnWriteHashtable.cs +++ b/src/Deprecated/Engine/Collections/CopyOnWriteHashtable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -22,9 +22,9 @@ internal sealed class CopyOnWriteHashtable : IDictionary, ICloneable private object sharedLock; // Carry around the StringComparer when possible to make Clear less expensive. - StringComparer stringComparer = null; + private StringComparer stringComparer = null; -#region Construct + #region Construct /// /// Construct as a traditional data-backed hashtable. /// @@ -101,7 +101,7 @@ private CopyOnWriteHashtable(CopyOnWriteHashtable that) this.sharedLock = new object(); ConstructFrom(that); } - + /// /// Implementation of construction logic. /// @@ -136,11 +136,11 @@ internal bool IsShallowCopy return this.readonlyData != null; } } -#endregion -#region Pass-through Hashtable methods. - public bool Contains(Object key) {return ReadOperation.Contains(key);} - public void Add(Object key, Object value) {WriteOperation.Add(key, value);} - public void Clear() + #endregion + #region Pass-through Hashtable methods. + public bool Contains(Object key) { return ReadOperation.Contains(key); } + public void Add(Object key, Object value) { WriteOperation.Add(key, value); } + public void Clear() { lock (sharedLock) { @@ -152,25 +152,25 @@ public void Clear() } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)ReadOperation).GetEnumerator(); } - public IDictionaryEnumerator GetEnumerator() {return ReadOperation.GetEnumerator();} - public void Remove(Object key) {WriteOperation.Remove(key);} - public bool IsFixedSize { get { return ReadOperation.IsFixedSize; }} - public bool IsReadOnly {get {return ReadOperation.IsFixedSize;}} - public ICollection Keys {get {return ReadOperation.Keys;}} - public ICollection Values {get {return ReadOperation.Values;}} + public IDictionaryEnumerator GetEnumerator() { return ReadOperation.GetEnumerator(); } + public void Remove(Object key) { WriteOperation.Remove(key); } + public bool IsFixedSize { get { return ReadOperation.IsFixedSize; } } + public bool IsReadOnly { get { return ReadOperation.IsFixedSize; } } + public ICollection Keys { get { return ReadOperation.Keys; } } + public ICollection Values { get { return ReadOperation.Values; } } public void CopyTo(Array array, int arrayIndex) { ReadOperation.CopyTo(array, arrayIndex); } - public int Count{get { return ReadOperation.Count; }} - public bool IsSynchronized {get { return ReadOperation.IsSynchronized; }} - public Object SyncRoot {get { return ReadOperation.SyncRoot; }} - public bool ContainsKey(Object key) {return ReadOperation.Contains(key);} - - public Object this[Object key] + public int Count { get { return ReadOperation.Count; } } + public bool IsSynchronized { get { return ReadOperation.IsSynchronized; } } + public Object SyncRoot { get { return ReadOperation.SyncRoot; } } + public bool ContainsKey(Object key) { return ReadOperation.Contains(key); } + + public Object this[Object key] { - get + get { return ReadOperation[key]; } - set + set { lock (sharedLock) { @@ -189,7 +189,7 @@ public Object this[Object key] } } } -#endregion + #endregion /// /// Clone this. diff --git a/src/Deprecated/Engine/Collections/DualQueue.cs b/src/Deprecated/Engine/Collections/DualQueue.cs index 37448774e8f..fff75c0a193 100644 --- a/src/Deprecated/Engine/Collections/DualQueue.cs +++ b/src/Deprecated/Engine/Collections/DualQueue.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Threading; using System.Collections.Generic; @@ -119,7 +119,7 @@ internal void Enqueue(T item) writingQueueCount++; // if the queue transitions from empty to non-empty reset the queue empty event and raise queue ready event - if ( writingQueueCount == 1) + if (writingQueueCount == 1) { // raise the event saying queue contains data queueReadyEvent.Set(); @@ -256,7 +256,7 @@ private Queue GetReadingQueue() Queue postingQueue = queue; queue = readingQueue; readingQueue = postingQueue; - + writingQueueCount = 0; } } diff --git a/src/Deprecated/Engine/Collections/HashTableUtility.cs b/src/Deprecated/Engine/Collections/HashTableUtility.cs index a7783f95ab3..e15c91b7865 100644 --- a/src/Deprecated/Engine/Collections/HashTableUtility.cs +++ b/src/Deprecated/Engine/Collections/HashTableUtility.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Deprecated/Engine/Conditionals/AndExpressionNode.cs b/src/Deprecated/Engine/Conditionals/AndExpressionNode.cs index c9b35383e35..b05b1785725 100644 --- a/src/Deprecated/Engine/Conditionals/AndExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/AndExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; @@ -21,7 +21,7 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) state.conditionAttribute, "ExpressionDoesNotEvaluateToBoolean", LeftChild.GetUnexpandedValue(state), - LeftChild.GetExpandedValue(state), + LeftChild.GetExpandedValue(state), state.parsedCondition); if (!LeftChild.BoolEvaluate(state)) diff --git a/src/Deprecated/Engine/Conditionals/CharacterUtilities.cs b/src/Deprecated/Engine/Conditionals/CharacterUtilities.cs index 6689ce4f3c3..ff1462d1eb0 100644 --- a/src/Deprecated/Engine/Conditionals/CharacterUtilities.cs +++ b/src/Deprecated/Engine/Conditionals/CharacterUtilities.cs @@ -1,32 +1,32 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { internal static class CharacterUtilities { - static internal bool IsNumberStart(char candidate) + internal static bool IsNumberStart(char candidate) { return candidate == '+' || candidate == '-' || candidate == '.' || char.IsDigit(candidate); } - static internal bool IsSimpleStringStart(char candidate) + internal static bool IsSimpleStringStart(char candidate) { return candidate == '_' || char.IsLetter(candidate); } - static internal bool IsSimpleStringChar(char candidate) + internal static bool IsSimpleStringChar(char candidate) { return IsSimpleStringStart(candidate) || char.IsDigit(candidate); } - static internal bool IsHexAlphabetic(char candidate) + internal static bool IsHexAlphabetic(char candidate) { return candidate == 'a' || candidate == 'b' || candidate == 'c' || candidate == 'd' || candidate == 'e' || candidate == 'f' || candidate == 'A' || candidate == 'B' || candidate == 'C' || candidate == 'D' || candidate == 'E' || candidate == 'F'; } - static internal bool IsHexDigit(char candidate) + internal static bool IsHexDigit(char candidate) { return char.IsDigit(candidate) || IsHexAlphabetic(candidate); } diff --git a/src/Deprecated/Engine/Conditionals/ConditionEvaluationState.cs b/src/Deprecated/Engine/Conditionals/ConditionEvaluationState.cs index 2f646f295ef..a0207d81cf4 100644 --- a/src/Deprecated/Engine/Conditionals/ConditionEvaluationState.cs +++ b/src/Deprecated/Engine/Conditionals/ConditionEvaluationState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Xml; diff --git a/src/Deprecated/Engine/Conditionals/EqualExpressionNode.cs b/src/Deprecated/Engine/Conditionals/EqualExpressionNode.cs index d30805cb481..87a73307e07 100644 --- a/src/Deprecated/Engine/Conditionals/EqualExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/EqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Deprecated/Engine/Conditionals/FunctionCallExpressionNode.cs b/src/Deprecated/Engine/Conditionals/FunctionCallExpressionNode.cs index d8fb84eae17..896c5979373 100644 --- a/src/Deprecated/Engine/Conditionals/FunctionCallExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/FunctionCallExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; @@ -40,14 +40,16 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) if (Project.PerThreadProjectDirectory != null && !String.IsNullOrEmpty(expandedValue)) { - try + try { expandedValue = Path.GetFullPath(Path.Combine(Project.PerThreadProjectDirectory, expandedValue)); } catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } // Ignore invalid characters or path related exceptions @@ -88,9 +90,9 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) { ProjectErrorUtilities.VerifyThrowInvalidProject( false, - state.conditionAttribute, + state.conditionAttribute, "UndefinedFunctionCall", - state.parsedCondition, + state.parsedCondition, this.functionName); return false; @@ -109,7 +111,7 @@ private string ExpandArgumentForScalarParameter(string function, GenericExpressi { string argument = argumentNode.GetUnexpandedValue(state); - List items = state.expanderToUse.ExpandAllIntoTaskItems(argument, state.conditionAttribute); + List items = state.expanderToUse.ExpandAllIntoTaskItems(argument, state.conditionAttribute); string expandedValue = String.Empty; diff --git a/src/Deprecated/Engine/Conditionals/GenericExpressionNode.cs b/src/Deprecated/Engine/Conditionals/GenericExpressionNode.cs index a62a6101d19..cd4f8d25fac 100644 --- a/src/Deprecated/Engine/Conditionals/GenericExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/GenericExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Conditionals/GreaterThanExpressionNode.cs b/src/Deprecated/Engine/Conditionals/GreaterThanExpressionNode.cs index 28f132bf6c5..db1f39db41c 100644 --- a/src/Deprecated/Engine/Conditionals/GreaterThanExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/GreaterThanExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Conditionals/GreaterThanOrEqualExpressionNode.cs b/src/Deprecated/Engine/Conditionals/GreaterThanOrEqualExpressionNode.cs index bb4590e74ed..ff8fc4f6cfc 100644 --- a/src/Deprecated/Engine/Conditionals/GreaterThanOrEqualExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/GreaterThanOrEqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Conditionals/LessThanExpressionNode.cs b/src/Deprecated/Engine/Conditionals/LessThanExpressionNode.cs index 9b54d6840f5..de9a73dfc53 100644 --- a/src/Deprecated/Engine/Conditionals/LessThanExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/LessThanExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Conditionals/LessThanOrEqualExpressionNode.cs b/src/Deprecated/Engine/Conditionals/LessThanOrEqualExpressionNode.cs index 90133e282c7..3e60b10c7c1 100644 --- a/src/Deprecated/Engine/Conditionals/LessThanOrEqualExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/LessThanOrEqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Conditionals/MultipleComparisonExpressionNode.cs b/src/Deprecated/Engine/Conditionals/MultipleComparisonExpressionNode.cs index 3f5ee4dbc44..aeb581435b4 100644 --- a/src/Deprecated/Engine/Conditionals/MultipleComparisonExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/MultipleComparisonExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; @@ -56,9 +56,9 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) string rightExpandedValue = RightChild.GetExpandedValue(state); ProjectErrorUtilities.VerifyThrowInvalidProject - (leftExpandedValue != null && rightExpandedValue != null, - state.conditionAttribute, - "IllFormedCondition", + (leftExpandedValue != null && rightExpandedValue != null, + state.conditionAttribute, + "IllFormedCondition", state.parsedCondition); if (!conditionedPropertiesUpdated) @@ -69,16 +69,16 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) if (leftUnexpandedValue != null) { Utilities.UpdateConditionedPropertiesTable - (state.conditionedPropertiesInProject, - leftUnexpandedValue, + (state.conditionedPropertiesInProject, + leftUnexpandedValue, rightExpandedValue); } if (rightUnexpandedValue != null) { Utilities.UpdateConditionedPropertiesTable - (state.conditionedPropertiesInProject, - rightUnexpandedValue, + (state.conditionedPropertiesInProject, + rightUnexpandedValue, leftExpandedValue); } diff --git a/src/Deprecated/Engine/Conditionals/NotEqualExpressionNode.cs b/src/Deprecated/Engine/Conditionals/NotEqualExpressionNode.cs index 9204d9932c9..8c3a6221de0 100644 --- a/src/Deprecated/Engine/Conditionals/NotEqualExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/NotEqualExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Deprecated/Engine/Conditionals/NotExpressionNode.cs b/src/Deprecated/Engine/Conditionals/NotExpressionNode.cs index 8086c4ad34b..5167530f58c 100644 --- a/src/Deprecated/Engine/Conditionals/NotExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/NotExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Conditionals/NumericComparisonExpressionNode.cs b/src/Deprecated/Engine/Conditionals/NumericComparisonExpressionNode.cs index 6333997c111..feffc85f7d7 100644 --- a/src/Deprecated/Engine/Conditionals/NumericComparisonExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/NumericComparisonExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; @@ -23,7 +23,7 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) { ProjectErrorUtilities.VerifyThrowInvalidProject (LeftChild.CanNumericEvaluate(state) && RightChild.CanNumericEvaluate(state), - state.conditionAttribute, + state.conditionAttribute, "ComparisonOnNonNumericExpression", state.parsedCondition, /* helpfully display unexpanded token and expanded result in error message */ diff --git a/src/Deprecated/Engine/Conditionals/NumericExpressionNode.cs b/src/Deprecated/Engine/Conditionals/NumericExpressionNode.cs index 4bde8c03e91..c556fc25b49 100644 --- a/src/Deprecated/Engine/Conditionals/NumericExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/NumericExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Conditionals/OperandExpressionNode.cs b/src/Deprecated/Engine/Conditionals/OperandExpressionNode.cs index 452223044c8..8773ccddd51 100644 --- a/src/Deprecated/Engine/Conditionals/OperandExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/OperandExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Conditionals/OperatorExpressionNode.cs b/src/Deprecated/Engine/Conditionals/OperatorExpressionNode.cs index 0fa3f8ca0c2..932b9c3c8dd 100644 --- a/src/Deprecated/Engine/Conditionals/OperatorExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/OperatorExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Conditionals/OrExpressionNode.cs b/src/Deprecated/Engine/Conditionals/OrExpressionNode.cs index 5d564a32faa..2dd6791916b 100644 --- a/src/Deprecated/Engine/Conditionals/OrExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/OrExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Conditionals/Parser.cs b/src/Deprecated/Engine/Conditionals/Parser.cs index e428728b559..8871466f464 100644 --- a/src/Deprecated/Engine/Conditionals/Parser.cs +++ b/src/Deprecated/Engine/Conditionals/Parser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Xml; @@ -13,13 +13,13 @@ namespace Microsoft.Build.BuildEngine [Flags] internal enum ParserOptions { - None = 0x0, - AllowProperties = 0x1, - AllowItemLists = 0x2, + None = 0x0, + AllowProperties = 0x1, + AllowItemLists = 0x2, AllowPropertiesAndItemLists = AllowProperties | AllowItemLists, - AllowItemMetadata = 0x4, + AllowItemMetadata = 0x4, AllowPropertiesAndItemMetadata = AllowProperties | AllowItemMetadata, - AllowAll = AllowProperties | AllowItemLists | AllowItemMetadata + AllowAll = AllowProperties | AllowItemLists | AllowItemMetadata }; /// @@ -38,10 +38,10 @@ internal sealed class Parser private ParserOptions options; internal int errorPosition = 0; // useful for unit tests -#region REMOVE_COMPAT_WARNING + #region REMOVE_COMPAT_WARNING private bool warnedForExpression = false; - + private BuildEventContext logBuildEventContext; /// /// Location contextual information which are attached to logging events to @@ -68,13 +68,13 @@ internal EngineLoggingServices LoggingServices { this.loggingServices = value; } - + get { return this.loggingServices; } } -#endregion + #endregion internal Parser() { @@ -133,7 +133,7 @@ private GenericExpressionNode Expr(string expression) warnedForExpression = true; // Try to figure out where this expression was located string projectFile = String.Empty; - int lineNumber = 0; + int lineNumber = 0; int columnNumber = 0; if (this.conditionAttribute != null) { @@ -142,7 +142,7 @@ private GenericExpressionNode Expr(string expression) } // Log a warning regarding the fact the expression may have been evaluated // incorrectly in earlier version of MSBuild - LoggingServices.LogWarning(logBuildEventContext,new BuildEventFileInfo(projectFile, lineNumber, columnNumber), "ConditionMaybeEvaluatedIncorrectly", expression); + LoggingServices.LogWarning(logBuildEventContext, new BuildEventFileInfo(projectFile, lineNumber, columnNumber), "ConditionMaybeEvaluatedIncorrectly", expression); } #endregion @@ -161,7 +161,7 @@ private GenericExpressionNode ExprPrime(string expression, GenericExpressionNode GenericExpressionNode rhs = BooleanTerm(expression); orNode.LeftChild = lhs; orNode.RightChild = rhs; - return ExprPrime( expression, orNode ); + return ExprPrime(expression, orNode); } else { @@ -217,7 +217,7 @@ private GenericExpressionNode BooleanTermPrime(string expression, GenericExpress private GenericExpressionNode RelationalExpr(string expression) { - { + { GenericExpressionNode lhs = Factor(expression); if (lhs == null) { @@ -296,13 +296,15 @@ private GenericExpressionNode Factor(string expression) ProjectErrorUtilities.VerifyThrowInvalidProject(false, this.conditionAttribute, "UnexpectedTokenInCondition", expression, lexer.IsNextString(), errorPosition); return null; } - return new FunctionCallExpressionNode( current.String, arglist); + return new FunctionCallExpressionNode(current.String, arglist); } else if (Same(expression, Token.TokenType.LeftParenthesis)) { GenericExpressionNode child = Expr(expression); if (Same(expression, Token.TokenType.RightParenthesis)) + { return child; + } else { errorPosition = lexer.GetErrorPosition(); @@ -332,7 +334,9 @@ private GenericExpressionNode Factor(string expression) private void Arglist(string expression, ArrayList arglist) { if (!lexer.IsNext(Token.TokenType.RightParenthesis)) + { Args(expression, arglist); + } } private void Args(string expression, ArrayList arglist) @@ -393,7 +397,9 @@ private bool Same(string expression, Token.TokenType token) return true; } else + { return false; + } } } } diff --git a/src/Deprecated/Engine/Conditionals/Scanner.cs b/src/Deprecated/Engine/Conditionals/Scanner.cs index 83ae741d5ac..23c0a26e1a9 100644 --- a/src/Deprecated/Engine/Conditionals/Scanner.cs +++ b/src/Deprecated/Engine/Conditionals/Scanner.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; using System; @@ -29,10 +29,10 @@ internal sealed class Scanner private bool errorState; private int errorPosition; // What we found instead of what we were looking for - private string unexpectedlyFound = null; + private string unexpectedlyFound = null; private ParserOptions options; private string errorResource = null; - + // Shared instances of "hardcoded" token strings. These are only used // in error messages. private const string comma = ","; @@ -104,7 +104,7 @@ internal string GetErrorResource() } } - internal bool IsNext( Token.TokenType type ) + internal bool IsNext(Token.TokenType type) { return lookahead.IsToken(type); } @@ -146,10 +146,14 @@ internal string UnexpectedlyFound internal bool Advance() { if (errorState) + { return false; + } if (lookahead?.IsToken(Token.TokenType.EndOfInput) == true) - return true; + { + return true; + } SkipWhiteSpace(); @@ -178,7 +182,10 @@ internal bool Advance() break; case '$': if (!ParseProperty()) + { return false; + } + break; case '%': // If the caller specified that he DOESN'T want to allow item metadata ... @@ -191,7 +198,10 @@ internal bool Advance() return false; } if (!ParseItemMetadata()) + { return false; + } + break; case '@': int start = this.parsePoint; @@ -207,7 +217,10 @@ internal bool Advance() } } if (!ParseItemList()) + { return false; + } + break; case '!': // negation and not-equal @@ -274,12 +287,18 @@ internal bool Advance() break; case '\'': if (!ParseQuotedString()) + { return false; + } + break; default: // Simple strings, function calls, decimal numbers, hex numbers if (!ParseRemaining()) + { return false; + } + break; } } @@ -532,12 +551,16 @@ private bool ParseRemaining() if (CharacterUtilities.IsNumberStart(expression[parsePoint])) // numeric { if (!ParseNumeric(start)) + { return false; + } } else if (CharacterUtilities.IsSimpleStringStart(expression[parsePoint])) // simple string (handle 'and' and 'or') { if (!ParseSimpleStringOrFunction(start)) + { return false; + } } else { @@ -550,7 +573,7 @@ private bool ParseRemaining() } return true; } - private bool ParseSimpleStringOrFunction( int start ) + private bool ParseSimpleStringOrFunction(int start) { SkipSimpleStringChars(); if (string.Equals(expression.Substring(start, parsePoint - start), "and", StringComparison.OrdinalIgnoreCase)) @@ -577,16 +600,16 @@ private bool ParseSimpleStringOrFunction( int start ) } return true; } - private bool ParseNumeric( int start ) + private bool ParseNumeric(int start) { - if ((expression.Length-parsePoint) > 2 && expression[parsePoint] == '0' && (expression[parsePoint + 1] == 'x' || expression[parsePoint + 1] == 'X')) + if ((expression.Length - parsePoint) > 2 && expression[parsePoint] == '0' && (expression[parsePoint + 1] == 'x' || expression[parsePoint + 1] == 'X')) { // Hex number parsePoint += 2; SkipHexDigits(); lookahead = new Token(Token.TokenType.Numeric, expression.Substring(start, parsePoint - start)); } - else if ( CharacterUtilities.IsNumberStart(expression[parsePoint])) + else if (CharacterUtilities.IsNumberStart(expression[parsePoint])) { // Decimal number if (expression[parsePoint] == '+') @@ -622,25 +645,37 @@ private bool ParseNumeric( int start ) private void SkipWhiteSpace() { while (parsePoint < expression.Length && char.IsWhiteSpace(expression[parsePoint])) + { parsePoint++; + } + return; } private void SkipDigits() { while (parsePoint < expression.Length && char.IsDigit(expression[parsePoint])) + { parsePoint++; + } + return; } private void SkipHexDigits() { while (parsePoint < expression.Length && CharacterUtilities.IsHexDigit(expression[parsePoint])) + { parsePoint++; + } + return; } private void SkipSimpleStringChars() { while (parsePoint < expression.Length && CharacterUtilities.IsSimpleStringChar(expression[parsePoint])) + { parsePoint++; + } + return; } } diff --git a/src/Deprecated/Engine/Conditionals/StringExpressionNode.cs b/src/Deprecated/Engine/Conditionals/StringExpressionNode.cs index b5493eae3b2..1c28c1a2f38 100644 --- a/src/Deprecated/Engine/Conditionals/StringExpressionNode.cs +++ b/src/Deprecated/Engine/Conditionals/StringExpressionNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; @@ -26,7 +26,7 @@ internal override bool BoolEvaluate(ConditionEvaluationState state) { return ConversionUtilities.ConvertStringToBool(GetExpandedValue(state)); } - + /// /// Evaluate as numeric /// diff --git a/src/Deprecated/Engine/Conditionals/Token.cs b/src/Deprecated/Engine/Conditionals/Token.cs index 60d93cfaeee..58ebbf97903 100644 --- a/src/Deprecated/Engine/Conditionals/Token.cs +++ b/src/Deprecated/Engine/Conditionals/Token.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { @@ -14,7 +14,7 @@ internal sealed class Token /// /// Valid tokens /// - internal enum TokenType + internal enum TokenType { Comma, LeftParenthesis, RightParenthesis, LessThan, GreaterThan, LessThanOrEqualTo, GreaterThanOrEqualTo, @@ -33,7 +33,7 @@ internal enum TokenType /// /// /// - internal Token( TokenType type, string tokenString ) + internal Token(TokenType type, string tokenString) { this.tokenType = type; this.tokenString = tokenString; @@ -44,7 +44,7 @@ internal Token( TokenType type, string tokenString ) /// /// /// - internal bool IsToken( TokenType type ) + internal bool IsToken(TokenType type) { return tokenType == type; } diff --git a/src/Deprecated/Engine/Engine/BatchingEngine.cs b/src/Deprecated/Engine/Engine/BatchingEngine.cs index f4cb0ac6e47..e8e30c39522 100644 --- a/src/Deprecated/Engine/Engine/BatchingEngine.cs +++ b/src/Deprecated/Engine/Engine/BatchingEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -192,9 +192,9 @@ private static Hashtable GetItemListsToBeBatched ( XmlNode parentNode, Dictionary consumedMetadataReferences, // Key is [string] potentially qualified metadata name - // Value is [struct MetadataReference] + // Value is [struct MetadataReference] Hashtable consumedItemReferenceNames, // Key is [string] item name. - // Value is always String.Empty (unused). + // Value is always String.Empty (unused). Lookup lookup ) { @@ -267,7 +267,7 @@ Lookup lookup return itemListsToBeBatched; } - + /// /// Partitions the items consumed by the batchable object into buckets, where each bucket contains a set of items that /// have the same value set on all item metadata consumed by the object. @@ -387,7 +387,7 @@ Dictionary consumedMetadataReferences string metadataItemName = consumedMetadataReference.Value.itemName; string metadataName = consumedMetadataReference.Value.metadataName; - if ( + if ( (metadataItemName != null) && (!String.Equals(item.Name, metadataItemName, StringComparison.OrdinalIgnoreCase)) ) diff --git a/src/Deprecated/Engine/Engine/BuildRequest.cs b/src/Deprecated/Engine/Engine/BuildRequest.cs index de90df06466..89419a6fe2b 100644 --- a/src/Deprecated/Engine/Engine/BuildRequest.cs +++ b/src/Deprecated/Engine/Engine/BuildRequest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -494,13 +494,13 @@ internal long StartTime get { return startTime; } set { startTime = value; } } - + internal long ProcessingStartTime { get { return processingStartTime; } set { processingStartTime = value; } } - + internal long ProcessingTotalTime { get { return processingTotalTime; } @@ -553,13 +553,13 @@ internal void InitializeFromCachedResult(BuildResult cachedResult) internal BuildResult GetBuildResult() { // Calculate the time spent on this build request - int totalTime = 0; + int totalTime = 0; int engineTime = 0; int taskTimeMs = 0; - if ( startTime != 0 ) + if (startTime != 0) { - TimeSpan totalTimeSpan = new TimeSpan(DateTime.Now.Ticks - startTime ); - totalTime = (int)totalTimeSpan.TotalMilliseconds; + TimeSpan totalTimeSpan = new TimeSpan(DateTime.Now.Ticks - startTime); + totalTime = (int)totalTimeSpan.TotalMilliseconds; } if (processingTotalTime != 0) { diff --git a/src/Deprecated/Engine/Engine/BuildResult.cs b/src/Deprecated/Engine/Engine/BuildResult.cs index 05a39f10452..3a4518a4211 100644 --- a/src/Deprecated/Engine/Engine/BuildResult.cs +++ b/src/Deprecated/Engine/Engine/BuildResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -25,8 +25,8 @@ internal BuildResult() /// internal BuildResult ( - IDictionary outputsByTarget, Hashtable resultByTarget, bool evaluationResult, - int handleId, int requestId, int projectId, bool useResultCache, + IDictionary outputsByTarget, Hashtable resultByTarget, bool evaluationResult, + int handleId, int requestId, int projectId, bool useResultCache, string defaultTargets, string initialTargets, int totalTime, int engineTime, int taskTime ) @@ -36,7 +36,7 @@ internal BuildResult this.handleId = handleId; this.requestId = requestId; this.projectId = projectId; - this.flags = (byte)((evaluationResult ? 1 : 0 ) | (useResultCache ? 2 : 0)); + this.flags = (byte)((evaluationResult ? 1 : 0) | (useResultCache ? 2 : 0)); this.defaultTargets = defaultTargets; this.initialTargets = initialTargets; this.totalTime = totalTime; @@ -86,7 +86,7 @@ internal BuildResult itemArray[i] = new BuildItem(null, originalArray[i].FinalItemSpecEscaped); } } - + this.outputsByTarget.Add(entry.Key, itemArray); } } diff --git a/src/Deprecated/Engine/Engine/BuildTask.cs b/src/Deprecated/Engine/Engine/BuildTask.cs index 4d7552ed0fa..2bf5ea34e01 100644 --- a/src/Deprecated/Engine/Engine/BuildTask.cs +++ b/src/Deprecated/Engine/Engine/BuildTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -30,7 +30,7 @@ public class BuildTask private XmlAttribute continueOnErrorAttribute = null; // The target to which this task belongs. - private Target parentTarget= null; + private Target parentTarget = null; // The name of the task. private string taskName = String.Empty; @@ -59,9 +59,9 @@ public class BuildTask /// rgoel internal BuildTask ( - XmlElement taskElement, - Target parentTarget, - bool importedFromAnotherProject + XmlElement taskElement, + Target parentTarget, + bool importedFromAnotherProject ) { // Make sure a valid node has been given to us. @@ -495,11 +495,11 @@ private void MarkTaskAsDirty ( ) { - - - // This is a change to the contents of the target. - this.ParentTarget?.MarkTargetAsDirty(); - + + + // This is a change to the contents of the target. + this.ParentTarget?.MarkTargetAsDirty(); + } #endregion diff --git a/src/Deprecated/Engine/Engine/CacheManager.cs b/src/Deprecated/Engine/Engine/CacheManager.cs index 472b3125dbb..0ed428b9dd2 100644 --- a/src/Deprecated/Engine/Engine/CacheManager.cs +++ b/src/Deprecated/Engine/Engine/CacheManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -104,7 +104,7 @@ internal CacheScope GetCacheScope(string scopeName, BuildPropertyGroup scopeProp lock (cacheManagerLock) { cacheScope = GetCacheScopeIfExists(scopeName, scopeProperties, scopeToolsVersion, cacheContentType); - + if (cacheScope == null) { // If the list of scopes doesn't exist create it diff --git a/src/Deprecated/Engine/Engine/CacheScope.cs b/src/Deprecated/Engine/Engine/CacheScope.cs index ffec30b70b4..4e87cab7e09 100644 --- a/src/Deprecated/Engine/Engine/CacheScope.cs +++ b/src/Deprecated/Engine/Engine/CacheScope.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -34,8 +34,8 @@ internal CacheScope(string scopeName, BuildPropertyGroup scopeProperties, string { // Make certain we don't cache a reference to a Project object, which would defeat // the purpose of this cache - scopeProperties.ClearParentProject(); - + scopeProperties.ClearParentProject(); + this.scopeName = scopeName; this.scopeToolsVersion = scopeToolsVersion; this.scopeProperties = scopeProperties; @@ -54,7 +54,7 @@ internal BuildPropertyGroup ScopeProperties return this.scopeProperties; } } - + /// /// Usually the project file name /// @@ -157,7 +157,7 @@ internal CacheEntry GetCacheEntry(string name) { return (CacheEntry)cacheContents[name]; } - + return null; } @@ -242,15 +242,15 @@ internal void AddCacheEntryForBuildResults(BuildResult buildResult) // If the project file is malformed the build may fail without initializing the initialtargets or // the default targests fields. The retrieval code expects non-null values // so it is necessary to replace null with empty string - ErrorUtilities.VerifyThrow(!buildResult.EvaluationResult || (buildResult.InitialTargets != null - && buildResult.DefaultTargets != null), + ErrorUtilities.VerifyThrow(!buildResult.EvaluationResult || (buildResult.InitialTargets != null + && buildResult.DefaultTargets != null), "Expect initial targets to be non-null for successful builds"); string defaultTargets = buildResult.DefaultTargets ?? String.Empty; PropertyCacheEntry defaultTargetsCacheEntry = new PropertyCacheEntry(Constants.defaultTargetCacheName, defaultTargets); AddCacheEntryInternal(defaultTargetsCacheEntry); string initialTargets = buildResult.InitialTargets ?? String.Empty; - PropertyCacheEntry initialTargetsCacheEntry = new PropertyCacheEntry(Constants.initialTargetCacheName, initialTargets ); + PropertyCacheEntry initialTargetsCacheEntry = new PropertyCacheEntry(Constants.initialTargetCacheName, initialTargets); AddCacheEntryInternal(initialTargetsCacheEntry); } @@ -350,7 +350,7 @@ internal BuildResult GetCachedBuildResult(BuildRequest buildRequest, out ArrayLi ErrorUtilities.VerifyThrow(defaultTargetsCacheEntry != null && initialTargetsCacheEntry != null, "We should have both the initial and default targets in the cache"); - ArrayList targetsToBuild = new ArrayList(initialTargetsCacheEntry.Value.Split(new char[] {';'}, StringSplitOptions.RemoveEmptyEntries)); + ArrayList targetsToBuild = new ArrayList(initialTargetsCacheEntry.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); if (buildRequest.TargetNames == null || buildRequest.TargetNames.Length == 0) { @@ -413,8 +413,8 @@ internal BuildResult GetCachedBuildResult(BuildRequest buildRequest, out ArrayLi actuallyBuiltTargets = targetsToBuild; - return new BuildResult(outputsByTargetName, resultByTarget, overallSuccess, buildRequest.HandleId, buildRequest.RequestId, - int.Parse(projectIdCacheEntry.Value, CultureInfo.InvariantCulture), false /* use results cache */, + return new BuildResult(outputsByTargetName, resultByTarget, overallSuccess, buildRequest.HandleId, buildRequest.RequestId, + int.Parse(projectIdCacheEntry.Value, CultureInfo.InvariantCulture), false /* use results cache */, defaultTargetsCacheEntry.Value, initialTargetsCacheEntry.Value, 0, 0, 0); } diff --git a/src/Deprecated/Engine/Engine/Engine.cs b/src/Deprecated/Engine/Engine/Engine.cs index e0bd956d1c4..aa2d5670394 100644 --- a/src/Deprecated/Engine/Engine/Engine.cs +++ b/src/Deprecated/Engine/Engine/Engine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -325,7 +325,7 @@ internal Engine(BuildPropertyGroup globalProperties, ToolsetDefinitionLocations // Get a list of properties which should be serialized if (!String.IsNullOrEmpty(forwardPropertiesFromChild)) { - propertyListToSerialize = forwardPropertiesFromChild.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries); + propertyListToSerialize = forwardPropertiesFromChild.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); } } @@ -1134,7 +1134,7 @@ public void RegisterDistributedLogger(ILogger centralLogger, LoggerDescription f localForwardingLogger.BuildEventRedirector = newRedirector; localForwardingLogger.Parameters = forwardingLogger.LoggerSwitchParameters; localForwardingLogger.Verbosity = forwardingLogger.Verbosity; - localForwardingLogger.NodeId= nodeId; + localForwardingLogger.NodeId = nodeId; // Convert the path to the logger DLL to full path before passing it to the node provider forwardingLogger.ConvertPathsToFullPaths(); } @@ -1374,7 +1374,7 @@ Project project UnloadProject(project, true /* Unload all versions */); } - internal void UnloadProject(Project project, bool unloadAllVersions ) + internal void UnloadProject(Project project, bool unloadAllVersions) { if (project.FullFileName.Length > 0) { @@ -1570,7 +1570,7 @@ public bool BuildProject IDictionary targetOutputs // can be null if outputs are not needed ) { - return BuildProject(project, targetNames, targetOutputs, BuildSettings.None); + return BuildProject(project, targetNames, targetOutputs, BuildSettings.None); } /// @@ -1614,7 +1614,7 @@ internal BuildResult EngineBuildLoop(BuildRequest terminatingBuildRequest) BuildResult buildResult = null; bool continueExecution = true; lastLoopActivity = DateTime.Now.Ticks; - int loopTimeout= Introspector.initialLoopTimeout; // Inactivity timeout which triggers deadlock check + int loopTimeout = Introspector.initialLoopTimeout; // Inactivity timeout which triggers deadlock check int loopTimeoutRemaining = Introspector.initialLoopTimeout; int flushTimeout = EngineLoggingServices.flushTimeoutInMS; // Timeout with which the log is flushed bool forceFlush = false; @@ -1735,9 +1735,13 @@ internal BuildResult EngineBuildLoop(BuildRequest terminatingBuildRequest) if (Engine.debugMode) { if (taskExecutionContext.BuildContext.BuildRequest != null) + { Console.WriteLine("NodeId: " + NodeId + " Got output update " + taskExecutionContext.ParentProject.FullFileName + " HandleId: " + taskExecutionContext.BuildContext.BuildRequest.HandleId + " Time: " + DateTime.Now.ToLongTimeString() + ":" + DateTime.Now.Millisecond); + } else + { Console.WriteLine("NodeId: " + NodeId + " Got output update " + taskExecutionContext.ParentProject.FullFileName + " HandleId: None Time: " + DateTime.Now.ToLongTimeString() + ":" + DateTime.Now.Millisecond); + } } // In inproc scenario we may receive a task done notification for a build context @@ -1752,9 +1756,13 @@ internal BuildResult EngineBuildLoop(BuildRequest terminatingBuildRequest) if (Engine.debugMode) { if (taskExecutionContext.BuildContext.BuildRequest != null) + { Console.WriteLine("Ignoring task output notification. NodeId: " + NodeId + " Got output update " + taskExecutionContext.ParentProject.FullFileName + " HandleId: " + taskExecutionContext.BuildContext.BuildRequest.HandleId); + } else + { Console.WriteLine("Ignoring task output notification. NodeId: " + NodeId + " Got output update " + taskExecutionContext.ParentProject.FullFileName); + } } } @@ -1788,7 +1796,7 @@ internal BuildResult EngineBuildLoop(BuildRequest terminatingBuildRequest) } } - if (ExternalLoggingServices != null && ( ExternalLoggingServices.NeedsFlush(lastLoopActivity) || forceFlush )) + if (ExternalLoggingServices != null && (ExternalLoggingServices.NeedsFlush(lastLoopActivity) || forceFlush)) { if (ExternalLoggingServices.ProcessPostedLoggingEvents()) { @@ -1984,7 +1992,7 @@ private void SetBuildItemCurrentDirectory(Project project) /// private void BuildProjectInternalContinue(BuildRequest buildRequest, ProjectBuildState buildContext, TaskExecutionContext taskExecutionContext, Project project) { - if (buildRequest != null && ProfileBuild ) + if (buildRequest != null && ProfileBuild) { buildRequest.ProcessingStartTime = DateTime.Now.Ticks; } @@ -2107,7 +2115,7 @@ public bool BuildProjectFile string targetName ) { - return this.BuildProjectFile(projectFile, new string[] {targetName}, this.GlobalProperties, + return this.BuildProjectFile(projectFile, new string[] { targetName }, this.GlobalProperties, null, BuildSettings.None); } @@ -2231,7 +2239,7 @@ string toolsVersion return PostProjectEvaluationRequests (null, new string[] { projectFile }, new string[][] { targetNames }, new BuildPropertyGroup[] { globalProperties }, new IDictionary[] { targetOutputs }, buildFlags, - new string[] {toolsVersion}); + new string[] { toolsVersion }); } /// @@ -2253,7 +2261,7 @@ public bool BuildProjectFiles BuildPropertyGroup[] globalPropertiesPerProject, IDictionary[] targetOutputsPerProject, BuildSettings buildFlags, - string [] toolsVersions + string[] toolsVersions ) { // Verify the arguments to the API @@ -2266,7 +2274,7 @@ string [] toolsVersions // Verify the entries in the project file array for (int i = 0; i < projectFiles.Length; i++) { - error.VerifyThrowArgumentNull(projectFiles[i], "projectFiles[" + i +"]"); + error.VerifyThrowArgumentNull(projectFiles[i], "projectFiles[" + i + "]"); error.VerifyThrowArgument(projectFiles[i].Length > 0, "projectFilesEmptyElement", i); } @@ -2283,7 +2291,7 @@ internal bool PostProjectEvaluationRequests BuildPropertyGroup[] globalPropertiesPerProject, IDictionary[] targetOutputsPerProject, BuildSettings buildFlags, - string [] toolVersions + string[] toolVersions ) { string currentDirectory = Environment.CurrentDirectory; @@ -2424,7 +2432,7 @@ private BuildRequest CreateLocalBuildRequest(BuildEventContext buildEventContext globalProperties = new BuildPropertyGroup(); } - BuildRequest buildRequest = new BuildRequest(EngineCallback.invalidEngineHandle, projectFile, targetNames, globalProperties, toolsVersion, -1, true, false); + BuildRequest buildRequest = new BuildRequest(EngineCallback.invalidEngineHandle, projectFile, targetNames, globalProperties, toolsVersion, -1, true, false); buildRequest.ParentBuildEventContext = buildEventContext; // Set the project object to the passed in project buildRequest.ProjectToBuild = project; @@ -2600,7 +2608,7 @@ BuildRequest buildRequest { IncrementProjectsInProgress(); } - Router.PostBuildRequest(buildRequest, evaluationNode); + Router.PostBuildRequest(buildRequest, evaluationNode); } } } @@ -2704,7 +2712,7 @@ internal Project GetMatchingProject string projectFullPath, BuildPropertyGroup globalPropertiesToUse, string toolsVersion, - string [] targetNames, + string[] targetNames, BuildEventContext buildEventContext, bool toolsVersionPeekedFromProjectFile ) @@ -2717,7 +2725,7 @@ bool toolsVersionPeekedFromProjectFile // and load the contents from the project file. if (returnProject == null) { - #if DEBUG +#if DEBUG if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("MSBUILDASSERTONLOADMULTIPLECOPIESOFPROJECT"))) { if (this.projectsLoadedByHost.Contains(projectFullPath)) @@ -2758,7 +2766,7 @@ bool toolsVersionPeekedFromProjectFile } } } - #endif +#endif // Check if the project has been previously unloaded due to a user request during the current build // In this case reloaded a project is an error because we can't ensure a consistent state of the reloaded project @@ -2794,7 +2802,7 @@ bool toolsVersionPeekedFromProjectFile string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "UnrecognizedToolsVersion", toolsVersion); - throw new InvalidProjectFileException(projectFullPath,fileInfo.Line,fileInfo.Column,fileInfo.EndLine, fileInfo.EndColumn,message, null, errorCode,helpKeyword); + throw new InvalidProjectFileException(projectFullPath, fileInfo.Line, fileInfo.Column, fileInfo.EndLine, fileInfo.EndColumn, message, null, errorCode, helpKeyword); } // We're only building this project ... it is not loaded by a host, and we @@ -2891,7 +2899,7 @@ IDictionary globalPropertiesPassedIntoTask string childProjectFullPath = Path.GetFullPath(childProjectFile); // Find out if there's a project already loaded with the same full path. - Project loadedProjectWithSameFullPath = (Project) this.projectsLoadedByHost[childProjectFullPath]; + Project loadedProjectWithSameFullPath = (Project)this.projectsLoadedByHost[childProjectFullPath]; // Then ... if there is a loaded project with the same full path, merge in its global properties. // This way, we honor whatever settings the IDE has requested for this project (e.g. Configuration=Release, or whatever). @@ -2906,8 +2914,8 @@ IDictionary globalPropertiesPassedIntoTask { foreach (DictionaryEntry newGlobalProperty in globalPropertiesPassedIntoTask) { - finalGlobalProperties.SetProperty((string) newGlobalProperty.Key, - (string) newGlobalProperty.Value); + finalGlobalProperties.SetProperty((string)newGlobalProperty.Key, + (string)newGlobalProperty.Value); } } @@ -2955,9 +2963,9 @@ internal TaskExecutionContext GetTaskOutputUpdates() internal NodeStatus RequestStatus(int requestId) { // Find out the list of the inprogress waiting targets - List outstandingRequests = new List(); - int [] handleIds = NodeManager.TaskExecutionModule.GetWaitingTaskData(outstandingRequests); - Target [] waitingTargets = EngineCallback.GetListOfTargets(handleIds); + List outstandingRequests = new List(); + int[] handleIds = NodeManager.TaskExecutionModule.GetWaitingTaskData(outstandingRequests); + Target[] waitingTargets = EngineCallback.GetListOfTargets(handleIds); // Find out the list of targets waiting due to dependency or onerror call but not actively in progress List inProgressProject = cacheOfBuildingProjects.GetInProgressProjects(); diff --git a/src/Deprecated/Engine/Engine/EngineCallback.cs b/src/Deprecated/Engine/Engine/EngineCallback.cs index f63605391cc..cead0ac2c9e 100644 --- a/src/Deprecated/Engine/Engine/EngineCallback.cs +++ b/src/Deprecated/Engine/Engine/EngineCallback.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -42,7 +42,7 @@ public void PostBuildRequestsToHost(BuildRequest[] buildRequests) { // We can safely assume that all requests need to be routed to the same engine because // they originated from the same task - for(int i = 0; i < buildRequests.Length; i++) + for (int i = 0; i < buildRequests.Length; i++) { ProcessBuildRequest(buildRequests[i]); } @@ -491,7 +491,7 @@ internal RequestRoutingContext GetRoutingContextFromHandleId(int handleId) internal int CreateTaskContext ( Project parentProject, - Target parentTarget, + Target parentTarget, ProjectBuildState buildContext, XmlElement taskNode, int nodeIndex, @@ -594,7 +594,7 @@ internal void ClearContextState(int handleId) /// /// List of contexts that should be removed from the hashtable by the engine thread /// - private List freedContexts = new List(2*freeListThreshold); + private List freedContexts = new List(2 * freeListThreshold); /// /// The counter used to generate unique identifiers for each context /// diff --git a/src/Deprecated/Engine/Engine/EngineCommand.cs b/src/Deprecated/Engine/Engine/EngineCommand.cs index 64b56703376..48f1ea0b00e 100644 --- a/src/Deprecated/Engine/Engine/EngineCommand.cs +++ b/src/Deprecated/Engine/Engine/EngineCommand.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BuildEngine.Shared; @@ -91,7 +91,7 @@ internal override void Execute(Engine parentEngine) } #endregion - #region ChangeTraversalType + #region ChangeTraversalType /// /// Wrapper class for a changing the traversal approach used by the TEM /// diff --git a/src/Deprecated/Engine/Engine/EngineLoggingServices.cs b/src/Deprecated/Engine/Engine/EngineLoggingServices.cs index c7648ee9523..df792b5025b 100644 --- a/src/Deprecated/Engine/Engine/EngineLoggingServices.cs +++ b/src/Deprecated/Engine/Engine/EngineLoggingServices.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -33,7 +33,7 @@ internal abstract class EngineLoggingServices protected void Initialize(ManualResetEvent flushRequestEventIn) { this.loggingQueueOfBuildEvents = new DualQueue(); - this.loggingQueueOfNodeEvents = new DualQueue(); + this.loggingQueueOfNodeEvents = new DualQueue(); this.lastFlushTime = DateTime.Now.Ticks; this.flushRequestEvent = flushRequestEventIn; this.requestedQueueFlush = false; @@ -58,7 +58,7 @@ internal void EndEatingEvents() /// /// Shutdown the logging service as appropriate /// - virtual internal void Shutdown() + internal virtual void Shutdown() { ErrorUtilities.VerifyThrow(false, "This method should be defined in a subclass"); } @@ -184,23 +184,23 @@ internal void PostLoggingEvents(NodeLoggingEvent[] eventArray) /// in-proc implementation, this will actually raise the events. In the out-of-proc /// implementation, this will send the events from the node process to the engine. /// - abstract internal bool ProcessPostedLoggingEvents(); - + internal abstract bool ProcessPostedLoggingEvents(); + /// /// This method is to process a single build event, by default if this method is used /// the event should be posted and processed /// /// - virtual internal void ProcessBuildEvent(BuildEventArgs buildEventArgs) + internal virtual void ProcessBuildEvent(BuildEventArgs buildEventArgs) { PostLoggingEvent(buildEventArgs); ProcessPostedLoggingEvents(); } - + /// /// Return true if the queue needs to be flushed /// - virtual internal bool NeedsFlush(long currentTickCount) + internal virtual bool NeedsFlush(long currentTickCount) { if (this.flushBuildEventsImmediatly) { @@ -310,7 +310,7 @@ internal void LogCustomEvent(CustomBuildEventArgs e) /// /// Logs a low-priority comment with all registered loggers using the specified resource string. /// - virtual internal void LogComment(BuildEventContext buildEventContext, string messageResourceName, params object[] messageArgs) + internal virtual void LogComment(BuildEventContext buildEventContext, string messageResourceName, params object[] messageArgs) { if (!OnlyLogCriticalEvents) { @@ -325,7 +325,7 @@ virtual internal void LogComment(BuildEventContext buildEventContext, string mes /// /// /// - virtual internal void LogComment(BuildEventContext buildEventContext, MessageImportance importance, string messageResourceName, params object[] messageArgs) + internal virtual void LogComment(BuildEventContext buildEventContext, MessageImportance importance, string messageResourceName, params object[] messageArgs) { if (!OnlyLogCriticalEvents) { @@ -338,7 +338,7 @@ virtual internal void LogComment(BuildEventContext buildEventContext, MessageImp /// /// Logs a custom-priority comment with all registered loggers using the given text. /// - virtual internal void LogCommentFromText(BuildEventContext buildEventContext,MessageImportance importance, string message) + internal virtual void LogCommentFromText(BuildEventContext buildEventContext, MessageImportance importance, string message) { if (!OnlyLogCriticalEvents) { @@ -374,7 +374,7 @@ virtual internal void LogCommentFromText(BuildEventContext buildEventContext,Mes /// /// /// - virtual internal void LogError(BuildEventContext location, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) + internal virtual void LogError(BuildEventContext location, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) { LogError(location, null, file, messageResourceName, messageArgs); } @@ -387,7 +387,7 @@ virtual internal void LogError(BuildEventContext location, BuildEventFileInfo fi /// /// /// - virtual internal void LogError(BuildEventContext buildEventContext, string subcategoryResourceName, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) + internal virtual void LogError(BuildEventContext buildEventContext, string subcategoryResourceName, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need resource string for error message."); @@ -407,7 +407,7 @@ virtual internal void LogError(BuildEventContext buildEventContext, string subca /// Can be null. /// /// - virtual internal void LogErrorFromText(BuildEventContext buildEventContext, string subcategoryResourceName, string errorCode, string helpKeyword, BuildEventFileInfo file, string message) + internal virtual void LogErrorFromText(BuildEventContext buildEventContext, string subcategoryResourceName, string errorCode, string helpKeyword, BuildEventFileInfo file, string message) { ErrorUtilities.VerifyThrow(file != null, "Must specify the associated file."); ErrorUtilities.VerifyThrow(message != null, "Need error message."); @@ -442,7 +442,7 @@ virtual internal void LogErrorFromText(BuildEventContext buildEventContext, stri /// /// SumedhK /// - virtual internal void LogInvalidProjectFileError(BuildEventContext buildEventContext, InvalidProjectFileException invalidProjectFileException) + internal virtual void LogInvalidProjectFileError(BuildEventContext buildEventContext, InvalidProjectFileException invalidProjectFileException) { ErrorUtilities.VerifyThrow(invalidProjectFileException != null, "Need exception context."); @@ -477,7 +477,7 @@ virtual internal void LogInvalidProjectFileError(BuildEventContext buildEventCon /// SumedhK /// /// - virtual internal void LogFatalBuildError(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file) + internal virtual void LogFatalBuildError(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file) { LogFatalError(buildEventContext, exception, file, "FatalBuildError"); } @@ -490,7 +490,7 @@ virtual internal void LogFatalBuildError(BuildEventContext buildEventContext, Ex /// /// /// - virtual internal void LogFatalTaskError(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file, string taskName) + internal virtual void LogFatalTaskError(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file, string taskName) { ErrorUtilities.VerifyThrow(taskName != null, "Must specify the name of the task that failed."); @@ -506,16 +506,16 @@ virtual internal void LogFatalTaskError(BuildEventContext buildEventContext, Exc /// /// /// - virtual internal void LogFatalError(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) + internal virtual void LogFatalError(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need resource string for error message."); string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, messageResourceName, messageArgs); - #if DEBUG +#if DEBUG message += Environment.NewLine + "This is an unhandled exception -- PLEASE OPEN A BUG."; - #endif +#endif if (exception != null) { message += Environment.NewLine + exception.ToString(); @@ -542,7 +542,7 @@ virtual internal void LogFatalError(BuildEventContext buildEventContext, Excepti /// /// /// - virtual internal void LogTaskWarningFromException(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file, string taskName) + internal virtual void LogTaskWarningFromException(BuildEventContext buildEventContext, Exception exception, BuildEventFileInfo file, string taskName) { ErrorUtilities.VerifyThrow(taskName != null, "Must specify the name of the task that failed."); ErrorUtilities.VerifyThrow(file != null, "Must specify the associated file."); @@ -550,9 +550,9 @@ virtual internal void LogTaskWarningFromException(BuildEventContext buildEventCo string warningCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out warningCode, out helpKeyword, "FatalTaskError", taskName); - #if DEBUG +#if DEBUG message += Environment.NewLine + "This is an unhandled exception -- PLEASE OPEN A BUG."; - #endif +#endif if (exception != null) { @@ -569,9 +569,9 @@ virtual internal void LogTaskWarningFromException(BuildEventContext buildEventCo /// /// /// - virtual internal void LogWarning(BuildEventContext buildEventContext, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) + internal virtual void LogWarning(BuildEventContext buildEventContext, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) { - LogWarning(buildEventContext,null, file, messageResourceName, messageArgs); + LogWarning(buildEventContext, null, file, messageResourceName, messageArgs); } /// @@ -582,7 +582,7 @@ virtual internal void LogWarning(BuildEventContext buildEventContext, BuildEvent /// /// /// - virtual internal void LogWarning(BuildEventContext buildEventContext, string subcategoryResourceName, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) + internal virtual void LogWarning(BuildEventContext buildEventContext, string subcategoryResourceName, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need resource string for warning message."); @@ -602,7 +602,7 @@ virtual internal void LogWarning(BuildEventContext buildEventContext, string sub /// Can be null. /// /// - virtual internal void LogWarningFromText(BuildEventContext buildEventContext, string subcategoryResourceName, string warningCode, string helpKeyword, BuildEventFileInfo file, string message) + internal virtual void LogWarningFromText(BuildEventContext buildEventContext, string subcategoryResourceName, string warningCode, string helpKeyword, BuildEventFileInfo file, string message) { ErrorUtilities.VerifyThrow(file != null, "Must specify the associated file."); ErrorUtilities.VerifyThrow(message != null, "Need warning message."); @@ -644,7 +644,7 @@ virtual internal void LogWarningFromText(BuildEventContext buildEventContext, st /// /// Logs that the build has started with all loggers (only called on the main node) /// - virtual internal void LogBuildStarted() + internal virtual void LogBuildStarted() { // If we're only logging critical events, don't risk causing all the resources to load by formatting // a string that won't get emitted anyway. @@ -666,7 +666,7 @@ virtual internal void LogBuildStarted() /// /// Logs that the build has finished with all loggers, except for forwarding loggers. /// - virtual internal void LogBuildStarted(int loggerId) + internal virtual void LogBuildStarted(int loggerId) { // If we're only logging critical events, don't risk causing all the resources to load by formatting // a string that won't get emitted anyway. @@ -689,7 +689,7 @@ virtual internal void LogBuildStarted(int loggerId) /// Logs that the build has finished with all registered loggers. /// /// - virtual internal void LogBuildFinished(bool success) + internal virtual void LogBuildFinished(bool success) { // If we're only logging critical events, don't risk causing all the resources to load by formatting // a string that won't get emitted anyway. @@ -707,7 +707,7 @@ virtual internal void LogBuildFinished(bool success) /// /// Logs that the build has finished to a particular logger Id /// - virtual internal void LogBuildFinished(bool success, int loggerId) + internal virtual void LogBuildFinished(bool success, int loggerId) { // If we're only logging critical events, don't risk causing all the resources to load by formatting // a string that won't get emitted anyway. @@ -734,12 +734,12 @@ virtual internal void LogBuildFinished(bool success, int loggerId) /// target names /// properties list /// items list - virtual internal void LogProjectStarted(int projectId, BuildEventContext parentBuildEventContext, BuildEventContext projectBuildEventContext, string projectFile, string targetNames, IEnumerable properties, IEnumerable items) + internal virtual void LogProjectStarted(int projectId, BuildEventContext parentBuildEventContext, BuildEventContext projectBuildEventContext, string projectFile, string targetNames, IEnumerable properties, IEnumerable items) { if (!OnlyLogCriticalEvents) { ProjectStartedEventArgs e; - + if (!string.IsNullOrEmpty(targetNames)) { e = new ProjectStartedEventArgs @@ -768,7 +768,7 @@ virtual internal void LogProjectStarted(int projectId, BuildEventContext parentB parentBuildEventContext ); } - + e.BuildEventContext = projectBuildEventContext; PostLoggingEvent(e); @@ -781,7 +781,7 @@ virtual internal void LogProjectStarted(int projectId, BuildEventContext parentB /// SumedhK /// /// - virtual internal void LogProjectFinished(BuildEventContext buildEventContext, string projectFile, bool success) + internal virtual void LogProjectFinished(BuildEventContext buildEventContext, string projectFile, bool success) { if (!OnlyLogCriticalEvents) { @@ -806,7 +806,7 @@ virtual internal void LogProjectFinished(BuildEventContext buildEventContext, st /// Name of target /// Main project file /// Project file actually containing the target - virtual internal void LogTargetStarted(BuildEventContext buildEventContext, string targetName, string projectFile, string projectFileOfTargetElement) + internal virtual void LogTargetStarted(BuildEventContext buildEventContext, string targetName, string projectFile, string projectFileOfTargetElement) { if (!OnlyLogCriticalEvents) { @@ -831,7 +831,7 @@ virtual internal void LogTargetStarted(BuildEventContext buildEventContext, stri /// main project file /// /// project file actually containing the target - virtual internal void LogTargetFinished(BuildEventContext buildEventContext, string targetName, string projectFile, string projectFileOfTargetElement, bool success) + internal virtual void LogTargetFinished(BuildEventContext buildEventContext, string targetName, string projectFile, string projectFileOfTargetElement, bool success) { if (!OnlyLogCriticalEvents) { @@ -859,7 +859,7 @@ virtual internal void LogTargetFinished(BuildEventContext buildEventContext, str /// /// /// project file actually containing the task - virtual internal void LogTaskStarted(BuildEventContext buildEventContext, string taskName, string projectFile, string projectFileOfTaskNode) + internal virtual void LogTaskStarted(BuildEventContext buildEventContext, string taskName, string projectFile, string projectFileOfTaskNode) { if (!OnlyLogCriticalEvents) { @@ -884,7 +884,7 @@ virtual internal void LogTaskStarted(BuildEventContext buildEventContext, string /// /// /// project file actually containing the task - virtual internal void LogTaskFinished(BuildEventContext buildEventContext, string taskName, string projectFile, string projectFileOfTaskNode, bool success) + internal virtual void LogTaskFinished(BuildEventContext buildEventContext, string taskName, string projectFile, string projectFileOfTaskNode, bool success) { if (!OnlyLogCriticalEvents) { @@ -1010,7 +1010,7 @@ internal bool FlushBuildEventsImmediatly protected ManualResetEvent flushRequestEvent; internal const int flushTimeoutInMS = 500; // flush the queue at least every 1/2 second - internal const int flushTimeoutInTicks = 500*10000; // flush the queue at least every 1/2 second + internal const int flushTimeoutInTicks = 500 * 10000; // flush the queue at least every 1/2 second internal const int flushQueueSize = 1000; // flush the queue every time 1000 events accumulate #endregion diff --git a/src/Deprecated/Engine/Engine/EngineLoggingServicesInProc.cs b/src/Deprecated/Engine/Engine/EngineLoggingServicesInProc.cs index 75bf624038a..de2abc127a3 100644 --- a/src/Deprecated/Engine/Engine/EngineLoggingServicesInProc.cs +++ b/src/Deprecated/Engine/Engine/EngineLoggingServicesInProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -51,7 +51,7 @@ internal EngineLoggingServicesInProc(EventSource eventSource, bool onlyLogCritic /// This function logs out all the messages currently posted to the queue. The active queue is swapped /// with the secondary queue to enable posting of messages while this function is running /// - override internal bool ProcessPostedLoggingEvents() + internal override bool ProcessPostedLoggingEvents() { bool processedEvents = false; lastFlushTime = DateTime.Now.Ticks; @@ -103,7 +103,7 @@ override internal bool ProcessPostedLoggingEvents() /// be posted to another logger /// /// - override internal void ProcessBuildEvent(BuildEventArgs buildEventArgs) + internal override void ProcessBuildEvent(BuildEventArgs buildEventArgs) { engineEventSource.RaiseStronglyTypedEvent(buildEventArgs); @@ -135,7 +135,7 @@ internal void UnregisterEventSource(int loggerId) /// /// Shutdown the logging service as appropriate /// - override internal void Shutdown() + internal override void Shutdown() { foreach (EventSource eventSource in eventSources.Values) { diff --git a/src/Deprecated/Engine/Engine/EngineLoggingServicesOutProc.cs b/src/Deprecated/Engine/Engine/EngineLoggingServicesOutProc.cs index da04f14f2d0..649526dc0ab 100644 --- a/src/Deprecated/Engine/Engine/EngineLoggingServicesOutProc.cs +++ b/src/Deprecated/Engine/Engine/EngineLoggingServicesOutProc.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Threading; @@ -49,7 +49,7 @@ internal EngineLoggingServicesOutProc(Node parentNode, ManualResetEvent flushReq /// This function is thread safe and is called both from the engine thread and communication threads to /// ensure that the events are delivered in coherent order. /// - override internal bool ProcessPostedLoggingEvents() + internal override bool ProcessPostedLoggingEvents() { lock (loggingQueueReadLock) { @@ -83,7 +83,7 @@ override internal bool ProcessPostedLoggingEvents() // If there are event - post them to the parent if (current != 0) { - NodeLoggingEvent [] trimmedEventArray = new NodeLoggingEvent[current]; + NodeLoggingEvent[] trimmedEventArray = new NodeLoggingEvent[current]; Array.Copy(eventArray, trimmedEventArray, current); parentNode.PostLoggingMessagesToHost(trimmedEventArray); current = 0; @@ -114,7 +114,7 @@ private void AddToCurrentArray(NodeLoggingEvent e) /// /// Shutdown the logging service as appropriate /// - override internal void Shutdown() + internal override void Shutdown() { // Do nothing } @@ -154,7 +154,7 @@ internal void ReportLoggingFailure(Exception e) /// /// The number of events in one array posted to the parent. /// - const int eventArrayChunkSize = 100; + private const int eventArrayChunkSize = 100; #endregion } } diff --git a/src/Deprecated/Engine/Engine/EngineProxy.cs b/src/Deprecated/Engine/Engine/EngineProxy.cs index afc4259b5be..ee84357a8b2 100644 --- a/src/Deprecated/Engine/Engine/EngineProxy.cs +++ b/src/Deprecated/Engine/Engine/EngineProxy.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -157,7 +157,7 @@ public void LogErrorEvent(BuildErrorEventArgs e) // but wants to ignore the failures. This implies that we shouldn't be logging // errors either, because you should never have a successful build with errors. BuildWarningEventArgs warningEvent = new BuildWarningEventArgs - ( e.Subcategory, + (e.Subcategory, e.Code, e.File, e.LineNumber, @@ -172,7 +172,7 @@ public void LogErrorEvent(BuildErrorEventArgs e) loggingServices.LogWarningEvent(warningEvent); // Log a message explaining why we converted the previous error into a warning. - loggingServices.LogComment(buildEventContext,MessageImportance.Normal, "ErrorConvertedIntoWarning"); + loggingServices.LogComment(buildEventContext, MessageImportance.Normal, "ErrorConvertedIntoWarning"); } else { @@ -291,7 +291,7 @@ public void LogMessageEvent(BuildMessageEventArgs e) if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable) { loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); - return; + return; } e.BuildEventContext = buildEventContext; loggingServices.LogMessageEvent(e); @@ -308,7 +308,7 @@ public void LogCustomEvent(CustomBuildEventArgs e) if (parentModule.IsRunningMultipleNodes && !e.GetType().IsSerializable) { loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(string.Empty), "ExpectedEventToBeSerializable", e.GetType().Name); - return; + return; } e.BuildEventContext = buildEventContext; @@ -483,16 +483,16 @@ bool unloadProjectsOnCompletion /// /// Not implemented for the proxy /// - public void Yield() - { - } + public void Yield() + { + } /// /// Not implemented for the proxy /// - public void Reacquire() - { - } + public void Reacquire() + { + } /// /// Stub implementation -- forwards to engine being proxied. @@ -515,7 +515,7 @@ public BuildEngineResult BuildProjectFilesInParallel ( string[] projectFileNames, string[] targetNames, - IDictionary [] globalProperties, + IDictionary[] globalProperties, IList[] removeGlobalProperties, string[] toolsVersions, bool returnTargetOutputs @@ -567,9 +567,9 @@ public override object InitializeLifetimeService() if (!String.IsNullOrEmpty(initialLeaseTimeFromEnvironment)) { int leaseTimeFromEnvironment; - if (int.TryParse(initialLeaseTimeFromEnvironment , out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0) + if (int.TryParse(initialLeaseTimeFromEnvironment, out leaseTimeFromEnvironment) && leaseTimeFromEnvironment > 0) { - initialLeaseTime = leaseTimeFromEnvironment; + initialLeaseTime = leaseTimeFromEnvironment; } } @@ -587,9 +587,9 @@ public override object InitializeLifetimeService() if (!String.IsNullOrEmpty(leaseExtensionTimeFromEnvironment)) { int leaseExtensionFromEnvironment; - if (int.TryParse(leaseExtensionTimeFromEnvironment , out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0) + if (int.TryParse(leaseExtensionTimeFromEnvironment, out leaseExtensionFromEnvironment) && leaseExtensionFromEnvironment > 0) { - leaseExtensionTime = leaseExtensionFromEnvironment; + leaseExtensionTime = leaseExtensionFromEnvironment; } } diff --git a/src/Deprecated/Engine/Engine/EventRedirector.cs b/src/Deprecated/Engine/Engine/EventRedirector.cs index e54678cb3c2..3c83a4fab79 100644 --- a/src/Deprecated/Engine/Engine/EventRedirector.cs +++ b/src/Deprecated/Engine/Engine/EventRedirector.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Engine/EventSource.cs b/src/Deprecated/Engine/Engine/EventSource.cs index b44d10aa901..a7f60365d38 100644 --- a/src/Deprecated/Engine/Engine/EventSource.cs +++ b/src/Deprecated/Engine/Engine/EventSource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -584,7 +584,7 @@ internal void RaiseStronglyTypedEvent(BuildEventArgs e) /// /// t-jeffv, sumedhk public event BuildErrorEventHandler ErrorRaised; - + /// /// This event is raised to log a warning. /// @@ -602,43 +602,43 @@ internal void RaiseStronglyTypedEvent(BuildEventArgs e) /// /// t-jeffv, sumedhk public event BuildFinishedEventHandler BuildFinished; - + /// /// this event is raised to log the start of a project build /// /// t-jeffv, sumedhk public event ProjectStartedEventHandler ProjectStarted; - + /// /// this event is raised to log the end of a project build /// /// t-jeffv, sumedhk public event ProjectFinishedEventHandler ProjectFinished; - + /// /// this event is raised to log the start of a target build /// /// t-jeffv, sumedhk public event TargetStartedEventHandler TargetStarted; - + /// /// this event is raised to log the end of a target build /// /// t-jeffv, sumedhk public event TargetFinishedEventHandler TargetFinished; - + /// /// this event is raised to log the start of task execution /// /// t-jeffv, sumedhk public event TaskStartedEventHandler TaskStarted; - + /// /// this event is raised to log the end of task execution /// /// t-jeffv, sumedhk - public event TaskFinishedEventHandler TaskFinished; - + public event TaskFinishedEventHandler TaskFinished; + /// /// this event is raised to log a custom event /// diff --git a/src/Deprecated/Engine/Engine/ExecutionContext.cs b/src/Deprecated/Engine/Engine/ExecutionContext.cs index d6fbbbf9a4c..a67f46bac82 100644 --- a/src/Deprecated/Engine/Engine/ExecutionContext.cs +++ b/src/Deprecated/Engine/Engine/ExecutionContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; @@ -17,7 +17,7 @@ internal class ExecutionContext /// internal ExecutionContext(int handleId, int nodeIndex, BuildEventContext buildEventContext) { - this.handleId = handleId; + this.handleId = handleId; this.nodeIndex = nodeIndex; this.buildEventContext = buildEventContext; } diff --git a/src/Deprecated/Engine/Engine/Expander.cs b/src/Deprecated/Engine/Engine/Expander.cs index 2cd7ba7bcd4..8fa4792b16c 100644 --- a/src/Deprecated/Engine/Engine/Expander.cs +++ b/src/Deprecated/Engine/Engine/Expander.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -122,7 +122,7 @@ internal Expander(Expander expander, ExpanderOptions options) } internal Expander(Expander expander, SpecificItemDefinitionLibrary itemDefinitionLibrary) - : this(expander.lookup, null , expander.options) + : this(expander.lookup, null, expander.options) { if (implicitMetadataItemType == null) { @@ -131,7 +131,7 @@ internal Expander(Expander expander, SpecificItemDefinitionLibrary itemDefinitio this.specificItemDefinitionLibrary = itemDefinitionLibrary; } -#endregion + #endregion /// /// Adds metadata to the table being used by this expander. @@ -704,7 +704,7 @@ private static int ScanForClosingParenthesis(string expression, int index, out b return (nestLevel == 0) ? index : -1; } - + /// /// Expand the body of the property, including any functions that it may contain /// @@ -871,7 +871,7 @@ private static bool IsValidPropertyName(string propertyName) private string ExpandRegistryValue(string registryExpression, XmlNode node) { string registryLocation = registryExpression.Substring(9); - + // Split off the value name -- the part after the "@" sign. If there's no "@" sign, then it's the default value name // we want. int firstAtSignOffset = registryLocation.IndexOf('@'); @@ -879,9 +879,9 @@ private string ExpandRegistryValue(string registryExpression, XmlNode node) ProjectErrorUtilities.VerifyThrowInvalidProject(firstAtSignOffset == lastAtSignOffset, node, "InvalidRegistryPropertyExpression", "$(" + registryExpression + ")", String.Empty); - string valueName = lastAtSignOffset == -1 || lastAtSignOffset == registryLocation.Length - 1 + string valueName = lastAtSignOffset == -1 || lastAtSignOffset == registryLocation.Length - 1 ? null : registryLocation.Substring(lastAtSignOffset + 1); - + // If there's no '@', or '@' is first, then we'll use null or String.Empty for the location; otherwise // the location is the part before the '@' string registryKeyName = lastAtSignOffset != -1 ? registryLocation.Substring(0, lastAtSignOffset) : registryLocation; @@ -1231,7 +1231,7 @@ public object Execute(Expander expander, object objectInstance, BuildPropertyGro { functionResult = EscapingUtilities.Escape((string)functionResult); } - + // There's nothing left to deal within the function expression, return the result from the execution if (String.IsNullOrEmpty(remainder)) { @@ -1474,7 +1474,7 @@ private static Type GetTypeFromAssembly(string typeName, string candidateAssembl return objectType; } - + /// /// Factory method to construct a function for property evaluation /// @@ -1584,7 +1584,7 @@ private static Function ConstructFunction(string expressionFunction, string expr private static string[] ExtractFunctionArguments(string expressionFunction, string argumentsContent) { List arguments = new List(); - StringBuilder argumentBuilder = new StringBuilder(argumentsContent.Length); + StringBuilder argumentBuilder = new StringBuilder(argumentsContent.Length); // Iterate over the contents of the arguments extracting the // the individual arguments as we go @@ -1945,7 +1945,7 @@ private string ExpandSingleMetadata(Match itemMetadataMatch) { metadataValue = GetDefaultMetadataValue(itemType, metadataName, metadataValue); } - + return metadataValue ?? String.Empty; } @@ -1955,7 +1955,10 @@ private string ExpandSingleMetadata(Match itemMetadataMatch) /// private string GetValueFromMetadataTable(string itemType, string metadataName, string metadataValue) { - if (itemMetadata == null) return null; + if (itemMetadata == null) + { + return null; + } if (implicitMetadataItemType == null) { @@ -1993,7 +1996,10 @@ private string GetValueFromMetadataTable(string itemType, string metadataName, s /// private string GetDefaultMetadataValue(string itemType, string metadataName, string metadataValue) { - if (specificItemDefinitionLibrary == null) return null; + if (specificItemDefinitionLibrary == null) + { + return null; + } if (itemType == null || String.Equals(itemType, specificItemDefinitionLibrary.ItemType, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Deprecated/Engine/Engine/IEngineCallback.cs b/src/Deprecated/Engine/Engine/IEngineCallback.cs index 7b538f15464..ef0e68ec266 100644 --- a/src/Deprecated/Engine/Engine/IEngineCallback.cs +++ b/src/Deprecated/Engine/Engine/IEngineCallback.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Deprecated/Engine/Engine/IItemPropertyGrouping.cs b/src/Deprecated/Engine/Engine/IItemPropertyGrouping.cs index 27d940ac092..384c819a7a8 100644 --- a/src/Deprecated/Engine/Engine/IItemPropertyGrouping.cs +++ b/src/Deprecated/Engine/Engine/IItemPropertyGrouping.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Engine/INodeDescription.cs b/src/Deprecated/Engine/Engine/INodeDescription.cs index 24d190e456c..10260aaba32 100644 --- a/src/Deprecated/Engine/Engine/INodeDescription.cs +++ b/src/Deprecated/Engine/Engine/INodeDescription.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Engine/INodeProvider.cs b/src/Deprecated/Engine/Engine/INodeProvider.cs index ae288add6b7..5ac748c3d27 100644 --- a/src/Deprecated/Engine/Engine/INodeProvider.cs +++ b/src/Deprecated/Engine/Engine/INodeProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { diff --git a/src/Deprecated/Engine/Engine/ITaskRegistry.cs b/src/Deprecated/Engine/Engine/ITaskRegistry.cs index 0a7f26c1198..befb3870587 100644 --- a/src/Deprecated/Engine/Engine/ITaskRegistry.cs +++ b/src/Deprecated/Engine/Engine/ITaskRegistry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Engine/Import.cs b/src/Deprecated/Engine/Engine/Import.cs index ba22f096800..b7079e6f05c 100644 --- a/src/Deprecated/Engine/Engine/Import.cs +++ b/src/Deprecated/Engine/Engine/Import.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; @@ -55,9 +55,9 @@ public bool IsImported /// LukaszG public string ProjectPath { - get - { - return this.projectPathAttribute?.Value; + get + { + return this.projectPathAttribute?.Value; } set { @@ -94,9 +94,9 @@ public string EvaluatedProjectPath /// LukaszG public string Condition { - get - { - return this.conditionAttribute?.Value; + get + { + return this.conditionAttribute?.Value; } set { @@ -136,11 +136,11 @@ internal Import(XmlElement importElement, Project parentProject, bool isImported "Need an XML node representing the element."); this.importElement = importElement; - + // Make sure we have a valid parent Project ErrorUtilities.VerifyThrow(parentProject != null, "Need a parent Project object to instantiate an Import."); - + this.parentProject = parentProject; // Make sure this really is the node. diff --git a/src/Deprecated/Engine/Engine/ImportCollection.cs b/src/Deprecated/Engine/Engine/ImportCollection.cs index e67db1d68c2..5d2a7d317d9 100644 --- a/src/Deprecated/Engine/Engine/ImportCollection.cs +++ b/src/Deprecated/Engine/Engine/ImportCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -112,7 +112,7 @@ public object SyncRoot #endregion #region Members - + /// /// Read-only accessor for the Project instance that this ImportCollection belongs to. /// @@ -173,7 +173,7 @@ public void AddNewImport(string projectFile, string condition) XmlElement projectElement = this.parentProject.ProjectElement; XmlElement newImportElement = projectElement.OwnerDocument.CreateElement(XMakeElements.import, XMakeAttributes.defaultXmlNamespace); - + if (condition != null) { newImportElement.SetAttribute(XMakeAttributes.condition, condition); @@ -211,7 +211,7 @@ Import importToRemove // Remove the import from our hashtable. this.imports.Remove(importToRemove.EvaluatedProjectPath); - + // Dissociate the import from the parent project. importToRemove.ParentProject = null; diff --git a/src/Deprecated/Engine/Engine/ImportedProject.cs b/src/Deprecated/Engine/Engine/ImportedProject.cs index b681602d6cd..e00308c90a7 100644 --- a/src/Deprecated/Engine/Engine/ImportedProject.cs +++ b/src/Deprecated/Engine/Engine/ImportedProject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Deprecated/Engine/Engine/IntrinsicFunctions.cs b/src/Deprecated/Engine/Engine/IntrinsicFunctions.cs index 4cc32723604..36edcdfd0f7 100644 --- a/src/Deprecated/Engine/Engine/IntrinsicFunctions.cs +++ b/src/Deprecated/Engine/Engine/IntrinsicFunctions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -239,7 +239,7 @@ internal static string MakeRelative(string basePath, string path) return result; } - + /// /// Locate a file in either the directory specified or a location in the /// direcorty structure above that directory. diff --git a/src/Deprecated/Engine/Engine/ItemBucket.cs b/src/Deprecated/Engine/Engine/ItemBucket.cs index 56faf58e576..b351e8c182f 100644 --- a/src/Deprecated/Engine/Engine/ItemBucket.cs +++ b/src/Deprecated/Engine/Engine/ItemBucket.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Deprecated/Engine/Engine/Node.cs b/src/Deprecated/Engine/Engine/Node.cs index da393b51c0c..15647bced7c 100644 --- a/src/Deprecated/Engine/Engine/Node.cs +++ b/src/Deprecated/Engine/Engine/Node.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -110,7 +110,7 @@ internal void PostBuildRequestToHost(BuildRequest currentRequest) // Add the request to the mapping hashtable so that we can recognize the outputs CacheScope cacheScope = localEngine.CacheManager.GetCacheScope(currentRequest.ProjectFileName, currentRequest.GlobalProperties, currentRequest.ToolsetVersion, CacheContentType.BuildResults); NodeRequestMapping nodeRequestMapping = - new NodeRequestMapping(currentRequest.HandleId, currentRequest.RequestId, cacheScope ); + new NodeRequestMapping(currentRequest.HandleId, currentRequest.RequestId, cacheScope); lock (requestToLocalIdMapping) { requestToLocalIdMapping.Add(lastRequestIdUsed, nodeRequestMapping); @@ -317,7 +317,7 @@ internal void PostBuildResult(BuildResult buildResult) internal void ShutdownNode(NodeShutdownLevel shutdownLevel) { if (shutdownLevel == NodeShutdownLevel.BuildCompleteSuccess || - shutdownLevel == NodeShutdownLevel.BuildCompleteFailure ) + shutdownLevel == NodeShutdownLevel.BuildCompleteFailure) { if (Engine.debugMode) { @@ -381,7 +381,7 @@ bool useBreadthFirstTraversal if (localEngine != null) { localEngine.LoggingServices.OnlyLogCriticalEvents = this.logOnlyCriticalEvents; - localEngine.PostEngineCommand( new ChangeTraversalTypeCommand( useBreadthFirstTraversal, true )); + localEngine.PostEngineCommand(new ChangeTraversalTypeCommand(useBreadthFirstTraversal, true)); } } diff --git a/src/Deprecated/Engine/Engine/NodeLoggingEvent.cs b/src/Deprecated/Engine/Engine/NodeLoggingEvent.cs index e13682f60aa..2aacc066b71 100644 --- a/src/Deprecated/Engine/Engine/NodeLoggingEvent.cs +++ b/src/Deprecated/Engine/Engine/NodeLoggingEvent.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -46,7 +46,7 @@ internal NodeLoggingEvent() /// internal NodeLoggingEvent(BuildEventArgs eventToLog) { - this.e = eventToLog; + this.e = eventToLog; } #endregion @@ -66,7 +66,7 @@ internal BuildEventArgs BuildEvent /// The ID of the central logger to which this event should be forwarded. By default /// all regular non-forwarded events are sent to all loggers registered on the parent. /// - virtual internal int LoggerId + internal virtual int LoggerId { get { @@ -156,7 +156,7 @@ private BuildEventArgs GetBuildEventArgFromId(LoggingEventType id) case LoggingEventType.BuildStartedEvent: return new BuildStartedEventArgs(null, null); case LoggingEventType.BuildWarningEvent: - return new BuildWarningEventArgs(null, null, null, -1, -1, -1, -1,null,null,null); + return new BuildWarningEventArgs(null, null, null, -1, -1, -1, -1, null, null, null); case LoggingEventType.ProjectFinishedEvent: return new ProjectFinishedEventArgs(null, null, null, false); case LoggingEventType.ProjectStartedEvent: @@ -249,24 +249,24 @@ internal virtual void CreateFromStream(BinaryReader reader, Hashtable loggingTyp customEventsLoaded.Add(fileLocation, null); } } + if (resolveAssembly) + { + resolver = new TaskEngineAssemblyResolver(); + resolver.InstallHandler(); + resolver.Initialize(fileLocation); + } + try + { + e = (BuildEventArgs)binaryFormatter.Deserialize(reader.BaseStream); + } + finally + { if (resolveAssembly) { - resolver = new TaskEngineAssemblyResolver(); - resolver.InstallHandler(); - resolver.Initialize(fileLocation); - } - try - { - e = (BuildEventArgs)binaryFormatter.Deserialize(reader.BaseStream); - } - finally - { - if (resolveAssembly) - { - resolver.RemoveHandler(); - resolver = null; - } + resolver.RemoveHandler(); + resolver = null; } + } } } #endregion @@ -297,7 +297,7 @@ internal NodeLoggingEventWithLoggerId() /// Create a wrapper for a given event associated with a particular loggerId /// internal NodeLoggingEventWithLoggerId(BuildEventArgs eventToLog, int loggerId) - :base(eventToLog) + : base(eventToLog) { this.loggerId = loggerId; } diff --git a/src/Deprecated/Engine/Engine/NodeManager.cs b/src/Deprecated/Engine/Engine/NodeManager.cs index c963d35e73c..f80d1707a43 100644 --- a/src/Deprecated/Engine/Engine/NodeManager.cs +++ b/src/Deprecated/Engine/Engine/NodeManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -60,9 +60,9 @@ internal bool RegisterNodeProvider(INodeProvider nodeProviderToRegister) nodeProviderToRegister.AssignNodeIdentifiers(nodeIds); // Go through all of the nodes as described by nodeDescriptions and add them to out list of nodes - for(int i=0; i < nodeDescriptions.Length;i++) + for (int i = 0; i < nodeDescriptions.Length; i++) { - ProvidersNodeInformation nodeToAddFromProvider = + ProvidersNodeInformation nodeToAddFromProvider = new ProvidersNodeInformation(i, nodeIds[i], nodeDescriptions[i], nodeProviderToRegister); nodeList.Add(nodeToAddFromProvider); } @@ -79,16 +79,16 @@ internal bool RegisterNodeProvider(INodeProvider nodeProviderToRegister) /// internal INodeDescription[] GetNodeDescriptions() { - // The number of node descriptions is the number of nodes from all of the node providers, plus one for the default "0" node - INodeDescription[] nodeDescription = new INodeDescription[nodeList.Count+1]; - nodeDescription[0] = null; - for (int nodeListIndex = 0; nodeListIndex < nodeList.Count; nodeListIndex++) - { - ProvidersNodeInformation nodeInfo = nodeList[nodeListIndex]; - // +1 because the node description already has the 0 element set to null - nodeDescription[nodeListIndex + 1] = nodeInfo.Description; - } - return nodeDescription; + // The number of node descriptions is the number of nodes from all of the node providers, plus one for the default "0" node + INodeDescription[] nodeDescription = new INodeDescription[nodeList.Count + 1]; + nodeDescription[0] = null; + for (int nodeListIndex = 0; nodeListIndex < nodeList.Count; nodeListIndex++) + { + ProvidersNodeInformation nodeInfo = nodeList[nodeListIndex]; + // +1 because the node description already has the 0 element set to null + nodeDescription[nodeListIndex + 1] = nodeInfo.Description; + } + return nodeDescription; } /// @@ -153,7 +153,7 @@ internal NodeStatus[] RequestStatusForNodes(int responseTimeout) internal void PostNodeStatus(int nodeId, NodeStatus nodeStatus) { - ErrorUtilities.VerifyThrow( nodeStatus.RequestId != NodeStatus.UnrequestedStatus, + ErrorUtilities.VerifyThrow(nodeStatus.RequestId != NodeStatus.UnrequestedStatus, "Node manager should not receive unrequested status"); NodeStatus[] currentStatus = statusForNodes; @@ -173,8 +173,8 @@ internal void PostNodeStatus(int nodeId, NodeStatus nodeStatus) internal void PostCycleNotification ( - int nodeId, - TargetInProgessState child, + int nodeId, + TargetInProgessState child, TargetInProgessState parent) { if (nodeId == 0) @@ -232,7 +232,7 @@ internal void PostBuildResultToNode(int nodeIndex, BuildResult buildResult) ErrorUtilities.VerifyThrow(nodeIndex <= nodeList.Count, "Should not pass a node index higher then the number of nodes in nodeManager"); if (nodeIndex != 0) { - nodeList[nodeIndex-1].NodeProvider.PostBuildResultToNode(nodeList[nodeIndex-1].NodeIndex, buildResult); + nodeList[nodeIndex - 1].NodeProvider.PostBuildResultToNode(nodeList[nodeIndex - 1].NodeIndex, buildResult); } else { @@ -265,7 +265,7 @@ internal void ExecuteTask(TaskExecutionState taskState) /// internal void UpdateSettings ( - bool enableOutofProcLogging, + bool enableOutofProcLogging, bool enableOnlyLogCriticalEvents, bool useBreadthFirstTraversal ) @@ -284,11 +284,11 @@ internal void ChangeNodeTraversalType(bool breadthFirstTraversal) #endregion #region Properties - + /// /// Getter access to the local node /// - internal TaskExecutionModule TaskExecutionModule + internal TaskExecutionModule TaskExecutionModule { get { @@ -299,7 +299,7 @@ internal TaskExecutionModule TaskExecutionModule taskExecutionModule = value; } } - + /// /// Number of Nodes being managed by NodeManager /// @@ -308,7 +308,7 @@ internal int MaxNodeCount get { // add 1 for the local node (taskExecutionModule) - return nodeList.Count+1; + return nodeList.Count + 1; } } #endregion diff --git a/src/Deprecated/Engine/Engine/NodeRequestMapping.cs b/src/Deprecated/Engine/Engine/NodeRequestMapping.cs index f72938b9b08..d17c3b1afef 100644 --- a/src/Deprecated/Engine/Engine/NodeRequestMapping.cs +++ b/src/Deprecated/Engine/Engine/NodeRequestMapping.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BuildEngine.Shared; @@ -14,7 +14,7 @@ internal class NodeRequestMapping #region Constructors internal NodeRequestMapping - (int handleId, int requestId, CacheScope resultsCache ) + (int handleId, int requestId, CacheScope resultsCache) { ErrorUtilities.VerifyThrow(resultsCache != null, "Expect a non-null build result"); this.handleId = handleId; diff --git a/src/Deprecated/Engine/Engine/Project.cs b/src/Deprecated/Engine/Engine/Project.cs index 45327c63a75..81ca6348c7c 100644 --- a/src/Deprecated/Engine/Engine/Project.cs +++ b/src/Deprecated/Engine/Engine/Project.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -69,10 +69,10 @@ public class Project #region Member Data // The parent Engine object for this project. - private Engine parentEngine; + private Engine parentEngine; // Event location contextual information for the current project instance - private BuildEventContext projectBuildEventContext; + private BuildEventContext projectBuildEventContext; // We need to know if the projectContextId which was generated during the // instantiation of the project instance has been used. If the Id has been used, @@ -85,77 +85,77 @@ public class Project private int projectId; // indicates if the project (file) and all its imported files are validated against a schema - private bool isValidated; + private bool isValidated; // the schema against which to validate the project (file) and all its imported files - private string schemaFile; + private string schemaFile; // The XML document for the main project file. - private XmlDocument mainProjectEntireContents; + private XmlDocument mainProjectEntireContents; // The XML node of the main project file which was loaded // (as opposed to any imported project files). - private XmlElement mainProjectElement; + private XmlElement mainProjectElement; // The default targets, specified as an optional attribute on the // element. - private string[] defaultTargetNames; + private string[] defaultTargetNames; // The names of the targets specified in the InitialTargets attributes // on the node. We separate the ones in the main project from // the ones in the imported projects to make the object model more sensible. // These ArrayLists contain strings. - private ArrayList initialTargetNamesInMainProject; - private ArrayList initialTargetNamesInImportedProjects; + private ArrayList initialTargetNamesInMainProject; + private ArrayList initialTargetNamesInImportedProjects; // The fully qualified path to the project file for this project. // If the project was loaded from in-memory XML, this will empty string. - private string fullFileName; + private string fullFileName; // This is the directory containing the project file - private string projectDirectory; + private string projectDirectory; // The set of global properties for this project. For example, global // properties may be set at the command-line via the /p: switch. - private BuildPropertyGroup globalProperties; + private BuildPropertyGroup globalProperties; // The set of properties coming from environment variables. - private BuildPropertyGroup environmentProperties; + private BuildPropertyGroup environmentProperties; // The set of XMake reserved properties for this project (e.g., // XMakeProjectName). - private BuildPropertyGroup reservedProperties; + private BuildPropertyGroup reservedProperties; // The raw persisted 's in the project file. - private BuildPropertyGroupCollection rawPropertyGroups; + private BuildPropertyGroupCollection rawPropertyGroups; // The set of all s in the project file after they've been evaluated // and made useful for end-users. - private TargetCollection targets; + private TargetCollection targets; // The name of the first target in the main project. This is used as the default // target when one isn't specified in some other way. - private string nameOfFirstTarget = null; + private string nameOfFirstTarget = null; // The final set of evaluated and expanded property values for this // project, which includes all global properties, environment properties, // reserved properties, and properties in the main project file and // any imported project files - taking into account property precedence // rules, of course. - internal BuildPropertyGroup evaluatedProperties; + internal BuildPropertyGroup evaluatedProperties; // This hash table keeps track of the properties that are referenced inside // any "Condition" attribute in the entire project, and for each such // property, we keep the list of string values that the property is // being tested against. This is how the IDE gets at the list of // configurations for a project. - private Hashtable conditionedPropertiesTable; + private Hashtable conditionedPropertiesTable; // The raw persisted 's in the project file. - private BuildItemGroupCollection rawItemGroups; + private BuildItemGroupCollection rawItemGroups; // The raw collection of all grouping elements (ItemGroup, BuildPropertyGroup, and Choose. - private GroupingCollection rawGroups; + private GroupingCollection rawGroups; // Each entry in this contains an BuildItemGroup. Each of these // ItemGroups represents a list of "BuildItem" objects all of the same item type. @@ -164,7 +164,7 @@ public class Project // (the tasks). It represents true reality, and therefore it gets // re-computed every time something in the project changes (like a property // value for example). - internal Hashtable evaluatedItemsByName; + internal Hashtable evaluatedItemsByName; // All the item definitions in the logical project, including imports. // (Imported definitions don't need to be distinguished, since we don't have OM support @@ -178,7 +178,7 @@ public class Project /// and therefore it gets re-computed every time something in the project changes /// (like a property value for example). /// - internal BuildItemGroup evaluatedItems; + internal BuildItemGroup evaluatedItems; // This is a Hashtable of ItemGroups. Each BuildItemGroup contains a list of Items // of a the same type. The key for the Hashtable is the "item type" string. @@ -199,7 +199,7 @@ public class Project // get used for "build" purposes, since it is not entirely accurate and up-to- // date. It is only to be consumed by the IDE for purposes of displaying // items in the Solution Explorer (for example). - internal Hashtable evaluatedItemsByNameIgnoringCondition; + internal Hashtable evaluatedItemsByNameIgnoringCondition; // A single BuildItemGroup containing all the items in the project, after // wildcard and property expansion, but ignoring "Condition"s. So, for example, @@ -218,52 +218,52 @@ public class Project // get used for "build" purposes, since it is not entirely accurate and up-to- // date. It is only to be consumed by the IDE for purposes of displaying // items in the Solution Explorer (for example). - internal BuildItemGroup evaluatedItemsIgnoringCondition; + internal BuildItemGroup evaluatedItemsIgnoringCondition; // This array list contains the ordered list of elements in // the project file and all the imported files. When we // object model for these things has been worked out, there should // be an actual class here that we define, rather than an array list. - private UsingTaskCollection usingTasks; + private UsingTaskCollection usingTasks; // holds all the tasks the project knows about and the assemblies they exist in // NOTE: tasks and their assemblies are declared in a project with the tag - private ITaskRegistry taskRegistry; + private ITaskRegistry taskRegistry; // The XML node if there is one. - private XmlNode projectExtensionsNode; + private XmlNode projectExtensionsNode; // This hash table simply keeps track of the list of imported project // files so that we can detect a circular import to prevent infinite // recursion. - private ImportCollection imports; + private ImportCollection imports; // Tells us if anything has changed that would require us to re-read and re- // process the XML. The main scenario here would be the addition or removal // of an tag. - private bool dirtyNeedToReprocessXml; + private bool dirtyNeedToReprocessXml; // Tells us if anything in this project has changed since the last time // we evaluated all our properties and items. That could include all sorts // of things like properties (including global properties), items, etc. // Note: The only reason this is internal is for unit tests. - private bool dirtyNeedToReevaluate; + private bool dirtyNeedToReevaluate; // Tells us whether we need to re-evaluate the conditions on global warnings and errors. - internal bool dirtyNeedToReevaluateGlobalWarningsAndErrors; + internal bool dirtyNeedToReevaluateGlobalWarningsAndErrors; // Tells us if anything in this project has changed since the last time // we either loaded or saved the project file to disk. That could include all sorts // of things like properties (including global properties), items, etc. - private bool dirtyNeedToSaveProjectFile; + private bool dirtyNeedToSaveProjectFile; // Tells us the timestamp of when the project was last touched in a way // that would require it to need to be saved. - private DateTime timeOfLastDirty; + private DateTime timeOfLastDirty; // Tells us whether the project is currently in the "reset" state, meaning // that all of the targets are marked NotStarted. - private bool isReset; + private bool isReset; // This variable indicates whether a particular project was loaded by the host // (e.g., the IDE) and therefore needs to be kept around permanently, or whether @@ -273,7 +273,7 @@ public class Project // way for the host to change it. The only entity that should every be changing // this to "false" is the Engine itself because it knows that we're just building // this project and don't need to keep it around for design-time scenarios. - private bool isLoadedByHost; + private bool isLoadedByHost; // This controls whether or not the building of targets/tasks is enabled for this // project. This is for security purposes in case a host wants to closely @@ -605,7 +605,7 @@ public string InitialTargets { // Return the concatenation of the initial target names from the main project and the ones from // all the imported projects. Join target names together with semicolons in between. - return String.Join("; ", (string[]) this.CombinedInitialTargetNames.ToArray(typeof(string))); + return String.Join("; ", (string[])this.CombinedInitialTargetNames.ToArray(typeof(string))); } set @@ -706,7 +706,7 @@ internal bool IsBuilding { get { - return buildingCount>0; + return buildingCount > 0; } } @@ -1211,7 +1211,7 @@ public string Xml { using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { - this.Save((TextWriter) stringWriter); + this.Save((TextWriter)stringWriter); return stringWriter.ToString(); } } @@ -1506,7 +1506,7 @@ internal void MarkProjectAsDirtyForReprocessXml ( ) { - this.MarkProjectAsDirty (); + this.MarkProjectAsDirty(); this.dirtyNeedToReprocessXml = true; } @@ -1966,7 +1966,7 @@ ProjectLoadSettings projectLoadSettings { BuildEventFileInfo fileInfo = new BuildEventFileInfo(e); - ParentEngine.LoggingServices.LogError(projectBuildEventContext, null,fileInfo, "InvalidProjectFile", e.Message); + ParentEngine.LoggingServices.LogError(projectBuildEventContext, null, fileInfo, "InvalidProjectFile", e.Message); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, fileInfo, "InvalidProjectFile", e.Message); @@ -2747,7 +2747,7 @@ string itemInclude // the same type as the new item being added. foreach (BuildItem originalItem in itemGroup) { - if ( String.Equals( originalItem.Name, itemName, StringComparison.OrdinalIgnoreCase)) + if (String.Equals(originalItem.Name, itemName, StringComparison.OrdinalIgnoreCase)) { // If the new item that the user is trying to add is already covered by // a wildcard in an existing item of the project, then there's really @@ -2928,7 +2928,7 @@ BuildItem itemToRemove // If the item doesn't have a parent BuildItemGroup associated with it, then it // must not be a persisted item that's actually declared in the project file. parentItemGroup = itemToRemove.ParentPersistedItemGroup; - error.VerifyThrowInvalidOperation (parentItemGroup != null, "ObjectIsNotInProject"); + error.VerifyThrowInvalidOperation(parentItemGroup != null, "ObjectIsNotInProject"); } else { @@ -2954,7 +2954,7 @@ BuildItem itemToRemove this.RemoveItemGroup(parentItemGroup); } - this.MarkProjectAsDirty (); + this.MarkProjectAsDirty(); } /// @@ -3041,7 +3041,7 @@ public void SetProjectExtensions(string id, string content) } // Look in the extensions node and see if there is a child that matches - XmlElement idElement = (XmlElement) projectExtensionsNode[id]; + XmlElement idElement = (XmlElement)projectExtensionsNode[id]; // Found anything? if (idElement == null) @@ -3109,7 +3109,7 @@ public bool Build string targetName ) { - return this.ParentEngine.BuildProject(this, (targetName == null) ? null : new string[] {targetName}, + return this.ParentEngine.BuildProject(this, (targetName == null) ? null : new string[] { targetName }, null, BuildSettings.None); } @@ -3233,7 +3233,7 @@ internal void ContinueBuild(ProjectBuildState buildContext, TaskExecutionContext if (buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.BuildingCurrentTarget) { // Execute the next appropriate operation for this target - ErrorUtilities.VerifyThrow( taskExecutionContext != null, "Task context should be non-null"); + ErrorUtilities.VerifyThrow(taskExecutionContext != null, "Task context should be non-null"); taskExecutionContext.ParentTarget.ContinueBuild(taskExecutionContext.BuildContext, taskExecutionContext); } else if (buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.StartingFirstTarget) @@ -3275,7 +3275,7 @@ internal void ContinueBuild(ProjectBuildState buildContext, TaskExecutionContext } finally { - if ( (exitedDueToError || buildContext.BuildComplete) && + if ((exitedDueToError || buildContext.BuildComplete) && buildContext.CurrentBuildContextState != ProjectBuildState.BuildContextState.RequestFilled) { // If the target that threw an exception is being built due to an @@ -3471,30 +3471,30 @@ private ProjectBuildState InitializeForBuildingTargets(BuildRequest buildRequest BuildEventContext buildEventContext = null; // Determine if a project started event is required to be fired, if so we may need a new projectContextId - if (buildRequest.FireProjectStartedFinishedEvents) - { - //If we have not already used the context from the project yet, lets use that as our first event context - if (!haveUsedInitialProjectContextId) - { - buildEventContext = projectBuildEventContext; - haveUsedInitialProjectContextId = true; - } - else // We are going to need a new Project context Id and a new buildEventContext - { - projectContextId = parentEngine.GetNextProjectId(); - } - } - - if (buildEventContext == null) - { - buildEventContext = new BuildEventContext - ( - projectBuildEventContext.NodeId, - projectBuildEventContext.TargetId, - projectContextId, - projectBuildEventContext.TaskId - ); - } + if (buildRequest.FireProjectStartedFinishedEvents) + { + //If we have not already used the context from the project yet, lets use that as our first event context + if (!haveUsedInitialProjectContextId) + { + buildEventContext = projectBuildEventContext; + haveUsedInitialProjectContextId = true; + } + else // We are going to need a new Project context Id and a new buildEventContext + { + projectContextId = parentEngine.GetNextProjectId(); + } + } + + if (buildEventContext == null) + { + buildEventContext = new BuildEventContext + ( + projectBuildEventContext.NodeId, + projectBuildEventContext.TargetId, + projectContextId, + projectBuildEventContext.TaskId + ); + } bool exitedDueToError = true; @@ -3733,8 +3733,8 @@ private void ProcessMainProjectElement /// RGoel private void ProcessProjectAttributes ( - XmlElement projectElement, - bool importedProject + XmlElement projectElement, + bool importedProject ) { // Make sure the node has been given to us. @@ -3863,15 +3863,15 @@ bool importedProject this.rawItemGroups.InsertAtEnd(newItemGroup); break; - // Process the element. - case XMakeElements.propertyGroup: - BuildPropertyGroup newPropertyGroup = new BuildPropertyGroup(this, childElement, importedProject); - newPropertyGroup.EnsureNoReservedProperties(); - this.rawPropertyGroups.InsertAtEnd(newPropertyGroup); - // PropertyGroups/Chooses are evaluated immediately during this scan, as they're needed to figure out whether - // we include Imports. - newPropertyGroup.Evaluate(this.evaluatedProperties, this.conditionedPropertiesTable, ProcessingPass.Pass1); - break; + // Process the element. + case XMakeElements.propertyGroup: + BuildPropertyGroup newPropertyGroup = new BuildPropertyGroup(this, childElement, importedProject); + newPropertyGroup.EnsureNoReservedProperties(); + this.rawPropertyGroups.InsertAtEnd(newPropertyGroup); + // PropertyGroups/Chooses are evaluated immediately during this scan, as they're needed to figure out whether + // we include Imports. + newPropertyGroup.Evaluate(this.evaluatedProperties, this.conditionedPropertiesTable, ProcessingPass.Pass1); + break; // Process the element. case XMakeElements.choose: @@ -3936,7 +3936,7 @@ bool importedProject case XMakeElements.importGroup: foreach (XmlElement importGroupChild in childElement.ChildNodes) { - switch(importGroupChild.Name) + switch (importGroupChild.Name) { case XMakeElements.import: ProcessImportElement(importGroupChild, projectDirectoryLocation, importedProject); @@ -3977,9 +3977,9 @@ bool importedProject /// private void ProcessImportElement ( - XmlElement importElement, - string projectDirectoryLocation, - bool importedProject + XmlElement importElement, + string projectDirectoryLocation, + bool importedProject ) { Import temp = new Import(importElement, this, importedProject); @@ -4008,7 +4008,7 @@ bool importedProject for (int i = 0; i < importedFilenames.Length; i++) { - string importedFilename = EscapingUtilities.UnescapeAll(importedFilenames[i]); + string importedFilename = EscapingUtilities.UnescapeAll(importedFilenames[i]); ProjectErrorUtilities.VerifyThrowInvalidProject(!string.IsNullOrEmpty(importedFilename), importElement, "MissingRequiredAttribute", XMakeAttributes.project, XMakeElements.import); @@ -4029,7 +4029,9 @@ bool importedProject catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } ProjectErrorUtilities.VerifyThrowInvalidProject(false, importElement, "InvalidAttributeValueWithException", importedFilename, XMakeAttributes.project, XMakeElements.import, e.Message); } @@ -4155,7 +4157,9 @@ private XmlDocument LoadImportedProject(Import import) catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } BuildEventFileInfo fileInfo = new BuildEventFileInfo(import.EvaluatedProjectPath); ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, @@ -4293,11 +4297,11 @@ private void EvaluateAllPropertyGroups { if (propertyGroup is BuildPropertyGroup) { - ((BuildPropertyGroup) propertyGroup).Evaluate(this.evaluatedProperties, this.conditionedPropertiesTable, ProcessingPass.Pass1); + ((BuildPropertyGroup)propertyGroup).Evaluate(this.evaluatedProperties, this.conditionedPropertiesTable, ProcessingPass.Pass1); } else if (propertyGroup is Choose) { - ((Choose) propertyGroup).Evaluate(this.evaluatedProperties, false, true, this.conditionedPropertiesTable, ProcessingPass.Pass1); + ((Choose)propertyGroup).Evaluate(this.evaluatedProperties, false, true, this.conditionedPropertiesTable, ProcessingPass.Pass1); } else { @@ -4325,11 +4329,11 @@ bool honorCondition { if (itemGroup is BuildItemGroup) { - ((BuildItemGroup) itemGroup).Evaluate(this.evaluatedProperties, this.evaluatedItemsByName, ignoreCondition, honorCondition, ProcessingPass.Pass2); + ((BuildItemGroup)itemGroup).Evaluate(this.evaluatedProperties, this.evaluatedItemsByName, ignoreCondition, honorCondition, ProcessingPass.Pass2); } else if (itemGroup is Choose) { - ((Choose) itemGroup).Evaluate(this.evaluatedProperties, ignoreCondition, honorCondition, this.conditionedPropertiesTable, ProcessingPass.Pass2); + ((Choose)itemGroup).Evaluate(this.evaluatedProperties, ignoreCondition, honorCondition, this.conditionedPropertiesTable, ProcessingPass.Pass2); } else { diff --git a/src/Deprecated/Engine/Engine/ProjectBuildState.cs b/src/Deprecated/Engine/Engine/ProjectBuildState.cs index 676ba8a9af5..b1dcc8ef06d 100644 --- a/src/Deprecated/Engine/Engine/ProjectBuildState.cs +++ b/src/Deprecated/Engine/Engine/ProjectBuildState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -207,7 +207,7 @@ internal bool ContainsCycle(string name) } if (!containsCycle && requiredTargets?.Count > 0) { - containsCycle = + containsCycle = (String.Equals(name, (string)targetNamesToBuild[indexOfTargetInProgress], StringComparison.OrdinalIgnoreCase)); } return containsCycle; @@ -244,7 +244,7 @@ internal string GetParentTarget(string name) { string[] requiredTargetsArray = requiredTargets.ToArray(); - for (int i = requiredTargetsArray.Length-1; i >= 0; i--) + for (int i = requiredTargetsArray.Length - 1; i >= 0; i--) { if (string.CompareOrdinal(requiredTargetsArray[i], name) != 0) { @@ -317,18 +317,23 @@ internal enum BuildContextState #region Data // Stack of targets which need to be completed before the in progress target can continue - Stack requiredTargets; + private Stack requiredTargets; + // BuildEventContext for the build context - BuildEventContext projectBuildEventContext; + private BuildEventContext projectBuildEventContext; + // Index of the currently in progress target - int indexOfTargetInProgress; + private int indexOfTargetInProgress; + // List of targets that need to be completed in order to complete the context // UNDONE should do the right thing and fully unescape before generating this list - ArrayList targetNamesToBuild; + private ArrayList targetNamesToBuild; + // Build request that caused the context to come into existance (either from the host or generated) - BuildRequest buildRequest; + private BuildRequest buildRequest; + // Current state of the context - BuildContextState buildContextState; + private BuildContextState buildContextState; #endregion } } diff --git a/src/Deprecated/Engine/Engine/ProjectManager.cs b/src/Deprecated/Engine/Engine/ProjectManager.cs index 8a19e03eafb..59b3c2c4d21 100644 --- a/src/Deprecated/Engine/Engine/ProjectManager.cs +++ b/src/Deprecated/Engine/Engine/ProjectManager.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #region Using directives @@ -80,7 +80,7 @@ Project project project_index = i; } } - + // The project should be in the table ErrorUtilities.VerifyThrow(project_index != -1, "Project missing from the list"); @@ -153,11 +153,11 @@ string projectFileFullPath ) { // Get the list of projects that have this full path. - ArrayList projectsWithThisFullPath = (ArrayList) this.projects[projectFileFullPath]; + ArrayList projectsWithThisFullPath = (ArrayList)this.projects[projectFileFullPath]; if ((projectsWithThisFullPath?.Count > 0)) { - return (Project) projectsWithThisFullPath[0]; + return (Project)projectsWithThisFullPath[0]; } // No project was found that matched the full path specified. @@ -434,7 +434,7 @@ internal class ProjectEntry internal string toolsVersion; internal int nodeIndex; } - + #endregion } } diff --git a/src/Deprecated/Engine/Engine/ProjectSchemaValidationHandler.cs b/src/Deprecated/Engine/Engine/ProjectSchemaValidationHandler.cs index ab4840d7004..2b8536bf7e2 100644 --- a/src/Deprecated/Engine/Engine/ProjectSchemaValidationHandler.cs +++ b/src/Deprecated/Engine/Engine/ProjectSchemaValidationHandler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -18,7 +18,7 @@ namespace Microsoft.Build.BuildEngine internal sealed class ProjectSchemaValidationHandler { // The parent Engine object for this project. - private EngineLoggingServices engineLoggingServices ; + private EngineLoggingServices engineLoggingServices; // the location of the MSBuild binaries private string binPath; @@ -114,7 +114,7 @@ string projectFile validatorSettings.ValidationType = ValidationType.Schema; validatorSettings.XmlResolver = null; validatorSettings.ValidationEventHandler += this.OnSchemaValidationError; - + if (string.IsNullOrEmpty(schemaFile)) { schemaFile = Path.Combine(binPath, "Microsoft.Build.xsd"); diff --git a/src/Deprecated/Engine/Engine/RegistryKeyWrapper.cs b/src/Deprecated/Engine/Engine/RegistryKeyWrapper.cs index b0a635794c7..cec7b909fea 100644 --- a/src/Deprecated/Engine/Engine/RegistryKeyWrapper.cs +++ b/src/Deprecated/Engine/Engine/RegistryKeyWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -75,7 +75,9 @@ public virtual string Name catch (Exception ex) { if (NotExpectedException(ex)) + { throw; + } throw new RegistryException(ex.Message, ex); } @@ -96,7 +98,9 @@ public virtual object GetValue(string name) catch (Exception ex) { if (NotExpectedException(ex)) + { throw; + } throw new RegistryException(ex.Message, Name + "@" + name, ex); } @@ -115,7 +119,9 @@ public virtual string[] GetValueNames() catch (Exception ex) { if (NotExpectedException(ex)) + { throw; + } throw new RegistryException(ex.Message, Name, ex); } @@ -134,7 +140,9 @@ public virtual string[] GetSubKeyNames() catch (Exception ex) { if (NotExpectedException(ex)) + { throw; + } throw new RegistryException(ex.Message, Name, ex); } @@ -149,7 +157,7 @@ public virtual string[] GetSubKeyNames() public virtual RegistryKeyWrapper OpenSubKey(string name) { ErrorUtilities.VerifyThrowArgumentLength(name, nameof(name)); - + RegistryKeyWrapper wrapper = this; string[] keyNames = name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries); @@ -162,7 +170,9 @@ public virtual RegistryKeyWrapper OpenSubKey(string name) catch (Exception ex) { if (NotExpectedException(ex)) + { throw; + } throw new RegistryException(ex.Message, wrapper.Name + "\\" + keyNames[i], ex); } @@ -199,7 +209,9 @@ private RegistryKey WrappedKey catch (Exception ex) { if (NotExpectedException(ex)) + { throw; + } throw new RegistryException(ex.Message, Name, ex); } @@ -212,7 +224,7 @@ private RegistryKey WrappedKey return wrappedKey; } } - + /// /// Returns false if this is a known exception thrown by the registry API. /// diff --git a/src/Deprecated/Engine/Engine/RequestRoutingContext.cs b/src/Deprecated/Engine/Engine/RequestRoutingContext.cs index aa5287fde18..eaaeec445bc 100644 --- a/src/Deprecated/Engine/Engine/RequestRoutingContext.cs +++ b/src/Deprecated/Engine/Engine/RequestRoutingContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; @@ -24,12 +24,12 @@ internal RequestRoutingContext int nodeIndex, int parentHandleId, int parentNodeIndex, - int parentRequestId, + int parentRequestId, CacheScope cacheScope, BuildRequest triggeringBuildRequest, BuildEventContext buildEventContext ) - :base(handleId, nodeIndex, buildEventContext) + : base(handleId, nodeIndex, buildEventContext) { this.parentHandleId = parentHandleId; this.parentNodeIndex = parentNodeIndex; diff --git a/src/Deprecated/Engine/Engine/Router.cs b/src/Deprecated/Engine/Engine/Router.cs index 52150867a2e..83ce36a4d38 100644 --- a/src/Deprecated/Engine/Engine/Router.cs +++ b/src/Deprecated/Engine/Engine/Router.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine { @@ -121,12 +121,12 @@ internal void PostDoneNotice(BuildRequest buildRequest) /// internal void PostDoneNotice(int nodeId, BuildResult buildResult) { - - - // Notify the scheduler that a given node(nodeId) will be getting a buildResult. - // This method is a no-op if the router is on a child process - scheduler?.NotifyOfBuildResult(nodeId, buildResult); - + + + // Notify the scheduler that a given node(nodeId) will be getting a buildResult. + // This method is a no-op if the router is on a child process + scheduler?.NotifyOfBuildResult(nodeId, buildResult); + if (nodeId == EngineCallback.inProcNode) { @@ -169,13 +169,13 @@ internal void PostBuildRequest(BuildRequest currentRequest, int nodeIndex) (nodeIndex, currentRequest.HandleId, currentRequest.NodeIndex, currentRequest.RequestId, cacheScope, currentRequest, null); - - - // Check to see if we need to change the traversal strategy of the system - // parentHandleId and node index are not used in the function so it can be ignored - scheduler?.NotifyOfBuildRequest(nodeIndex, currentRequest, parentHandleId); - - + + + // Check to see if we need to change the traversal strategy of the system + // parentHandleId and node index are not used in the function so it can be ignored + scheduler?.NotifyOfBuildRequest(nodeIndex, currentRequest, parentHandleId); + + nodeManager.PostBuildRequestToNode(nodeIndex, currentRequest); } } @@ -187,27 +187,27 @@ internal void PostBuildRequest(BuildRequest currentRequest, int nodeIndex) /// /// The node manager is used as a proxy for communication with child nodes /// - NodeManager nodeManager; + private NodeManager nodeManager; /// /// The parent engine who instantiated the router /// - Engine parentEngine; + private Engine parentEngine; /// /// Scheduler who is responsible for determining which nodes a build request should be sent to. /// - Scheduler scheduler; + private Scheduler scheduler; /// /// Is the router instantiated on a child process /// - bool childMode; + private bool childMode; /// /// What is the parent Node on which the engine is hosted if we are a child process /// - Node parentNode; + private Node parentNode; #endregion } } diff --git a/src/Deprecated/Engine/Engine/Scheduler.cs b/src/Deprecated/Engine/Engine/Scheduler.cs index 110e2dbbf84..b5548c04cbd 100644 --- a/src/Deprecated/Engine/Engine/Scheduler.cs +++ b/src/Deprecated/Engine/Engine/Scheduler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -275,7 +275,7 @@ internal void NotifyOfBuildResult(int nodeId, BuildResult buildResult) } // Dump some interesting information to the console if profile build is turned on by an environment variable - if (parentEngine.ProfileBuild && scheduleRecord != null && buildResult.TaskTime != 0 ) + if (parentEngine.ProfileBuild && scheduleRecord != null && buildResult.TaskTime != 0) { Console.WriteLine("N " + scheduleRecord.EvaluationNode + " Name " + scheduleRecord.ProjectName + ":" + scheduleRecord.ParentKey.HandleId + ":" + scheduleRecord.ParentKey.RequestId + @@ -303,7 +303,7 @@ internal void NotifyOfBuildRequest(int nodeIndex, BuildRequest currentRequest, i { // Continue using breadth-first traversal as long as the non-blocked work load for this node is below // the nodeWorkloadProjectCount or its postBlockCount is non-zero - if ((totalRequestsPerNode[i] - blockedRequestsPerNode[i]) < nodeWorkLoadProjectCount || postBlockCount[i] != 0 ) + if ((totalRequestsPerNode[i] - blockedRequestsPerNode[i]) < nodeWorkLoadProjectCount || postBlockCount[i] != 0) { useBreadthFirstTraversal = true; break; @@ -314,7 +314,7 @@ internal void NotifyOfBuildRequest(int nodeIndex, BuildRequest currentRequest, i { if (Engine.debugMode) { - Console.WriteLine("Switching to depth first traversal because all node have workitems"); + Console.WriteLine("Switching to depth first traversal because all node have workitems"); } parentEngine.NodeManager.TaskExecutionModule.UseBreadthFirstTraversal = false; @@ -381,7 +381,7 @@ internal void NotifyOfBlockedNode(int nodeId) Console.WriteLine("Switch to breadth first traversal is requested by " + nodeId); } - postBlockCount[nodeId] = nodeWorkLoadProjectCount/2; + postBlockCount[nodeId] = nodeWorkLoadProjectCount / 2; } /// @@ -397,7 +397,7 @@ internal void DumpState() foreach (ScheduleRecordKey key in handleIdToScheduleRecord.Keys) { ScheduleRecord record = handleIdToScheduleRecord[key]; - Console.WriteLine(key.HandleId + ":" + key.RequestId + " " + record.ProjectName + " on node " + record.EvaluationNode); + Console.WriteLine(key.HandleId + ":" + key.RequestId + " " + record.ProjectName + " on node " + record.EvaluationNode); } } #endregion diff --git a/src/Deprecated/Engine/Engine/SchedulerRecord.cs b/src/Deprecated/Engine/Engine/SchedulerRecord.cs index b97261cb00a..ce054b5ae71 100644 --- a/src/Deprecated/Engine/Engine/SchedulerRecord.cs +++ b/src/Deprecated/Engine/Engine/SchedulerRecord.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; // For the debugger attribute @@ -17,12 +17,12 @@ internal class ScheduleRecord #region Constructors internal ScheduleRecord ( - ScheduleRecordKey recordKey, - ScheduleRecordKey parentKey, + ScheduleRecordKey recordKey, + ScheduleRecordKey parentKey, int evaluationNode, string projectName, string toolsVersion, - string [] targetsBuild + string[] targetsBuild ) { this.recordKey = recordKey; @@ -175,7 +175,7 @@ internal void ReportChildCompleted(ScheduleRecordKey key) /// This class is used as a key combining both HandleId and RequestId into a single class. /// [DebuggerDisplay("Key ({handleId},{requestId})")] - internal class ScheduleRecordKey + internal class ScheduleRecordKey { #region Constructors internal ScheduleRecordKey(int handleId, int requestId) diff --git a/src/Deprecated/Engine/Engine/Target.cs b/src/Deprecated/Engine/Engine/Target.cs index 73cd4911687..d6e23872382 100644 --- a/src/Deprecated/Engine/Engine/Target.cs +++ b/src/Deprecated/Engine/Engine/Target.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -55,17 +55,17 @@ internal enum BuildState #region Member Data // The evaluated name of the target. - private string targetName; + private string targetName; // The parent project.object. We will need this in order get the // complete list of targets, items, properties, etc. - private Project parentProject; + private Project parentProject; // The parent Engine object. - private Engine parentEngine; + private Engine parentEngine; // The state of this target, in terms of the build. - private BuildState buildState; + private BuildState buildState; // The XML element, if this is a persisted item. For virtual // items (i.e., those generated by tasks), this would be null. @@ -84,7 +84,7 @@ internal enum BuildState private XmlAttribute outputsAttribute = null; // This contains all of the child task nodes in this node. - ArrayList taskElementList = null; + private ArrayList taskElementList = null; // If this is a persisted element, this boolean tells us whether // it came from the main parentProject.file or an imported parentProject.file. @@ -103,11 +103,9 @@ internal enum BuildState // We check the target's condition to ensure it doesn't reference item metadata in an attempt to batch. private bool conditionCheckedForInvalidMetadataReferences = false; + private TargetExecutionWrapper executionState = null; + private List batchableTargetParameters = null; - TargetExecutionWrapper executionState = null; - - List batchableTargetParameters = null; - // TargetId private int id; @@ -124,13 +122,13 @@ internal enum BuildState /// internal Target ( - XmlElement targetElement, - Project project, - bool importedFromAnotherProject + XmlElement targetElement, + Project project, + bool importedFromAnotherProject ) { // Make sure a valid node has been given to us. - error.VerifyThrow(targetElement != null,"Need a valid XML node."); + error.VerifyThrow(targetElement != null, "Need a valid XML node."); // Make sure this really is the node. ProjectXmlUtilities.VerifyThrowElementName(targetElement, XMakeElements.target); @@ -147,7 +145,7 @@ bool importedFromAnotherProject // The target name and target dependendencies (dependencies on other // targets) are specified as attributes of the element. - XmlAttribute returnsAttribute = null; + XmlAttribute returnsAttribute = null; // Loop through all the attributes on the element. foreach (XmlAttribute targetAttribute in targetElement.Attributes) { @@ -277,7 +275,7 @@ internal int Id /// The target name string. public string Name { - get + get { return this.targetName; } @@ -532,7 +530,7 @@ internal void ResetBuildStatus /// internal void UpdateTargetStateOnBuildCompletion ( - BuildState stateOfBuild, + BuildState stateOfBuild, List targetOutputItemList ) { @@ -594,7 +592,7 @@ ProjectBuildState buildContext // Only contexts which are generated from an MSBuild task could need // the outputs of this target, such contexts have a non-null evaluation // request - if ((buildState == BuildState.CompletedSuccessfully) && + if ((buildState == BuildState.CompletedSuccessfully) && (buildContext.BuildRequest.OutputsByTarget != null && buildContext.NameOfBlockingTarget == null)) { @@ -683,7 +681,7 @@ ProjectBuildState buildContext /// /// Context within which the target is being executed /// Result of last execution (multi-threaded only) - internal void ContinueBuild( ProjectBuildState buildContext, TaskExecutionContext taskExecutionContext) + internal void ContinueBuild(ProjectBuildState buildContext, TaskExecutionContext taskExecutionContext) { executionState.ContinueBuild(buildContext, taskExecutionContext); } @@ -705,7 +703,7 @@ internal bool ExecuteOneTask(XmlElement taskNode, ITaskHost hostObject) ParentProject.ProjectBuildEventContext.ProjectContextId, ParentProject.ProjectBuildEventContext.TaskId ); - int handleId = parentEngine.EngineCallback.CreateTaskContext(ParentProject,this, null, taskNode, + int handleId = parentEngine.EngineCallback.CreateTaskContext(ParentProject, this, null, taskNode, EngineCallback.inProcNode, targetBuildEventContext); TaskExecutionModule taskExecutionModule = parentEngine.NodeManager.TaskExecutionModule; TaskEngine taskEngine = new TaskEngine(taskNode, hostObject, parentProject.FullFileName, projectFileOfTaskNode, parentEngine.LoggingServices, handleId, taskExecutionModule, targetBuildEventContext); @@ -725,11 +723,11 @@ internal void MarkTargetAsDirty ( ) { - - - // This is a change to the contents of the project file. - this.ParentProject?.MarkProjectAsDirty(); - + + + // This is a change to the contents of the project file. + this.ParentProject?.MarkProjectAsDirty(); + } /// diff --git a/src/Deprecated/Engine/Engine/TargetCollection.cs b/src/Deprecated/Engine/Engine/TargetCollection.cs index 3db0507014b..3f7fb230511 100644 --- a/src/Deprecated/Engine/Engine/TargetCollection.cs +++ b/src/Deprecated/Engine/Engine/TargetCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -22,8 +22,8 @@ public class TargetCollection : IEnumerable, ICollection #region Member Data // This is the hashtable of Targets (indexed by name) contained in this collection. - Hashtable targetTable = null; - Project parentProject = null; + private Hashtable targetTable = null; + private Project parentProject = null; #endregion diff --git a/src/Deprecated/Engine/Engine/TargetDependencyAnalyzer.cs b/src/Deprecated/Engine/Engine/TargetDependencyAnalyzer.cs index 71fefcb6bb9..2c1b036dc1d 100644 --- a/src/Deprecated/Engine/Engine/TargetDependencyAnalyzer.cs +++ b/src/Deprecated/Engine/Engine/TargetDependencyAnalyzer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -71,7 +71,7 @@ internal Target TargetToAnalyze } } - /// + /// /// Gets the value of the target's "Inputs" attribute. /// /// SumedhK @@ -249,7 +249,7 @@ out Hashtable upToDateTargetInputs loggingService.LogComment(buildEventContext, MessageImportance.Normal, "SkipTargetBecauseOutputsUpToDate", TargetToAnalyze.Name); - + // Log the target inputs & outputs if (!loggingService.OnlyLogCriticalEvents) { @@ -288,7 +288,7 @@ private void LogReasonForBuildingTarget(DependencyAnalysisResult result) if (result == DependencyAnalysisResult.FullBuild && this.dependencyAnalysisDetail.Count > 0) { // For the full build decision the are three possible outcomes - loggingService.LogComment(buildEventContext,"BuildTargetCompletely", this.targetToAnalyze.Name); + loggingService.LogComment(buildEventContext, "BuildTargetCompletely", this.targetToAnalyze.Name); foreach (DependencyAnalysisLogDetail logDetail in this.dependencyAnalysisDetail) { @@ -476,7 +476,7 @@ private DependencyAnalysisResult PerformDependencyAnalysisIfNoOutputs() // otherwise, don't build the target else { - loggingService.LogComment(buildEventContext, MessageImportance.Normal, + loggingService.LogComment(buildEventContext, MessageImportance.Normal, "SkipTargetBecauseNoOutputs", TargetToAnalyze.Name); // detailed reason is low importance to keep log clean loggingService.LogComment(buildEventContext, MessageImportance.Low, @@ -702,7 +702,7 @@ ArrayList targetOutputItemSpecs // if the target did declare inputs, but the specification evaluated to nothing if (TargetInputSpecification.Length > 0) { - loggingService.LogComment(buildEventContext, MessageImportance.Normal, + loggingService.LogComment(buildEventContext, MessageImportance.Normal, "SkipTargetBecauseNoInputs", TargetToAnalyze.Name); // detailed reason is low importance to keep log clean loggingService.LogComment(buildEventContext, MessageImportance.Low, @@ -725,8 +725,8 @@ ArrayList targetOutputItemSpecs else { DependencyAnalysisLogDetail dependencyAnalysisDetailEntry; - bool someOutOfDate = IsAnyOutOfDate(out dependencyAnalysisDetailEntry, projectDirectory, targetInputItemSpecs, targetOutputItemSpecs); - + bool someOutOfDate = IsAnyOutOfDate(out dependencyAnalysisDetailEntry, projectDirectory, targetInputItemSpecs, targetOutputItemSpecs); + if (someOutOfDate) { dependencyAnalysisDetail.Add(dependencyAnalysisDetailEntry); @@ -911,7 +911,7 @@ internal static bool IsAnyOutOfDate(out DependencyAnalysisLogDetail dependencyAn { ErrorUtilities.VerifyThrow((inputs.Count > 0) && (outputs.Count > 0), "Need to specify inputs and outputs."); - // Algorithm: walk through all the outputs to find the oldest output + // Algorithm: walk through all the outputs to find the oldest output // walk through the inputs as far as we need to until we find one that's newer (if any) // PERF -- we could change this to ensure that we walk the shortest list first (because we walk that one entirely): @@ -1210,22 +1210,27 @@ private int CompareLastWriteTimes(string path1, string path2, out bool path1Does private XmlAttribute targetInputsAttribute; // The XmlAttribute for the "Outputs" private XmlAttribute targetOutputsAttribute; + // Details of the dependency analysis for logging - ArrayList dependencyAnalysisDetail = new ArrayList(); + private ArrayList dependencyAnalysisDetail = new ArrayList(); + // The unique target inputs - Hashtable uniqueTargetInputs = new Hashtable(StringComparer.OrdinalIgnoreCase); + private Hashtable uniqueTargetInputs = new Hashtable(StringComparer.OrdinalIgnoreCase); + // The unique target outputs; - Hashtable uniqueTargetOutputs = new Hashtable(StringComparer.OrdinalIgnoreCase); + private Hashtable uniqueTargetOutputs = new Hashtable(StringComparer.OrdinalIgnoreCase); + // Engine logging service which to log message to - EngineLoggingServices loggingService; + private EngineLoggingServices loggingService; + // Event context information where event is raised from - BuildEventContext buildEventContext; + private BuildEventContext buildEventContext; } /// /// Why TLDA decided this entry was out of date /// - enum OutofdateReason + internal enum OutofdateReason { MissingInput, // The input file was missing MissingOutput, // The output file was missing @@ -1235,7 +1240,7 @@ enum OutofdateReason /// /// A logging detail entry. Describes what TLDA decided about inputs / outputs /// - class DependencyAnalysisLogDetail + internal class DependencyAnalysisLogDetail { private OutofdateReason reason; private string inputItemName; diff --git a/src/Deprecated/Engine/Engine/TargetExecutionWrapper.cs b/src/Deprecated/Engine/Engine/TargetExecutionWrapper.cs index 937cd28b801..1ba50ce82bd 100644 --- a/src/Deprecated/Engine/Engine/TargetExecutionWrapper.cs +++ b/src/Deprecated/Engine/Engine/TargetExecutionWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -36,10 +36,10 @@ BuildEventContext targetBuildEventContext ) { // Initialize the data about the target XML that has been calculated in the target class - this.targetClass = targetClass; - this.parentEngine = targetClass.ParentEngine; + this.targetClass = targetClass; + this.parentEngine = targetClass.ParentEngine; this.parentProject = targetClass.ParentProject; - this.targetElement = targetElement; + this.targetElement = targetElement; this.taskElementList = taskElementList; this.targetParameters = targetParameters; this.targetBuildEventContext = targetBuildEventContext; @@ -209,7 +209,7 @@ ProjectBuildState errorContext #region Methods for building dependencies ( InProgressBuildState.BuildingDependencies ) - private void ContinueBuildingDependencies (ProjectBuildState buildContext) + private void ContinueBuildingDependencies(ProjectBuildState buildContext) { // Verify that the target is in the right state ErrorUtilities.VerifyThrow(inProgressBuildState == InProgressBuildState.BuildingDependencies, "Wrong state"); @@ -280,7 +280,7 @@ ProjectBuildState buildContext #endregion #region Methods for build error targets ( InProgressBuildState.BuildingErrorClause ) - private void ContinueBuildingErrorClause (ProjectBuildState buildContext) + private void ContinueBuildingErrorClause(ProjectBuildState buildContext) { // Verify that the target is in the right state ErrorUtilities.VerifyThrow(inProgressBuildState == InProgressBuildState.BuildingErrorClause, "Wrong state"); @@ -776,7 +776,7 @@ ProjectBuildState buildContext // A TaskExecutionMode of ExecuteTaskAndGatherOutputs should have its messages logged in the context of the task and therefore should have a valid taskID // A TaskExecutionMode of InferOutputs or Invalid should have its messages logged in the context of the target and therefore should have an invalid taskID - BuildEventContext buildEventContext = PrepareBuildEventContext(executionMode == TaskExecutionMode.ExecuteTaskAndGatherOutputs ? false: true); + BuildEventContext buildEventContext = PrepareBuildEventContext(executionMode == TaskExecutionMode.ExecuteTaskAndGatherOutputs ? false : true); // Create the task execution context int handleId = parentEngine.EngineCallback.CreateTaskContext(parentProject, targetClass, buildContext, @@ -842,9 +842,13 @@ private void ProcessTaskOutputs(TaskExecutionContext executionContext) howToBuild == DependencyAnalysisResult.IncrementalBuild, "We can only see a failure for an execution stage"); if (howToBuild != DependencyAnalysisResult.FullBuild) + { howToBuild = DependencyAnalysisResult.SkipUpToDate; + } else + { exitBatchDueToError = true; + } } } diff --git a/src/Deprecated/Engine/Engine/TaskEngine.cs b/src/Deprecated/Engine/Engine/TaskEngine.cs index 5f0e47a7c76..909c7071472 100644 --- a/src/Deprecated/Engine/Engine/TaskEngine.cs +++ b/src/Deprecated/Engine/Engine/TaskEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -215,7 +215,9 @@ private AppDomain PrepareAppDomain() catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } // Reflection related exception ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskInstantiationFailureError", TaskName, TaskClass.Assembly.ToString(), e.Message); @@ -231,20 +233,20 @@ private AppDomain PrepareAppDomain() } else { - // Our task depend on this name to be precisely that, so if you change it make sure - // you also change the checks in the tasks run in separate AppDomains. Better yet, just don't change it. + // Our task depend on this name to be precisely that, so if you change it make sure + // you also change the checks in the tasks run in separate AppDomains. Better yet, just don't change it. - // Make sure we copy the appdomain configuration and send it to the appdomain we create so that if the creator of the current appdomain - // has done the binding redirection in code, that we will get those settings as well. - AppDomainSetup appDomainInfo = new AppDomainSetup(); + // Make sure we copy the appdomain configuration and send it to the appdomain we create so that if the creator of the current appdomain + // has done the binding redirection in code, that we will get those settings as well. + AppDomainSetup appDomainInfo = new AppDomainSetup(); - // Get the current app domain setup settings - byte[] currentAppdomainBytes = AppDomain.CurrentDomain.SetupInformation.GetConfigurationBytes(); + // Get the current app domain setup settings + byte[] currentAppdomainBytes = AppDomain.CurrentDomain.SetupInformation.GetConfigurationBytes(); - //Apply the appdomain settings to the new appdomain before creating it - appDomainInfo.SetConfigurationBytes(currentAppdomainBytes); - taskAppDomain = AppDomain.CreateDomain("taskAppDomain", null, appDomainInfo); - } + //Apply the appdomain settings to the new appdomain before creating it + appDomainInfo.SetConfigurationBytes(currentAppdomainBytes); + taskAppDomain = AppDomain.CreateDomain("taskAppDomain", null, appDomainInfo); + } } return taskAppDomain; @@ -276,8 +278,8 @@ internal bool ExecuteTask(TaskExecutionMode howToExecuteTask, Lookup lookup) lookupHash = Utilities.CreateTableIfNecessary((Hashtable)null); } - // Loop through each of the batch buckets and execute them one at a time - for (int i=0; i < buckets.Count; i++) + // Loop through each of the batch buckets and execute them one at a time + for (int i = 0; i < buckets.Count; i++) { // Execute the batch bucket, pass in which bucket we are executing so that we know when to get a new taskId for the bucket. taskExecutedSuccessfully = ExecuteBucket(engineProxy, (ItemBucket)buckets[i], i, howToExecuteTask); @@ -365,10 +367,10 @@ private bool ExecuteBucket(EngineProxy engineProxy, ItemBucket bucket, int bucke // If this is the first bucket use the task context originally given to it, for the remaining buckets get a unique id for them if (bucketNumber != 0) { - // Ask the parent engine the next Id which should be used for the taskId. + // Ask the parent engine the next Id which should be used for the taskId. buildEventContext = new BuildEventContext(buildEventContext.NodeId, buildEventContext.TargetId, buildEventContext.ProjectContextId, parentModule.GetNextTaskId()); - // For each batch the engineProxy needs to have the correct buildEventContext as all messages comming from a task will have the buildEventContext of the EngineProxy. + // For each batch the engineProxy needs to have the correct buildEventContext as all messages comming from a task will have the buildEventContext of the EngineProxy. engineProxy.BuildEventContext = buildEventContext; } @@ -454,13 +456,13 @@ private void UpdateContinueOnError(ItemBucket bucket, EngineProxy engineProxy) { continueOnError = ( - // if attribute doesn't exist, default to "false" + // if attribute doesn't exist, default to "false" (continueOnErrorAttribute != null) && - // otherwise, convert its value to a boolean + // otherwise, convert its value to a boolean ConversionUtilities.ConvertStringToBool ( - // expand embedded item vectors after expanding properties and item metadata + // expand embedded item vectors after expanding properties and item metadata bucket.Expander.ExpandAllIntoString(continueOnErrorAttribute) ) ); @@ -496,7 +498,7 @@ private ITask InstantiateTask(AppDomain taskAppDomain) task = (ITask)taskAppDomain.CreateInstanceFromAndUnwrap(TaskClass.Assembly.AssemblyFile, TaskClass.Type.FullName); - // this will force evaluation of the task class type and try to load the task assembly + // this will force evaluation of the task class type and try to load the task assembly Type taskType = task.GetType(); // If the types don't match, we have a problem. It means that our AppDomain was able to load @@ -539,7 +541,9 @@ private ITask InstantiateTask(AppDomain taskAppDomain) catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } // Reflection related exception loggingServices.LogError(buildEventContext, CreateBuildEventFileInfoForTask(), @@ -584,9 +588,9 @@ internal bool InitializeTask(ITask task, ItemBucket bucket, EngineProxy enginePr loggingServices.LogFatalTaskError(buildEventContext, e, - // Display the task's exception stack. - // Log the task line number, whatever the value of ContinueOnError; - // because InitializeTask failure will be a hard error anyway. + // Display the task's exception stack. + // Log the task line number, whatever the value of ContinueOnError; + // because InitializeTask failure will be a hard error anyway. CreateBuildEventFileInfoForTask(), TaskName); @@ -666,7 +670,9 @@ private Dictionary GetNamesOfPropertiesWithRequiredAttribute() catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } // Reflection related exception loggingServices.LogError(buildEventContext, CreateBuildEventFileInfoForTask(), "AttributeTypeLoadError", TaskName, e.Message); @@ -961,7 +967,9 @@ internal bool GatherGeneratedTaskOutputs catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskOutputSpecification.TaskParameterAttribute, "FailedToRetrieveTaskOutputs", TaskName, taskParameterName, e.Message); @@ -1283,7 +1291,9 @@ out bool taskParameterSet catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } // Reflection related exception loggingServices.LogError(buildEventContext, CreateBuildEventFileInfoForTask(), "TaskParametersError", TaskName, e.Message); @@ -1560,7 +1570,9 @@ object parameterValue catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } loggingServices.LogFatalTaskError(buildEventContext, e, CreateBuildEventFileInfoForTask(), diff --git a/src/Deprecated/Engine/Engine/TaskEngineAssemblyResolver.cs b/src/Deprecated/Engine/Engine/TaskEngineAssemblyResolver.cs index 297ecefa3ea..9bae44d4dba 100644 --- a/src/Deprecated/Engine/Engine/TaskEngineAssemblyResolver.cs +++ b/src/Deprecated/Engine/Engine/TaskEngineAssemblyResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -95,11 +95,11 @@ internal Assembly ResolveAssembly(object sender, ResolveEventArgs args) } } // any problems with the task assembly? return null. - catch (FileNotFoundException ) + catch (FileNotFoundException) { return null; } - catch (BadImageFormatException ) + catch (BadImageFormatException) { return null; } diff --git a/src/Deprecated/Engine/Engine/TaskExecutionContext.cs b/src/Deprecated/Engine/Engine/TaskExecutionContext.cs index 9851e8c6df9..d2947869433 100644 --- a/src/Deprecated/Engine/Engine/TaskExecutionContext.cs +++ b/src/Deprecated/Engine/Engine/TaskExecutionContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -25,14 +25,14 @@ internal class TaskExecutionContext : ExecutionContext internal TaskExecutionContext ( Project parentProject, - Target parentTarget, + Target parentTarget, XmlElement taskNode, ProjectBuildState buildContext, int handleId, int nodeIndex, BuildEventContext taskBuildEventContext ) - :base(handleId, nodeIndex, taskBuildEventContext) + : base(handleId, nodeIndex, taskBuildEventContext) { this.parentProject = parentProject; this.parentTarget = parentTarget; @@ -165,8 +165,8 @@ long executionTime /// /// Task outputs /// - bool taskExecutedSuccessfully; - Exception thrownException; + private bool taskExecutedSuccessfully; + private Exception thrownException; #endregion } diff --git a/src/Deprecated/Engine/Engine/TaskExecutionModule.cs b/src/Deprecated/Engine/Engine/TaskExecutionModule.cs index 54915eebb4d..26814250ebe 100644 --- a/src/Deprecated/Engine/Engine/TaskExecutionModule.cs +++ b/src/Deprecated/Engine/Engine/TaskExecutionModule.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -53,7 +53,7 @@ bool profileExecution this.isRunningMultipleNodes = true; this.activeThreadCount = 0; this.overallThreadCount = 0; - this.threadActiveCountEvent = new ManualResetEvent(false); + this.threadActiveCountEvent = new ManualResetEvent(false); this.threadOverallCountEvent = new ManualResetEvent(false); this.lastTaskActivity = 0; @@ -158,7 +158,7 @@ internal long TaskExecutionTime /// This method passes the task outputs to the engine, it is virtual for testing purposes to /// create a mock TEM /// - virtual internal void PostTaskOutputs + internal virtual void PostTaskOutputs ( int handleId, bool taskExecutedSuccessfully, @@ -174,7 +174,7 @@ long executionTime /// This function implements the callback via the IBuildEngine interface /// /// result of call to engine - virtual internal bool BuildProjectFile + internal virtual bool BuildProjectFile ( int handleId, string[] projectFileNames, @@ -182,7 +182,7 @@ virtual internal bool BuildProjectFile IDictionary[] globalPropertiesPerProject, IDictionary[] targetOutputsPerProject, EngineLoggingServices loggingServices, - string [] toolsVersions, + string[] toolsVersions, bool useResultsCache, bool unloadProjectsOnCompletion, BuildEventContext taskContext @@ -290,22 +290,22 @@ BuildEventContext taskContext return overallResult; } - /// - /// Once the buildRequests from the EngineCallback have been created they are sent to this method which will - /// post the build requests to the parent engine and then wait on the results to come back. - /// This method uses either a breadthFirst or depthFirst traversal strategy when sending buildRequests to the parent engine. - /// This method will start in breadthFirst traversal. It will continue to use this strategy until one of two events occur: - /// 1. The parent node sents a message indicating the TEM should switch to depthFirst traversal. - /// 2. The number of buildRequests is larger than the batchRequestSize. - /// In both of these cases the system will go from a breadthFirstTraversal to a depthFirst Traversal. In the second case - /// a message will be sent to the parent engine to switch the system to depthFirst traversal as the system is starting to - /// be overloaded with work. - /// In a depth first strategy the buildRequests will be sent to the parent engine one at a time and waiting for results for - /// each buildRequest sent. In a breadthFirst traversal strategy some number of the buildrequests will be sent to the parent engine - /// in a batch of requests. The system will then wait on the results of ALL the build requests sent before continuing - /// to send more build requests. - /// - private void WaitForBuildResults(int handleId, BuildResult[] buildResultsLocal, BuildRequest[] buildRequests) + /// + /// Once the buildRequests from the EngineCallback have been created they are sent to this method which will + /// post the build requests to the parent engine and then wait on the results to come back. + /// This method uses either a breadthFirst or depthFirst traversal strategy when sending buildRequests to the parent engine. + /// This method will start in breadthFirst traversal. It will continue to use this strategy until one of two events occur: + /// 1. The parent node sents a message indicating the TEM should switch to depthFirst traversal. + /// 2. The number of buildRequests is larger than the batchRequestSize. + /// In both of these cases the system will go from a breadthFirstTraversal to a depthFirst Traversal. In the second case + /// a message will be sent to the parent engine to switch the system to depthFirst traversal as the system is starting to + /// be overloaded with work. + /// In a depth first strategy the buildRequests will be sent to the parent engine one at a time and waiting for results for + /// each buildRequest sent. In a breadthFirst traversal strategy some number of the buildrequests will be sent to the parent engine + /// in a batch of requests. The system will then wait on the results of ALL the build requests sent before continuing + /// to send more build requests. + /// + private void WaitForBuildResults(int handleId, BuildResult[] buildResultsLocal, BuildRequest[] buildRequests) { // If the traversal strategy is breadth first and the number of requests is less than the batchRequestSize // or if there is only 1 build request then send ALL build requests to the parent engine and wait on the results. @@ -392,7 +392,7 @@ private void WaitForBuildResults(int handleId, BuildResult[] buildResultsLocal, /// Call into the engine to figure out the line and column number of the task XML node in the original /// project context /// - virtual internal void GetLineColumnOfXmlNode(int handleId, out int lineNumber, out int columnNumber) + internal virtual void GetLineColumnOfXmlNode(int handleId, out int lineNumber, out int columnNumber) { engineCallback.GetLineColumnOfXmlNode(handleId, out lineNumber, out columnNumber); } @@ -446,7 +446,7 @@ public void ExecuteTask(TaskExecutionState taskState) // If we running in single proc mode, we should execute this task on the current thread if (moduleMode == TaskExecutionModuleMode.SingleProcMode) { - taskState.ExecuteTask(); + taskState.ExecuteTask(); } else { @@ -499,13 +499,13 @@ internal long LastTaskActivity() return DateTime.Now.Ticks; } - internal int[] GetWaitingTaskData(List outstandingRequests) + internal int[] GetWaitingTaskData(List outstandingRequests) { if (moduleMode != TaskExecutionModuleMode.SingleProcMode) { return workerThread.GetWaitingTasksData(outstandingRequests); } - return new int [0]; + return new int[0]; } internal void Shutdown() @@ -572,9 +572,9 @@ internal void WaitForZeroActiveThreadCount() /// internal TaskExecutionModuleMode GetExecutionModuleMode() { - // The Execution module mode is used to determine if they system is running under single proc or multiproc for the purposes of creating a new thread - // to execute tasks on. - return moduleMode; + // The Execution module mode is used to determine if they system is running under single proc or multiproc for the purposes of creating a new thread + // to execute tasks on. + return moduleMode; } /// @@ -591,14 +591,16 @@ internal TaskWorkerThread GetWorkerThread() /// Callback interface to communicate with the engine /// private EngineCallback engineCallback; + /// /// The mode in which the TEM is running /// - TaskExecutionModuleMode moduleMode; + private TaskExecutionModuleMode moduleMode; + /// /// The class used to execute user tasks. /// - TaskWorkerThread workerThread; + private TaskWorkerThread workerThread; // Data shared between all worker threads within the TEM /// diff --git a/src/Deprecated/Engine/Engine/TaskExecutionState.cs b/src/Deprecated/Engine/Engine/TaskExecutionState.cs index 4ed1e6d3854..a1402733cf5 100644 --- a/src/Deprecated/Engine/Engine/TaskExecutionState.cs +++ b/src/Deprecated/Engine/Engine/TaskExecutionState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -120,7 +120,7 @@ internal bool ProfileExecution /// /// The thread procedure executes the tasks and calls callback once it is done /// - virtual internal void ExecuteTask() + internal virtual void ExecuteTask() { bool taskExecutedSuccessfully = true; @@ -169,7 +169,7 @@ virtual internal void ExecuteTask() { taskExecutedSuccessfully = TaskEngineExecuteTask - ( taskEngine, + (taskEngine, TaskExecutionMode.ExecuteTaskAndGatherOutputs, lookupForExecution ); @@ -217,7 +217,7 @@ internal void NotifyOfWait(long waitStartTime) /// engine, Interface or a non sealed TaskEngine these methods can disappear. /// /// - virtual internal bool TaskEngineExecuteTask( + internal virtual bool TaskEngineExecuteTask( TaskEngine taskEngine, TaskExecutionMode howTaskShouldBeExecuted, Lookup lookup @@ -230,7 +230,7 @@ Lookup lookup ); } #endregion - + #endregion #region Fields set by the Engine thread @@ -239,7 +239,7 @@ Lookup lookup private Lookup lookupForInference; private Lookup lookupForExecution; - + private ITaskHost hostObject; private string projectFileOfTaskNode; private string parentProjectFullFileName; diff --git a/src/Deprecated/Engine/Engine/TaskOutput.cs b/src/Deprecated/Engine/Engine/TaskOutput.cs index 472c259da4f..db21abce839 100644 --- a/src/Deprecated/Engine/Engine/TaskOutput.cs +++ b/src/Deprecated/Engine/Engine/TaskOutput.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; @@ -81,7 +81,7 @@ internal TaskOutput(XmlElement node) * if PropertyName is specified, then ItemName cannot be specified * only Condition is truly optional */ - ProjectErrorUtilities.VerifyThrowInvalidProject((this.taskParameterAttribute != null) && (requiredData == 1), + ProjectErrorUtilities.VerifyThrowInvalidProject((this.taskParameterAttribute != null) && (requiredData == 1), node, "InvalidTaskOutputSpecification", taskName); } diff --git a/src/Deprecated/Engine/Engine/TaskRegistry.cs b/src/Deprecated/Engine/Engine/TaskRegistry.cs index b1c83181b4b..ef690909b26 100644 --- a/src/Deprecated/Engine/Engine/TaskRegistry.cs +++ b/src/Deprecated/Engine/Engine/TaskRegistry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -111,13 +111,13 @@ out LoadedType taskClass } Hashtable cachedTaskClasses = exactMatchRequired ? this.cachedTaskClassesWithExactMatch : this.cachedTaskClassesWithFuzzyMatch; - + if (cachedTaskClasses.Contains(taskName)) { // Caller has asked us before for this same task name, and for the same value of "bool exactMatchRequired". // Return whatever the previous result was, even if it was null. Why would the result be different than // it was before? NOTE: Hash tables CAN have "null" as their value, and this still returns "true" for Contains(...). - taskClass = (LoadedType) cachedTaskClasses[taskName]; + taskClass = (LoadedType)cachedTaskClasses[taskName]; } else { @@ -250,11 +250,13 @@ out LoadedType taskClass catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedReflectionException(e)) + { throw; + } ProjectErrorUtilities.VerifyThrowInvalidProject(false, taskNode, "TaskLoadFailure", taskName, assembly.ToString(), e.Message); } - + if (taskClass != null) { return true; @@ -274,10 +276,10 @@ out LoadedType taskClass public void RegisterTask(UsingTask usingTask, Expander expander, EngineLoggingServices loggingServices, BuildEventContext buildEventContext) { if ( - // if the tag doesn't have a condition on it + // if the tag doesn't have a condition on it (usingTask.Condition == null) || - // or if the condition holds + // or if the condition holds Utilities.EvaluateCondition(usingTask.Condition, usingTask.ConditionAttribute, expander, null, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, loggingServices, buildEventContext) ) diff --git a/src/Deprecated/Engine/Engine/TaskWorkerThread.cs b/src/Deprecated/Engine/Engine/TaskWorkerThread.cs index 37efbc5c0c2..893c9b78381 100644 --- a/src/Deprecated/Engine/Engine/TaskWorkerThread.cs +++ b/src/Deprecated/Engine/Engine/TaskWorkerThread.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -14,7 +14,7 @@ namespace Microsoft.Build.BuildEngine /// internal class TaskWorkerThread { - enum NodeLoopExecutionMode + private enum NodeLoopExecutionMode { /// /// This is a mode of a thread that is not executing a task but is responsible for picking up @@ -254,7 +254,7 @@ private bool WaitAnyFast(NodeLoopExecutionMode executionMode, out int index) /// /// Current execution mode /// Array of handles to wait on - private WaitHandle [] GetHandlesArray( NodeLoopExecutionMode executionMode ) + private WaitHandle[] GetHandlesArray(NodeLoopExecutionMode executionMode) { WaitHandle[] waitHandles = null; @@ -307,7 +307,7 @@ private void NodeActionLoop ( NodeLoopExecutionMode executionMode, int handleId, - BuildResult [] buildResults + BuildResult[] buildResults ) { // Create an array of event to the node thread responds @@ -350,7 +350,7 @@ BuildResult [] buildResults continueExecution = false; } // New work item has appeared in the queue - else if (eventType == 1 && executionMode != NodeLoopExecutionMode.WaitingPassiveThread ) + else if (eventType == 1 && executionMode != NodeLoopExecutionMode.WaitingPassiveThread) { ErrorUtilities.VerifyThrow( executionMode == NodeLoopExecutionMode.WaitingActiveThread || @@ -499,7 +499,7 @@ internal void WaitForResults ( int handleId, BuildResult[] buildResults, - BuildRequest [] buildRequests + BuildRequest[] buildRequests ) { TaskWorkerThread workerThread = GetWorkerThreadForHandleId(handleId); @@ -519,7 +519,7 @@ BuildRequest [] buildRequests } - internal int [] GetWaitingTasksData(List outstandingRequests) + internal int[] GetWaitingTasksData(List outstandingRequests) { int[] waitingTasksArray; lock (waitingTasks) @@ -548,7 +548,7 @@ internal int [] GetWaitingTasksData(List outstandingRequests) return waitingTasksArray; } - internal void PostWorkItem( TaskExecutionState workItem) + internal void PostWorkItem(TaskExecutionState workItem) { lock (workItemQueue) { @@ -557,7 +557,7 @@ internal void PostWorkItem( TaskExecutionState workItem) } } - internal void PostBuildResult( BuildResult buildResult) + internal void PostBuildResult(BuildResult buildResult) { TaskWorkerThread workerThread = GetWorkerThreadForHandleId(buildResult.HandleId); diff --git a/src/Deprecated/Engine/Engine/Toolset.cs b/src/Deprecated/Engine/Engine/Toolset.cs index 6e96c01f231..cc3bacd103e 100644 --- a/src/Deprecated/Engine/Engine/Toolset.cs +++ b/src/Deprecated/Engine/Engine/Toolset.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -80,7 +80,7 @@ private set // they don't end up with a double-backslash in the middle. (It doesn't // technically hurt anything, but it doesn't look nice.) string toolsPathToUse = value; - + if (FileUtilities.EndsWithSlash(toolsPathToUse)) { string rootPath = Path.GetPathRoot(Path.GetFullPath(toolsPathToUse)); diff --git a/src/Deprecated/Engine/Engine/ToolsetCollection.cs b/src/Deprecated/Engine/Engine/ToolsetCollection.cs index f269f8f34a0..b58c946ba43 100644 --- a/src/Deprecated/Engine/Engine/ToolsetCollection.cs +++ b/src/Deprecated/Engine/Engine/ToolsetCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -129,7 +129,7 @@ public void Add(Toolset item) } else { - toolsetMap.Add(item.ToolsVersion,item); + toolsetMap.Add(item.ToolsVersion, item); } // The parent engine needs to handle this as well diff --git a/src/Deprecated/Engine/Engine/ToolsetConfigurationReader.cs b/src/Deprecated/Engine/Engine/ToolsetConfigurationReader.cs index a1d7e31e005..1facf2df351 100644 --- a/src/Deprecated/Engine/Engine/ToolsetConfigurationReader.cs +++ b/src/Deprecated/Engine/Engine/ToolsetConfigurationReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -104,11 +104,11 @@ protected override IEnumerable GetPropertyDefinitions(string { InvalidToolsetDefinitionException.Throw("InvalidToolsetValueInConfigFileValue", location); } - + yield return new PropertyDefinition(propertyElement.Name, propertyElement.Value, location); } } - + /// /// Reads the application configuration file. /// NOTE: this is abstracted into a method to support unit testing GetToolsetDataFromConfiguration(). @@ -156,8 +156,8 @@ private ToolsetConfigurationSection ConfigurationSection { string location = ResourceUtilities.FormatResourceString ( - "ConfigFileLocation", - ex.Filename, + "ConfigFileLocation", + ex.Filename, ex.Line ); @@ -294,7 +294,7 @@ private void UpdateToolsVersionMap(ConfigurationElement element) throw new ConfigurationErrorsException(message, element.ElementInformation.Source, element.ElementInformation.LineNumber); } - + previouslySeenToolsVersions.Add(toolsVersion, string.Empty); } @@ -410,7 +410,7 @@ internal sealed class PropertyElementCollection : ConfigurationElementCollection /// won't perform this check without respect for case. /// private Dictionary previouslySeenPropertyNames = new Dictionary(StringComparer.OrdinalIgnoreCase); - + /// /// Creates a new element /// @@ -462,7 +462,7 @@ private void UpdatePropertyNameMap(ConfigurationElement element) previouslySeenPropertyNames.Add(propertyName, string.Empty); } - + /// /// Gets the key for the element /// diff --git a/src/Deprecated/Engine/Engine/ToolsetReader.cs b/src/Deprecated/Engine/Engine/ToolsetReader.cs index c952cf4bb5c..f0ab606e9be 100644 --- a/src/Deprecated/Engine/Engine/ToolsetReader.cs +++ b/src/Deprecated/Engine/Engine/ToolsetReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -222,7 +222,9 @@ private static bool ConfigurationFileMayHaveToolsets() catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } // There was some problem reading the config file: let the configuration reader // encounter it @@ -464,7 +466,9 @@ private string ExpandRelativePathsRelativeToExeLocation(string path) catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } // This means that the path looked relative, but was an invalid path. In this case, we'll // just not expand it, and carry on - to be consistent with what happens when there's a // non-relative bin path with invalid characters. The problem will be detected later when diff --git a/src/Deprecated/Engine/Engine/ToolsetRegistryReader.cs b/src/Deprecated/Engine/Engine/ToolsetRegistryReader.cs index 4935eaea24e..999d9f0eac7 100644 --- a/src/Deprecated/Engine/Engine/ToolsetRegistryReader.cs +++ b/src/Deprecated/Engine/Engine/ToolsetRegistryReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using error = Microsoft.Build.BuildEngine.Shared.ErrorUtilities; @@ -27,7 +27,7 @@ internal class ToolsetRegistryReader : ToolsetReader { // Registry location for storing tools version dependent data for msbuild private const string msbuildRegistryPath = @"SOFTWARE\Microsoft\MSBuild"; - + // Cached registry wrapper at root of the msbuild entries private RegistryKeyWrapper msbuildRegistryWrapper; @@ -35,7 +35,7 @@ internal class ToolsetRegistryReader : ToolsetReader /// Default constructor /// internal ToolsetRegistryReader() - : this (new RegistryKeyWrapper(msbuildRegistryPath)) + : this(new RegistryKeyWrapper(msbuildRegistryPath)) { } @@ -46,7 +46,7 @@ internal ToolsetRegistryReader() internal ToolsetRegistryReader(RegistryKeyWrapper msbuildRegistryWrapper) { error.VerifyThrowArgumentNull(msbuildRegistryWrapper, nameof(msbuildRegistryWrapper)); - + this.msbuildRegistryWrapper = msbuildRegistryWrapper; } @@ -105,7 +105,7 @@ protected override string DefaultToolsVersion protected override IEnumerable GetPropertyDefinitions(string toolsVersion) { RegistryKeyWrapper toolsVersionWrapper = null; - + try { toolsVersionWrapper = msbuildRegistryWrapper.OpenSubKey("ToolsVersions\\" + toolsVersion); @@ -123,7 +123,7 @@ protected override IEnumerable GetPropertyDefinitions(string { InvalidToolsetDefinitionException.Throw("PropertyNameInRegistryHasZeroLength", toolsVersionWrapper.Name); } - + try { propertyValue = GetValue(toolsVersionWrapper, propertyName); @@ -136,7 +136,7 @@ protected override IEnumerable GetPropertyDefinitions(string yield return new PropertyDefinition(propertyName, propertyValue, toolsVersionWrapper.Name + "@" + propertyName); } } - + /// /// Reads a string value from the specified registry key /// diff --git a/src/Deprecated/Engine/Engine/ToolsetState.cs b/src/Deprecated/Engine/Engine/ToolsetState.cs index 15436e47e88..dc3cd45ff6f 100644 --- a/src/Deprecated/Engine/Engine/ToolsetState.cs +++ b/src/Deprecated/Engine/Engine/ToolsetState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -102,7 +102,7 @@ internal string ToolsPath /// internal BuildPropertyGroup BuildProperties { - get + get { return this.toolset.BuildProperties; } @@ -188,7 +188,7 @@ private void RegisterDefaultTasks(BuildEventContext buildEventContext) if (defaultTasksFiles.Length == 0) { - loggingServices.LogWarning( buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), + loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), "DefaultTasksFileLoadFailureWarning", defaultTasksFilePattern, toolset.ToolsPath, String.Empty); } @@ -196,7 +196,7 @@ private void RegisterDefaultTasks(BuildEventContext buildEventContext) // handle security problems when finding the default tasks files catch (UnauthorizedAccessException e) { - loggingServices.LogWarning( buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), + loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), "DefaultTasksFileLoadFailureWarning", defaultTasksFilePattern, toolset.ToolsPath, e.Message); } @@ -204,9 +204,11 @@ private void RegisterDefaultTasks(BuildEventContext buildEventContext) catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } - loggingServices.LogWarning( buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), + loggingServices.LogWarning(buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty), "DefaultTasksFileLoadFailureWarning", defaultTasksFilePattern, toolset.ToolsPath, e.Message); } @@ -235,7 +237,7 @@ private void RegisterDefaultTasks(BuildEventContext buildEventContext) // the tag can only the XML namespace -- no other attributes foreach (XmlAttribute projectAttribute in topLevelNode.Attributes) { - ProjectXmlUtilities.VerifyThrowProjectInvalidAttribute(projectAttribute.Name == XMakeAttributes.xmlns, projectAttribute); + ProjectXmlUtilities.VerifyThrowProjectInvalidAttribute(projectAttribute.Name == XMakeAttributes.xmlns, projectAttribute); } // look at all the child tags of the root tag we found diff --git a/src/Deprecated/Engine/Engine/UsingTask.cs b/src/Deprecated/Engine/Engine/UsingTask.cs index 84dfde06690..fbc96584ba4 100644 --- a/src/Deprecated/Engine/Engine/UsingTask.cs +++ b/src/Deprecated/Engine/Engine/UsingTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -81,7 +81,7 @@ public string AssemblyFile /// internal XmlAttribute AssemblyFileAttribute { - get { return this.assemblyFileAttribute; } + get { return this.assemblyFileAttribute; } } private XmlAttribute conditionAttribute = null; @@ -174,12 +174,12 @@ internal UsingTask(XmlElement usingTaskNode, bool isImported) case XMakeAttributes.assemblyFile: assemblyFileAttribute = usingTaskAttribute; break; - + // ignore any RequiredRuntime XML attribute // (we'll make this actually do something when we run on a CLR other than v2.0) case XMakeAttributes.requiredRuntime: // Do nothing - break; + break; // get the condition, if any case XMakeAttributes.condition: @@ -211,7 +211,7 @@ internal UsingTask(XmlElement usingTaskNode, bool isImported) break; default: - ProjectXmlUtilities.ThrowProjectInvalidAttribute(usingTaskAttribute); + ProjectXmlUtilities.ThrowProjectInvalidAttribute(usingTaskAttribute); break; } } diff --git a/src/Deprecated/Engine/Engine/UsingTaskCollection.cs b/src/Deprecated/Engine/Engine/UsingTaskCollection.cs index a19c668c3b8..72cd53c4f73 100644 --- a/src/Deprecated/Engine/Engine/UsingTaskCollection.cs +++ b/src/Deprecated/Engine/Engine/UsingTaskCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -68,10 +68,10 @@ public void CopyTo(Array array, int index) /// LukaszG public int Count { - get + get { ErrorUtilities.VerifyThrow(this.usingTasks != null, "UsingTaskCollection's ArrayList not initialized!"); - return this.usingTasks.Count; + return this.usingTasks.Count; } } @@ -81,10 +81,10 @@ public int Count /// LukaszG public bool IsSynchronized { - get + get { ErrorUtilities.VerifyThrow(this.usingTasks != null, "UsingTaskCollection's ArrayList not initialized!"); - return this.usingTasks.IsSynchronized; + return this.usingTasks.IsSynchronized; } } @@ -137,7 +137,7 @@ internal UsingTask this[int index] get { ErrorUtilities.VerifyThrow(this.usingTasks != null, "UsingTaskCollection's ArrayList not initialized!"); - return (UsingTask) this.usingTasks[index]; + return (UsingTask)this.usingTasks[index]; } } diff --git a/src/Deprecated/Engine/Engine/Utilities.cs b/src/Deprecated/Engine/Engine/Utilities.cs index 6f7cb535570..7cbfce7b91f 100644 --- a/src/Deprecated/Engine/Engine/Utilities.cs +++ b/src/Deprecated/Engine/Engine/Utilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -17,9 +17,9 @@ namespace Microsoft.Build.BuildEngine /// This class contains utility methods for the MSBuild engine. /// /// RGoel - static public class Utilities + public static class Utilities { - private readonly static Regex singlePropertyRegex = new Regex(@"^\$\(([^\$\(\)]*)\)$"); + private static readonly Regex singlePropertyRegex = new Regex(@"^\$\(([^\$\(\)]*)\)$"); /// /// Update our table which keeps track of all the properties that are referenced @@ -55,10 +55,10 @@ string rightValueExpanded // The fully expanded value on the right // and we don't touch the table. // Split up the leftValue into pieces based on the vertical bar character. - string[] leftValuePieces = leftValue.Split(new char[]{'|'}); + string[] leftValuePieces = leftValue.Split(new char[] { '|' }); // Loop through each of the pieces. - for (int i = 0 ; i < leftValuePieces.Length ; i++) + for (int i = 0; i < leftValuePieces.Length; i++) { Match singlePropertyMatch = singlePropertyRegex.Match(leftValuePieces[i]); @@ -91,8 +91,8 @@ string rightValueExpanded // The fully expanded value on the right string propertyName = singlePropertyMatch.Groups[1].ToString(); // Get the string collection for this property name, if one already exists. - StringCollection conditionedPropertyValues = - (StringCollection) conditionedPropertiesTable[propertyName]; + StringCollection conditionedPropertyValues = + (StringCollection)conditionedPropertiesTable[propertyName]; // If this property is not already represented in the table, add a new entry // for it. @@ -124,10 +124,10 @@ string rightValueExpanded // The fully expanded value on the right */ internal static void GatherReferencedPropertyNames ( - string condition, // Can be null - XmlAttribute conditionAttribute, // XML attribute on which the condition is evaluated - Expander expander, // The set of properties to use for expansion - Hashtable conditionedPropertiesTable // Can be null + string condition, // Can be null + XmlAttribute conditionAttribute, // XML attribute on which the condition is evaluated + Expander expander, // The set of properties to use for expansion + Hashtable conditionedPropertiesTable // Can be null ) { EvaluateCondition(condition, conditionAttribute, expander, conditionedPropertiesTable, ParserOptions.AllowProperties | ParserOptions.AllowItemLists, null, null); @@ -137,9 +137,9 @@ Hashtable conditionedPropertiesTable // Can be null // and parser options private static volatile Hashtable[] cachedExpressionTrees = new Hashtable[8 /* == ParserOptions.AllowAll*/] { - new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), - new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), - new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), + new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), + new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), + new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase), new Hashtable(StringComparer.OrdinalIgnoreCase) }; @@ -241,7 +241,7 @@ BuildEventContext buildEventContext Hashtable cachedExpressionTreesForCurrentOptions = cachedExpressionTrees[(int)itemListOptions]; // Try and see if we have an expression tree for this condition already - GenericExpressionNode parsedExpression = (GenericExpressionNode) cachedExpressionTreesForCurrentOptions[condition]; + GenericExpressionNode parsedExpression = (GenericExpressionNode)cachedExpressionTreesForCurrentOptions[condition]; if (parsedExpression == null) { @@ -303,7 +303,7 @@ internal static void SetXmlNodeInnerContents(XmlNode node, string s) // XML. Eat the exception and fall through below ... } } - + // The value does not contain valid XML markup. Store it as text, so it gets // escaped properly. node.InnerText = s; diff --git a/src/Deprecated/Engine/Engine/XmlSearcher.cs b/src/Deprecated/Engine/Engine/XmlSearcher.cs index 94cb2516e44..3016ece3da9 100644 --- a/src/Deprecated/Engine/Engine/XmlSearcher.cs +++ b/src/Deprecated/Engine/Engine/XmlSearcher.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -67,7 +67,7 @@ out int foundColumnNumber // Now that we know what element/attribute number we're searching for, find // it in the Xml document on disk, and grab the line/column number. - return GetLineColumnByNodeNumber(fileName, elementNumber, attributeNumber, + return GetLineColumnByNodeNumber(fileName, elementNumber, attributeNumber, out foundLineNumber, out foundColumnNumber); } @@ -116,7 +116,7 @@ out int attributeNumber } else if (xmlNodeToFind.NodeType == XmlNodeType.Attribute) { - elementToFind = ((XmlAttribute) xmlNodeToFind).OwnerElement; + elementToFind = ((XmlAttribute)xmlNodeToFind).OwnerElement; ErrorUtilities.VerifyThrow(elementToFind != null, "How can an xml attribute not have a parent?"); } else @@ -275,7 +275,7 @@ out int foundColumnNumber foundLineNumber = reader.LineNumber; foundColumnNumber = reader.LinePosition; - if (reader.NodeType == XmlNodeType.Element) + if (reader.NodeType == XmlNodeType.Element) { // Do a minus-one here, because the XmlTextReader points us at the first // letter of the tag name, whereas we would prefer to point at the opening @@ -284,7 +284,7 @@ out int foundColumnNumber foundColumnNumber--; } } - else if (reader.MoveToFirstAttribute()) + else if (reader.MoveToFirstAttribute()) { // Caller wants a particular attribute within the element, // and the element does have 1 or more attributes. So let's @@ -292,7 +292,7 @@ out int foundColumnNumber int currentXmlAttributeNumber = 0; // Loop through all the XML attributes on the current element. - do + do { // Bump the current attribute number and check to see if this // is the one. @@ -313,7 +313,7 @@ out int foundColumnNumber } } } - catch (XmlException) + catch (XmlException) { // Eat the exception. If anything fails, we simply don't surface the line/column number. } diff --git a/src/Deprecated/Engine/Errors/InternalLoggerException.cs b/src/Deprecated/Engine/Errors/InternalLoggerException.cs index 3926d8504db..c2a314bd6c5 100644 --- a/src/Deprecated/Engine/Errors/InternalLoggerException.cs +++ b/src/Deprecated/Engine/Errors/InternalLoggerException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -113,7 +113,7 @@ bool initializationException private InternalLoggerException(SerializationInfo info, StreamingContext context) : base(info, context) { - this.e = (BuildEventArgs) info.GetValue("e", typeof(BuildEventArgs)); + this.e = (BuildEventArgs)info.GetValue("e", typeof(BuildEventArgs)); this.errorCode = info.GetString("errorCode"); this.helpKeyword = info.GetString("helpKeyword"); this.initializationException = info.GetBoolean("initializationException"); @@ -126,7 +126,7 @@ private InternalLoggerException(SerializationInfo info, StreamingContext context /// /// [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); diff --git a/src/Deprecated/Engine/Errors/InvalidProjectFileException.cs b/src/Deprecated/Engine/Errors/InvalidProjectFileException.cs index 2f08d3348e9..2311e582a9c 100644 --- a/src/Deprecated/Engine/Errors/InvalidProjectFileException.cs +++ b/src/Deprecated/Engine/Errors/InvalidProjectFileException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -97,7 +97,7 @@ private InvalidProjectFileException(SerializationInfo info, StreamingContext con /// /// [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); @@ -133,7 +133,7 @@ public InvalidProjectFileException string errorSubcategory, string errorCode, string helpKeyword - ) : + ) : base(message) { ErrorUtilities.VerifyThrowArgumentLength(message, nameof(message)); @@ -174,7 +174,7 @@ public InvalidProjectFileException string errorSubcategory, string errorCode, string helpKeyword - ) : + ) : base(message) { ErrorUtilities.VerifyThrowArgumentNull(projectFile, nameof(projectFile)); diff --git a/src/Deprecated/Engine/Errors/InvalidToolsetDefinitionException.cs b/src/Deprecated/Engine/Errors/InvalidToolsetDefinitionException.cs index 4c458782833..743cea4b59c 100644 --- a/src/Deprecated/Engine/Errors/InvalidToolsetDefinitionException.cs +++ b/src/Deprecated/Engine/Errors/InvalidToolsetDefinitionException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -90,7 +90,7 @@ public InvalidToolsetDefinitionException(string message, string errorCode, Excep /// /// [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info)); @@ -154,7 +154,7 @@ params object[] args string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, resourceName, args); - + throw new InvalidToolsetDefinitionException(message, errorCode, innerException); } diff --git a/src/Deprecated/Engine/Errors/RegistryException.cs b/src/Deprecated/Engine/Errors/RegistryException.cs index 822064f0f61..a4c07c216cc 100644 --- a/src/Deprecated/Engine/Errors/RegistryException.cs +++ b/src/Deprecated/Engine/Errors/RegistryException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -51,16 +51,16 @@ public RegistryException(string message, string source) base.Source = source; } - /// + /// /// Since this class implements Iserializable this constructor is required to be implemented. /// - protected RegistryException(SerializationInfo info, StreamingContext context) : base(info, context) + protected RegistryException(SerializationInfo info, StreamingContext context) : base(info, context) { // We don't have any reason at the moment to do any custom serizlization or deserialization, this methods was added // to conform to the implementation of the standard constructors for ISerializable classes - } - - /// + } + + /// /// Constructor that takes a string description of the registry /// key or value causing the error. /// diff --git a/src/Deprecated/Engine/Errors/RemoteErrorException.cs b/src/Deprecated/Engine/Errors/RemoteErrorException.cs index 00839224075..d6061669ff9 100644 --- a/src/Deprecated/Engine/Errors/RemoteErrorException.cs +++ b/src/Deprecated/Engine/Errors/RemoteErrorException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -46,7 +46,7 @@ private RemoteErrorException(SerializationInfo info, StreamingContext context) /// /// [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); diff --git a/src/Deprecated/Engine/Introspector/Introspector.cs b/src/Deprecated/Engine/Introspector/Introspector.cs index 203896320f5..0ed9599f8e5 100644 --- a/src/Deprecated/Engine/Introspector/Introspector.cs +++ b/src/Deprecated/Engine/Introspector/Introspector.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -15,10 +15,10 @@ internal class Introspector #region Constructors internal Introspector(Engine parentEngine, ProjectManager projectManager, NodeManager nodeManager) { - this.parentEngine = parentEngine; + this.parentEngine = parentEngine; this.projectManager = projectManager; - this.nodeManager = nodeManager; - this.ignoreTimeout = 0; + this.nodeManager = nodeManager; + this.ignoreTimeout = 0; } #endregion @@ -31,7 +31,7 @@ internal Introspector(Engine parentEngine, ProjectManager projectManager, NodeMa /// to break it. If no cause for deadlock can be determined the system is shutdown. /// /// New inactivity timeout - internal int DetectDeadlock( int queueCounts, long lastLoopActivity, int currentTimeout) + internal int DetectDeadlock(int queueCounts, long lastLoopActivity, int currentTimeout) { // Don't try to detect deadlock in single threaded mode or on a child node if (parentEngine.Router.ChildMode || parentEngine.Router.SingleThreadedMode) @@ -161,7 +161,7 @@ internal int DetectDeadlock( int queueCounts, long lastLoopActivity, int current // There was some activity between previous and current status checks on the local node if (localStatus.LastLoopActivity != previousLocalStatus.LastLoopActivity || - localStatus.LastTaskActivity != previousLocalStatus.LastTaskActivity ) + localStatus.LastTaskActivity != previousLocalStatus.LastTaskActivity) { previousStatus = nodeStatus; previousLocalStatus = localStatus; @@ -214,7 +214,7 @@ private void AddTargetStatesToCycleDetector(NodeStatus[] nodeStatus, TargetCycle { for (int i = 0; i < nodeStatus.Length; i++) { - cycleDetector.AddTargetsToGraph(nodeStatus[i].StateOfInProgressTargets); + cycleDetector.AddTargetsToGraph(nodeStatus[i].StateOfInProgressTargets); } } @@ -256,7 +256,7 @@ private void GatherNodeInformationForShutdown(NodeStatus[] nodeStatus, NodeStatu /// internal void SystemShutdown() { - ErrorUtilities.LaunchMsBuildDebuggerOnFatalError(); + ErrorUtilities.LaunchMsBuildDebuggerOnFatalError(); nodeManager.ShutdownNodes(Node.NodeShutdownLevel.ErrorShutdown); } @@ -272,12 +272,12 @@ internal void SystemShutdown() /// internal void BreakCycle(TargetInProgessState child, TargetInProgessState parent) { - ErrorUtilities.VerifyThrow( child.TargetId.nodeId == parentEngine.NodeId, + ErrorUtilities.VerifyThrow(child.TargetId.nodeId == parentEngine.NodeId, "Expect the child target to be on the node"); Project parentProject = projectManager.GetProject(child.TargetId.projectId); - ErrorUtilities.VerifyThrow(parentProject != null, + ErrorUtilities.VerifyThrow(parentProject != null, "Expect the parent project to be on the node"); Target childTarget = parentProject.Targets[child.TargetId.name]; @@ -345,7 +345,7 @@ private int calculateNewLoopTimeout(int currentTimeout) { if (currentTimeout < maxLoopTimeout) { - currentTimeout = 2*currentTimeout; + currentTimeout = 2 * currentTimeout; } return currentTimeout; diff --git a/src/Deprecated/Engine/Introspector/NodeStatus.cs b/src/Deprecated/Engine/Introspector/NodeStatus.cs index f615afc8dc9..659b759ec7f 100644 --- a/src/Deprecated/Engine/Introspector/NodeStatus.cs +++ b/src/Deprecated/Engine/Introspector/NodeStatus.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -153,7 +153,7 @@ internal bool HasExited return this.hasExited; } } - + /// /// The token of the request to which this is a response (-1 if status is unrequested) /// @@ -179,7 +179,7 @@ internal int QueueDepth /// /// The state of the targets which are in progress on the node /// - internal TargetInProgessState [] StateOfInProgressTargets + internal TargetInProgessState[] StateOfInProgressTargets { get { @@ -224,10 +224,10 @@ internal bool TraversalType #region Data private long statusTimeStamp; // the timestamp indicating when this status structure was filled out - private int requestId; // the token of the request to which this is a response (-1 if status is unrequested) + private int requestId; // the token of the request to which this is a response (-1 if status is unrequested) private bool isActive; // is the node active private bool isLaunchInProgress; // is the node in the process of being launched - private int queueDepth; // the number of build request in the node's queue + private int queueDepth; // the number of build request in the node's queue private long lastTaskActivityTimeStamp; // the time stamp of the last task activity private long lastEngineActivityTimeStamp; // the time stamp of the last engine activity private TargetInProgessState[] stateOfInProgressTargets; @@ -266,8 +266,8 @@ internal void WriteToStream(BinaryWriter writer) } else { - writer.Write((byte)1); - stateOfInProgressTargets[i].WriteToStream(writer); + writer.Write((byte)1); + stateOfInProgressTargets[i].WriteToStream(writer); } } } diff --git a/src/Deprecated/Engine/Introspector/TargetCycleDetector.cs b/src/Deprecated/Engine/Introspector/TargetCycleDetector.cs index 90d499820e2..b9a6e128815 100644 --- a/src/Deprecated/Engine/Introspector/TargetCycleDetector.cs +++ b/src/Deprecated/Engine/Introspector/TargetCycleDetector.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -32,7 +32,7 @@ internal TargetCycleDetector(EngineLoggingServices engineLoggingService, EngineC dependencyGraph = new Hashtable(); outstandingExternalRequests = new Hashtable(); cycleParent = null; - cycleChild = null; + cycleChild = null; } #endregion @@ -179,7 +179,7 @@ private void LinkCrossNodeBuildRequests() TargetInProgessState.TargetIdWrapper[] parentsForBuildRequests = new TargetInProgessState.TargetIdWrapper[node.targetState.ParentBuildRequests.Count]; - for (int j = 0; j < node.targetState.ParentBuildRequests.Count; j++ ) + for (int j = 0; j < node.targetState.ParentBuildRequests.Count; j++) { BuildRequest buildRequest = node.targetState.ParentBuildRequests[j]; int nodeIndex = buildRequest.NodeIndex; @@ -210,9 +210,9 @@ private void LinkCrossNodeBuildRequests() if (nextExecutionContext is RequestRoutingContext) { - nodeIndex = nextExecutionContext.NodeIndex; + nodeIndex = nextExecutionContext.NodeIndex; handleId = routingContext.ParentHandleId; - requestId = routingContext.ParentRequestId; + requestId = routingContext.ParentRequestId; } } else @@ -293,10 +293,10 @@ private void FindBackEdges(GraphNode node) for (int i = 0; i < node.children.Count; i++) { // Check for a back edge - if (node.children[i].traversalIndex > node.traversalIndex ) + if (node.children[i].traversalIndex > node.traversalIndex) { cycleParent = node.targetState; - cycleChild = node.children[i].targetState; + cycleChild = node.children[i].targetState; DumpCycleSequence(node.children[i], node); break; } @@ -304,7 +304,7 @@ private void FindBackEdges(GraphNode node) if (node.children[i].targetState.TargetId == node.targetState.TargetId) { cycleParent = node.targetState; - cycleChild = node.targetState; + cycleChild = node.targetState; break; } } @@ -327,7 +327,7 @@ private void DumpCycleSequence(GraphNode parent, GraphNode child) private bool DumpCycleSequenceOutput(GraphNode parent, GraphNode child, BuildEventContext buildEventContext) { - if (parent == child ) + if (parent == child) { engineLoggingService.LogComment(buildEventContext, "cycleTraceTitle"); engineLoggingService.LogComment @@ -408,7 +408,7 @@ internal GraphNode(TargetInProgessState targetState) internal bool isRoot; internal int traversalIndex; - internal const int InvalidIndex = -1; + internal const int InvalidIndex = -1; internal const int InProgressIndex = -2; #endregion } diff --git a/src/Deprecated/Engine/Introspector/TargetInProgressState.cs b/src/Deprecated/Engine/Introspector/TargetInProgressState.cs index 114ac3532b9..922347d5963 100644 --- a/src/Deprecated/Engine/Introspector/TargetInProgressState.cs +++ b/src/Deprecated/Engine/Introspector/TargetInProgressState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -24,10 +24,10 @@ internal TargetInProgessState() internal TargetInProgessState ( EngineCallback engineCallback, - Target target, + Target target, List waitingBuildStates, ProjectBuildState initiatingRequest, - BuildRequest [] outstandingBuildRequests, + BuildRequest[] outstandingBuildRequests, string projectName ) { @@ -172,7 +172,7 @@ internal TargetIdWrapper FindParentTarget ( EngineCallback engineCallback, ProjectBuildState buildContext, - Target target, + Target target, out BuildRequest parentRequest ) { @@ -297,21 +297,27 @@ ProjectBuildState projectBuildState #region Data // Unique identifier for the target - TargetIdWrapper targetId; + private TargetIdWrapper targetId; + // List of targets waiting on the current target - List parentTargets; + private List parentTargets; + // List of build requests waiting on the current target - List parentBuildRequests; + private List parentBuildRequests; + // List of the build requests the target is waiting on - BuildRequest[] outstandingBuildRequests; + private BuildRequest[] outstandingBuildRequests; + // Mapping between list of build requests waiting on the current target and targets // from which these build reuquests originated - TargetIdWrapper [] parentTargetsForBuildRequests; + private TargetIdWrapper[] parentTargetsForBuildRequests; + // Name of the project containing the target (only used for logging) - string projectName; + private string projectName; + // Set to true if the target had a been requested by host (direct requests from host only occur on // parent node) - bool requestedByHost; + private bool requestedByHost; #endregion #region CustomSerializationToStream diff --git a/src/Deprecated/Engine/Items/BuildItem.cs b/src/Deprecated/Engine/Items/BuildItem.cs index b6f4df29c36..9bc731add47 100644 --- a/src/Deprecated/Engine/Items/BuildItem.cs +++ b/src/Deprecated/Engine/Items/BuildItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -496,7 +496,7 @@ internal BuildItem(XmlElement itemElement, bool importedFromAnotherProject, bool /// This constructor creates a new virtual (non-persisted) item based /// on a ITaskItem object that was emitted by a task. /// - public BuildItem(string itemName, ITaskItem taskItem) + public BuildItem(string itemName, ITaskItem taskItem) { ErrorUtilities.VerifyThrowArgumentNull(taskItem, nameof(taskItem)); @@ -519,7 +519,7 @@ public BuildItem(string itemName, ITaskItem taskItem) rawSourceTable.Keys.CopyTo(keys, 0); foreach (string singleMetadataName in keys) { - string singleMetadataValue = (string) rawSourceTable[singleMetadataName]; + string singleMetadataValue = (string)rawSourceTable[singleMetadataName]; rawSourceTable[singleMetadataName] = EscapingUtilities.Escape(singleMetadataValue); } @@ -727,7 +727,7 @@ public int CustomMetadataCount return GetCustomMetadataCount(); } } - + /// /// Read-only accessor for accessing the XML attribute for "Include". Callers should /// never try and modify this. Go through this.Include to change the include spec. @@ -829,7 +829,7 @@ public string FinalItemSpec { get { return EscapingUtilities.UnescapeAll(FinalItemSpecEscaped); } } - + /// /// Read-only accessor for the piece of the item's Include that resulted in /// this item, with properties expanded. @@ -851,7 +851,7 @@ internal BuildItemGroup ParentPersistedItemGroup set { - ErrorUtilities.VerifyThrow( ((value == null) && (this.parentPersistedItemGroup != null)) || ((value != null) && (this.parentPersistedItemGroup == null)), + ErrorUtilities.VerifyThrow(((value == null) && (this.parentPersistedItemGroup != null)) || ((value != null) && (this.parentPersistedItemGroup == null)), "Either new parent cannot be assigned because we already have a parent, or old parent cannot be removed because none exists."); this.parentPersistedItemGroup = value; @@ -875,7 +875,7 @@ internal BuildItem ParentPersistedItem set { - ErrorUtilities.VerifyThrow( ((value == null) && (this.parentPersistedItem != null)) || ((value != null) && (this.parentPersistedItem == null)), + ErrorUtilities.VerifyThrow(((value == null) && (this.parentPersistedItem != null)) || ((value != null) && (this.parentPersistedItem == null)), "Either new parent cannot be assigned because we already have a parent, or old parent cannot be removed because none exists."); this.parentPersistedItem = value; @@ -894,7 +894,7 @@ internal BuildItemGroup ChildItems { if (this.childItems == null) { - this.childItems = new BuildItemGroup (); + this.childItems = new BuildItemGroup(); } return this.childItems; @@ -943,7 +943,7 @@ internal bool IsBackedUp /// 1) this method should return a clone of the metadata /// 2) writing to this dictionary should not be reflected in the underlying item. /// - internal IDictionary CloneCustomMetadata() + internal IDictionary CloneCustomMetadata() { IDictionary result = (IDictionary)this.evaluatedCustomMetadata.Clone(); return MergeDefaultMetadata(result); @@ -1061,11 +1061,11 @@ internal string ExtractRecursivePortionOfFinalItemSpecDirectory() /// Evaluates the item and returns a virtual group containing any resulting items. /// This allows an item to be evaluated without it belonging to an item group. /// - internal BuildItemGroup Evaluate(Expander expander, - string baseDirectory, + internal BuildItemGroup Evaluate(Expander expander, + string baseDirectory, bool expandMetadata, ParserOptions parserOptions, - EngineLoggingServices loggingServices, + EngineLoggingServices loggingServices, BuildEventContext buildEventContext) { BuildItemGroup result = new BuildItemGroup(); @@ -1255,14 +1255,14 @@ public string GetMetadata(string metadataName) { ErrorUtilities.VerifyThrow(this.unevaluatedCustomMetadata != null, "Item not initialized properly. unevaluatedCustomMetadata is null."); - metadataValue = (string) this.unevaluatedCustomMetadata[metadataName]; + metadataValue = (string)this.unevaluatedCustomMetadata[metadataName]; } // If we don't have an explicit value for this metadata then try to find a default value if (metadataValue == null) { metadataValue = GetDefaultMetadataValue(metadataName); - } + } return metadataValue ?? String.Empty; } @@ -1305,14 +1305,14 @@ internal string GetEvaluatedMetadataEscaped(string metadataName) { ErrorUtilities.VerifyThrow(this.evaluatedCustomMetadata != null, "Item not initialized properly. evaluatedCustomMetadata is null."); - metadataValue = (string) this.evaluatedCustomMetadata[metadataName]; + metadataValue = (string)this.evaluatedCustomMetadata[metadataName]; } // If we don't have an explicit value for this metadata then try to find a default value if (metadataValue == null) { metadataValue = GetDefaultMetadataValue(metadataName); - } + } return metadataValue ?? String.Empty; } @@ -1564,7 +1564,7 @@ internal void RevertToPersistedMetadata() evaluatedCustomMetadataBackup = null; } } - + /// /// Sets an arbitrary metadata on the item element. These are metadata that the project author has placed on the item /// element that have no meaning to MSBuild. They are just arbitrary metadata that travel around with the BuildItem. @@ -1645,7 +1645,7 @@ private string GetDefaultMetadataValue(string metadataName) /// Thrown when the item-spec is not a path. private string GetItemSpecModifier(string modifier) { - string modifiedItemSpec = + string modifiedItemSpec = FileUtilities.GetItemSpecModifier(Project.PerThreadProjectDirectory, FinalItemSpecEscaped, modifier, ref itemSpecModifiers); if (modifiedItemSpec.Length == 0) @@ -1901,7 +1901,7 @@ public BuildItem Clone() /// internal void UpdateBackingXml(BuildItemGroupChildXml backingXml) { - xml = backingXml; + xml = backingXml; this.name = xml.Name; } @@ -1928,15 +1928,15 @@ internal BuildItem VirtualClone(bool removeReferences) definitionLibraryToClone = null; } - BuildItem virtualClone = - new BuildItem - ( - null /* this is a virtual item with no backing XML */, - name, Include, - false, /* PERF NOTE: don't waste time creating a new custom metadata + BuildItem virtualClone = + new BuildItem + ( + null /* this is a virtual item with no backing XML */, + name, Include, + false, /* PERF NOTE: don't waste time creating a new custom metadata * cache, because we're going to clone the current item's cache */ - definitionLibraryToClone - ); + definitionLibraryToClone + ); virtualClone.SetEvaluatedItemSpecEscaped(evaluatedItemSpecEscaped); virtualClone.SetFinalItemSpecEscaped(FinalItemSpecEscaped); @@ -1947,7 +1947,7 @@ internal BuildItem VirtualClone(bool removeReferences) virtualClone.recursivePortionOfFinalItemSpecDirectory = recursivePortionOfFinalItemSpecDirectory; ErrorUtilities.VerifyThrow(unevaluatedCustomMetadata != null && evaluatedCustomMetadata != null, "Item is not initialized properly."); - + if (removeReferences) { // The ItemDefinition is going to be cleared to remove a link between a project instance and the Item when it is in the cache of targetOutputs. @@ -1961,8 +1961,8 @@ internal BuildItem VirtualClone(bool removeReferences) // Cloning is cheap for CopyOnWriteHashtable so just always do it. virtualClone.unevaluatedCustomMetadata = (CopyOnWriteHashtable)this.unevaluatedCustomMetadata.Clone(); virtualClone.evaluatedCustomMetadata = (CopyOnWriteHashtable)this.evaluatedCustomMetadata.Clone(); - } - + } + return virtualClone; } diff --git a/src/Deprecated/Engine/Items/BuildItemGroup.cs b/src/Deprecated/Engine/Items/BuildItemGroup.cs index 82f439c644b..b11d20d010a 100644 --- a/src/Deprecated/Engine/Items/BuildItemGroup.cs +++ b/src/Deprecated/Engine/Items/BuildItemGroup.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -31,7 +31,7 @@ public class BuildItemGroup : IItemPropertyGrouping, IEnumerable // If this is a persisted , this boolean tells us whether // it came from the main project file, or an imported project file. - bool importedFromAnotherProject = false; + private bool importedFromAnotherProject = false; // These are the loose Items beneath this BuildItemGroup. This is // valid for both persisted and virtual ItemGroups. @@ -388,11 +388,11 @@ internal void AddItem(BuildItem itemToAdd) int insertionIndex = items.Count; for (int i = 0; i < items.Count; i++) { - if ( String.Equals(itemToAdd.Name, items[i].Name, StringComparison.OrdinalIgnoreCase)) + if (String.Equals(itemToAdd.Name, items[i].Name, StringComparison.OrdinalIgnoreCase)) { insertionIndex = i + 1; - if ( 0 > String.Compare(itemToAdd.Include, items[i].Include, StringComparison.OrdinalIgnoreCase)) + if (0 > String.Compare(itemToAdd.Include, items[i].Include, StringComparison.OrdinalIgnoreCase)) { insertionIndex = i; break; @@ -597,7 +597,7 @@ public void Clear() { MustNotBeImported(); - foreach(BuildItem itemToRemove in items) + foreach (BuildItem itemToRemove in items) { XmlElement itemElement = itemToRemove.ItemElement; MustHaveThisParentElement(itemToRemove); diff --git a/src/Deprecated/Engine/Items/BuildItemGroupCollection.cs b/src/Deprecated/Engine/Items/BuildItemGroupCollection.cs index 703772c70db..ec7bc1cb34e 100644 --- a/src/Deprecated/Engine/Items/BuildItemGroupCollection.cs +++ b/src/Deprecated/Engine/Items/BuildItemGroupCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Deprecated/Engine/Items/BuildItemGroupProxy.cs b/src/Deprecated/Engine/Items/BuildItemGroupProxy.cs index fa015ebcc36..481e3d2b06d 100644 --- a/src/Deprecated/Engine/Items/BuildItemGroupProxy.cs +++ b/src/Deprecated/Engine/Items/BuildItemGroupProxy.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -21,7 +21,7 @@ internal class BuildItemGroupProxy : IEnumerable private BuildItemGroup backingItemGroup; private BuildItemGroupProxy() - { + { // Do nothing } diff --git a/src/Deprecated/Engine/Items/ItemDefinitionLibrary.cs b/src/Deprecated/Engine/Items/ItemDefinitionLibrary.cs index 87cb6e68e47..732d49fedf4 100644 --- a/src/Deprecated/Engine/Items/ItemDefinitionLibrary.cs +++ b/src/Deprecated/Engine/Items/ItemDefinitionLibrary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -21,10 +21,10 @@ internal class ItemDefinitionLibrary { #region Fields - Project parentProject; - List itemDefinitions; - ItemDefinitionsDictionary itemDefinitionsDictionary; - bool evaluated; + private Project parentProject; + private List itemDefinitions; + private ItemDefinitionsDictionary itemDefinitionsDictionary; + private bool evaluated; #endregion @@ -176,10 +176,10 @@ private class BuildItemDefinitionGroupXml { #region Fields - XmlElement element; - Project parentProject; - XmlAttribute conditionAttribute; - string condition; + private XmlElement element; + private Project parentProject; + private XmlAttribute conditionAttribute; + private string condition; #endregion @@ -317,8 +317,8 @@ private void EvaluateItemDefinitionChildElement(XmlElement itemDefinitionChildEl /// internal class SpecificItemDefinitionLibrary { - string itemType; - ItemDefinitionLibrary itemDefinitionLibrary; + private string itemType; + private ItemDefinitionLibrary itemDefinitionLibrary; /// /// Constructor diff --git a/src/Deprecated/Engine/Items/ItemExpander.cs b/src/Deprecated/Engine/Items/ItemExpander.cs index dd60744cfc3..3643c32e74a 100644 --- a/src/Deprecated/Engine/Items/ItemExpander.cs +++ b/src/Deprecated/Engine/Items/ItemExpander.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -220,7 +220,7 @@ out Match itemVectorMatch ErrorUtilities.VerifyThrow(items != null, "ItemizeItemVector shouldn't give us null."); } - + return items; } @@ -235,7 +235,7 @@ internal static bool ExpressionContainsItemVector(string expression) { return true; } - + return false; } @@ -253,7 +253,7 @@ private static Match GetItemVectorMatches(string expression) itemVectorMatch = itemVectorPattern.Match(expression); } - return itemVectorMatch; + return itemVectorMatch; } /// @@ -343,7 +343,7 @@ private string ExpandItemVector(Match itemVector) { ErrorUtilities.VerifyThrow(itemVector.Success, "Need a valid item vector."); - string separator = (itemVector.Groups["SEPARATOR_SPECIFICATION"].Length != 0) + string separator = (itemVector.Groups["SEPARATOR_SPECIFICATION"].Length != 0) ? itemVector.Groups["SEPARATOR"].Value : ";"; diff --git a/src/Deprecated/Engine/Items/TaskItem.cs b/src/Deprecated/Engine/Items/TaskItem.cs index a5a53f4da5c..27aac1327f6 100644 --- a/src/Deprecated/Engine/Items/TaskItem.cs +++ b/src/Deprecated/Engine/Items/TaskItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -119,7 +119,7 @@ public int CustomMetadataCount return item.CustomMetadataCount; } } - + /// /// Looks up the value of the given custom metadata. /// @@ -208,14 +208,14 @@ ITaskItem destinationItem /// JomoF public IDictionary CloneCustomMetadata() { - IDictionary backingItemMetadata = item.CloneCustomMetadata(); + IDictionary backingItemMetadata = item.CloneCustomMetadata(); // Go through and escape the metadata as necessary. string[] keys = new string[backingItemMetadata.Count]; backingItemMetadata.Keys.CopyTo(keys, 0); foreach (string singleMetadataName in keys) { - string singleMetadataValue = (string) backingItemMetadata[singleMetadataName]; + string singleMetadataValue = (string)backingItemMetadata[singleMetadataName]; bool unescapingWasNecessary; string singleMetadataValueUnescaped = EscapingUtilities.UnescapeAll(singleMetadataValue, out unescapingWasNecessary); @@ -253,7 +253,7 @@ public override object InitializeLifetimeService() // the backing item internal BuildItem item; - + #region Operators /// diff --git a/src/Deprecated/Engine/ItemsAndProperties/ExpressionShredder.cs b/src/Deprecated/Engine/ItemsAndProperties/ExpressionShredder.cs index 1ead6244ab7..74d9b3c3edb 100644 --- a/src/Deprecated/Engine/ItemsAndProperties/ExpressionShredder.cs +++ b/src/Deprecated/Engine/ItemsAndProperties/ExpressionShredder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -87,7 +87,7 @@ internal static List SplitSemiColonSeparatedList(string expression) return splitList; } - + /// /// Given a list of expressions that may contain item list expressions, /// returns a pair of tables of all item names found, as K=Name, V=String.Empty; diff --git a/src/Deprecated/Engine/ItemsAndProperties/Lookup.cs b/src/Deprecated/Engine/ItemsAndProperties/Lookup.cs index 0b219cc6f5f..2b346d2ace4 100644 --- a/src/Deprecated/Engine/ItemsAndProperties/Lookup.cs +++ b/src/Deprecated/Engine/ItemsAndProperties/Lookup.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -139,7 +139,7 @@ private Lookup(Lookup that) this.cloneTable = that.cloneTable; } -#endregion + #endregion #region Properties @@ -227,7 +227,7 @@ private BuildPropertyGroup SecondaryPropertySets set { lookupEntries.First.Next.Value.PropertySets = value; } } -#endregion + #endregion #region Internal Methods @@ -662,7 +662,7 @@ internal void AddNewItems(BuildItemGroup group) { MustBeOwningThread(); - // Adding to outer scope could be easily implemented, but our code does not do it at present + // Adding to outer scope could be easily implemented, but our code does not do it at present MustNotBeOuterScope(); #if DEBUG @@ -802,7 +802,7 @@ internal void ModifyItems(string name, BuildItemGroup group, Dictionary /// Appropriate action to take if this event is received on the parent process /// - internal virtual void HostAction( IEngineCallback engineCallback, LocalNodeProvider nodeProvider, int nodeId ) + internal virtual void HostAction(IEngineCallback engineCallback, LocalNodeProvider nodeProvider, int nodeId) { ErrorUtilities.VerifyThrow(false, "This description doesn't support this operation"); } @@ -113,8 +113,8 @@ internal virtual void WriteToStream(BinaryWriter writer) internal virtual void CreateFromStream(BinaryReader reader) { - callType = (LocalCallType)reader.ReadByte(); - callNumber = reader.ReadInt32(); + callType = (LocalCallType)reader.ReadByte(); + callNumber = reader.ReadInt32(); } #endregion } @@ -196,7 +196,7 @@ internal override void WriteToStream(BinaryWriter writer) if (replyData is CacheEntry[]) { writer.Write((byte)0); - CacheEntry[] cacheArray =(CacheEntry[]) replyData; + CacheEntry[] cacheArray = (CacheEntry[])replyData; writer.Write((Int32)cacheArray.Length); for (int i = 0; i < cacheArray.Length; i++) { @@ -234,7 +234,7 @@ internal override void CreateFromStream(BinaryReader reader) { int numberOfEntries = reader.ReadInt32(); CacheEntry[] cacheArray = new CacheEntry[numberOfEntries]; - + for (int i = 0; i < numberOfEntries; i++) { if (reader.ReadByte() == 0) @@ -266,8 +266,8 @@ internal LocalCallDescriptorForPostBuildRequests() { } - internal LocalCallDescriptorForPostBuildRequests(BuildRequest [] buildRequests) - :base(LocalCallType.PostBuildRequests) + internal LocalCallDescriptorForPostBuildRequests(BuildRequest[] buildRequests) + : base(LocalCallType.PostBuildRequests) { this.buildRequests = buildRequests; } @@ -280,7 +280,7 @@ internal LocalCallDescriptorForPostBuildRequests(BuildRequest buildRequest) } #endregion - + #region Methods internal override void HostAction(IEngineCallback engineCallback, LocalNodeProvider nodeProvider, int nodeId) { @@ -649,7 +649,7 @@ internal LocalCallDescriptorForShutdownComplete() { } - internal LocalCallDescriptorForShutdownComplete(Node.NodeShutdownLevel shutdownLevel, int totalTaskTime ) + internal LocalCallDescriptorForShutdownComplete(Node.NodeShutdownLevel shutdownLevel, int totalTaskTime) : base(LocalCallType.ShutdownComplete) { this.shutdownLevel = shutdownLevel; @@ -693,7 +693,7 @@ internal override void CreateFromStream(BinaryReader reader) { base.CreateFromStream(reader); shutdownLevel = (Node.NodeShutdownLevel)reader.ReadInt32(); - totalTaskTime = reader.ReadInt32(); + totalTaskTime = reader.ReadInt32(); } #endregion } @@ -713,7 +713,7 @@ internal LocalCallDescriptorForInitializeNode() internal LocalCallDescriptorForInitializeNode ( - Hashtable environmentVariablesToSend, + Hashtable environmentVariablesToSend, LoggerDescription[] nodeLoggers, int nodeId, BuildPropertyGroup parentGlobalProperties, @@ -736,7 +736,7 @@ string parentStartupDirectory #region Methods internal override void NodeAction(Node node, LocalNode localNode) { - localNode.Activate(environmentVariables, nodeLoggers, nodeId, parentGlobalProperties, + localNode.Activate(environmentVariables, nodeLoggers, nodeId, parentGlobalProperties, toolsetSearchLocations, parentProcessId, parentStartupDirectory); } #endregion @@ -764,7 +764,7 @@ internal LoggerDescription[] NodeLoggers { get { - return nodeLoggers; + return nodeLoggers; } } internal int NodeId @@ -886,7 +886,7 @@ internal override void CreateFromStream(BinaryReader reader) #endregion toolsetSearchLocations = (ToolsetDefinitionLocations)reader.ReadByte(); parentStartupDirectory = (string)reader.ReadString(); - } + } #endregion } #endregion @@ -984,8 +984,8 @@ internal int RequestId #region CustomSerializationToStream internal override void WriteToStream(BinaryWriter writer) { - base.WriteToStream(writer); - writer.Write((Int32)requestId); + base.WriteToStream(writer); + writer.Write((Int32)requestId); } internal override void CreateFromStream(BinaryReader reader) @@ -1072,7 +1072,7 @@ internal class LocalCallDescriptorForPostIntrospectorCommand : LocalCallDescript internal LocalCallDescriptorForPostIntrospectorCommand(TargetInProgessState child, TargetInProgessState parent) : base(LocalCallType.PostIntrospectorCommand) { - this.child = child; + this.child = child; this.parent = parent; } #endregion @@ -1212,7 +1212,7 @@ internal override void WriteToStream(BinaryWriter writer) writer.Write((Int32)entries.Length); for (int i = 0; i < entries.Length; i++) { - CacheEntryCustomSerializer.WriteToStream(entries[i], writer); + CacheEntryCustomSerializer.WriteToStream(entries[i], writer); } } #endregion @@ -1519,7 +1519,7 @@ internal override void CreateFromStream(BinaryReader reader) cacheContentType = (CacheContentType)reader.ReadByte(); } #endregion - + } #endregion diff --git a/src/Deprecated/Engine/LocalProvider/LocalNode.cs b/src/Deprecated/Engine/LocalProvider/LocalNode.cs index c883962ece7..62dabcdb2f4 100644 --- a/src/Deprecated/Engine/LocalProvider/LocalNode.cs +++ b/src/Deprecated/Engine/LocalProvider/LocalNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -45,42 +45,42 @@ private static void UnhandledExceptionHandler(object sender, UnhandledExceptionE /// internal static void DumpExceptionToFile(Exception ex) { - // Lock as multiple threads may throw simultaneously - lock (dumpFileLocker) + // Lock as multiple threads may throw simultaneously + lock (dumpFileLocker) + { + if (dumpFileName == null) { - if (dumpFileName == null) - { - Guid guid = Guid.NewGuid(); - string tempPath = Path.GetTempPath(); - - // For some reason we get Watson buckets because GetTempPath gives us a folder here that doesn't exist. - // Either because %TMP% is misdefined, or because they deleted the temp folder during the build. - if (!Directory.Exists(tempPath)) - { - // If this throws, no sense catching it, we can't log it now, and we're here - // because we're a child node with no console to log to, so die - Directory.CreateDirectory(tempPath); - } + Guid guid = Guid.NewGuid(); + string tempPath = Path.GetTempPath(); - dumpFileName = Path.Combine(tempPath, "MSBuild_" + guid.ToString()); - - using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/)) - { - writer.WriteLine("UNHANDLED EXCEPTIONS FROM CHILD NODE:"); - writer.WriteLine("==================="); - } + // For some reason we get Watson buckets because GetTempPath gives us a folder here that doesn't exist. + // Either because %TMP% is misdefined, or because they deleted the temp folder during the build. + if (!Directory.Exists(tempPath)) + { + // If this throws, no sense catching it, we can't log it now, and we're here + // because we're a child node with no console to log to, so die + Directory.CreateDirectory(tempPath); } + dumpFileName = Path.Combine(tempPath, "MSBuild_" + guid.ToString()); + using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/)) { - writer.WriteLine(DateTime.Now.ToLongTimeString()); - writer.WriteLine(ex.ToString()); + writer.WriteLine("UNHANDLED EXCEPTIONS FROM CHILD NODE:"); writer.WriteLine("==================="); } } + + using (StreamWriter writer = new StreamWriter(dumpFileName, true /*append*/)) + { + writer.WriteLine(DateTime.Now.ToLongTimeString()); + writer.WriteLine(ex.ToString()); + writer.WriteLine("==================="); + } + } } -#endregion + #endregion #region Constructors @@ -101,7 +101,7 @@ internal LocalNode(int nodeNumberIn) /// /// This method causes the reader and writer threads to start and create the shared memory structures /// - void StartCommunicationThreads() + private void StartCommunicationThreads() { // The writer thread should be created before the // reader thread because some LocalCallDescriptors @@ -138,7 +138,7 @@ void StartCommunicationThreads() /// /// This method causes the reader and writer threads to exit and dispose of the shared memory structures /// - void StopCommunicationThreads() + private void StopCommunicationThreads() { communicationThreadExitEvent.Set(); @@ -320,7 +320,7 @@ public static void StartLocalNodeServer(int nodeNumber) globalNodeActive.Close(); globalNodeInUse.Close(); - } + } #endregion @@ -370,7 +370,7 @@ private void SharedMemoryReaderThread() { // Process the reply from the parent so it can be looked in a hashtable based // on the call descriptor who requested the reply. - engineCallback.PostReplyFromParent((LocalReplyCallDescriptor) callDescriptor); + engineCallback.PostReplyFromParent((LocalReplyCallDescriptor)callDescriptor); } } } @@ -413,11 +413,11 @@ internal void ShutdownNode(Node.NodeShutdownLevel shutdownLevel, bool exitProces new LocalCallDescriptorForShutdownComplete(shutdownLevel, node.TotalTaskTime); // Post the message indicating that the shutdown is complete engineCallback.PostMessageToParent(callDescriptor, true); - } + } } catch (Exception e) { - if (shutdownLevel != Node.NodeShutdownLevel.ErrorShutdown) + if (shutdownLevel != Node.NodeShutdownLevel.ErrorShutdown) { ReportNonFatalCommunicationError(e); } @@ -437,7 +437,7 @@ internal void ShutdownNode(Node.NodeShutdownLevel shutdownLevel, bool exitProces { // Even if we completed a build, if we are goign to exit the process we need to null out the node and set the notInUseEvent, this is // accomplished by calling this method again with the ErrorShutdown handle - if ( shutdownLevel == Node.NodeShutdownLevel.BuildCompleteSuccess || shutdownLevel == Node.NodeShutdownLevel.BuildCompleteFailure ) + if (shutdownLevel == Node.NodeShutdownLevel.BuildCompleteSuccess || shutdownLevel == Node.NodeShutdownLevel.BuildCompleteFailure) { ShutdownNode(Node.NodeShutdownLevel.ErrorShutdown, false, true); } @@ -476,9 +476,9 @@ string parentStartupDirectory Environment.SetEnvironmentVariable(variableName, null); } - foreach(string key in environmentVariables.Keys) + foreach (string key in environmentVariables.Keys) { - Environment.SetEnvironmentVariable(key,(string)environmentVariables[key]); + Environment.SetEnvironmentVariable(key, (string)environmentVariables[key]); } // Host the msbuild engine and system @@ -613,7 +613,7 @@ internal static string DumpFileName /// Indicates the node is now in use. This means the node has recieved an activate command with initialization /// data from the parent procss /// - private static ManualResetEvent inUseEvent = new ManualResetEvent(false); + private static ManualResetEvent inUseEvent = new ManualResetEvent(false); /// /// Randomly generated file name for all exceptions thrown by this node that need to be dumped to a file. @@ -622,7 +622,7 @@ internal static string DumpFileName private static string dumpFileName = null; // Timeouts && Constants - private const int inactivityTimeout = 60 * 1000; // 60 seconds of inactivity to exit + private const int inactivityTimeout = 60 * 1000; // 60 seconds of inactivity to exit private const int parentCheckInterval = 5 * 1000; // Check if the parent process is there every 5 seconds #endregion diff --git a/src/Deprecated/Engine/LocalProvider/LocalNodeCallback.cs b/src/Deprecated/Engine/LocalProvider/LocalNodeCallback.cs index 000446c6fc1..776c0a08b61 100644 --- a/src/Deprecated/Engine/LocalProvider/LocalNodeCallback.cs +++ b/src/Deprecated/Engine/LocalProvider/LocalNodeCallback.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -61,7 +61,7 @@ internal void StartWriterThread(int nodeNumber) // Start the thread that will be processing the calls to the parent engine ThreadStart threadState = new ThreadStart(this.SharedMemoryWriterThread); writerThread = new Thread(threadState); - writerThread.Name = "MSBuild Child->Parent Writer"; + writerThread.Name = "MSBuild Child->Parent Writer"; writerThread.Start(); } @@ -115,8 +115,8 @@ internal void PostReplyFromParent(LocalReplyCallDescriptor reply) lock (repliesFromParent) { - ReplyData replyData = (ReplyData) repliesFromParent[requestingCallNumber]; - ErrorUtilities.VerifyThrow(replyData?.waitEvent != null, + ReplyData replyData = (ReplyData)repliesFromParent[requestingCallNumber]; + ErrorUtilities.VerifyThrow(replyData?.waitEvent != null, "We must have an event for this call at this point"); replyData.reply = reply; @@ -241,7 +241,7 @@ private object GetReplyForCallDescriptor(LocalCallDescriptor callDescriptor) replyFromParentArrived.Reset(); int requestingCallNumber = callDescriptor.CallNumber; - + ReplyData replyData = new ReplyData(); replyData.waitEvent = replyFromParentArrived; diff --git a/src/Deprecated/Engine/LocalProvider/LocalNodeInfo.cs b/src/Deprecated/Engine/LocalProvider/LocalNodeInfo.cs index 506cd32a483..f4c4b0de46b 100644 --- a/src/Deprecated/Engine/LocalProvider/LocalNodeInfo.cs +++ b/src/Deprecated/Engine/LocalProvider/LocalNodeInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Threading; @@ -15,13 +15,13 @@ internal class LocalNodeInfo #region Constructors internal LocalNodeInfo(int availableNodeNumberHint) { - this.nodeState = LocalNodeProvider.NodeState.NotLaunched; - this.targetList = new LinkedList(); - this.nodeCommandQueue = new DualQueue(); - this.nodeHiPriCommandQueue = new DualQueue(); - this.nodeReserveHandle = null; - this.communicationFailed = false; - this.processId = unInitializedProcessId; + this.nodeState = LocalNodeProvider.NodeState.NotLaunched; + this.targetList = new LinkedList(); + this.nodeCommandQueue = new DualQueue(); + this.nodeHiPriCommandQueue = new DualQueue(); + this.nodeReserveHandle = null; + this.communicationFailed = false; + this.processId = unInitializedProcessId; // Figure out the next available node number ReserveNextAvailableNodeNumber(availableNodeNumberHint); @@ -141,12 +141,12 @@ internal bool CommunicationFailed public bool ShutdownResponseReceived { - get + get { return shutdownResponseReceived; } - set - { + set + { shutdownResponseReceived = value; } } @@ -192,7 +192,7 @@ internal bool CreateSharedMemoryBuffers() internal void ReleaseNode() { - if ( nodeReserveHandle != null ) + if (nodeReserveHandle != null) { nodeReserveHandle.Close(); processId = invalidProcessId; @@ -209,7 +209,7 @@ private void ReserveNextAvailableNodeNumber(int currentNodeNumber) while (nodeReserveHandle == null) { bool createdNew; - nodeReserveHandle = + nodeReserveHandle = new EventWaitHandle(false, EventResetMode.ManualReset, LocalNodeProviderGlobalNames.NodeReserveEventName(currentNodeNumber), out createdNew); if (!createdNew) { diff --git a/src/Deprecated/Engine/LocalProvider/LocalNodeProvider.cs b/src/Deprecated/Engine/LocalProvider/LocalNodeProvider.cs index eb73adeb434..ad45e12e9b3 100644 --- a/src/Deprecated/Engine/LocalProvider/LocalNodeProvider.cs +++ b/src/Deprecated/Engine/LocalProvider/LocalNodeProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -66,7 +66,7 @@ string startupDirectory { this.locationOfMSBuildExe = AppDomain.CurrentDomain.BaseDirectory; } - if ( (cpuCount - 1) <= 0) + if ((cpuCount - 1) <= 0) { return; } @@ -122,7 +122,7 @@ public void ApplyParameter(string parameterName, string parameterValue) if (String.Equals(parameterName, "MAXCPUCOUNT", StringComparison.OrdinalIgnoreCase)) { - try + try { this.cpuCount = Convert.ToInt32(parameterValue, CultureInfo.InvariantCulture); } @@ -166,7 +166,7 @@ public void ApplyParameter(string parameterName, string parameterValue) public INodeDescription[] QueryNodeDescriptions() { - return new INodeDescription[cpuCount-1]; + return new INodeDescription[cpuCount - 1]; } public void AssignNodeIdentifiers(int[] nodeIds) @@ -409,7 +409,7 @@ private void SendShutdownRequests(Node.NodeShutdownLevel nodeShutdownLevel) // before shutting down the node while (nodeData[i].NodeState == NodeState.LaunchInProgress && !nodeData[i].CommunicationFailed) { - Thread.Sleep(500); + Thread.Sleep(500); } if (nodeData[i].NodeState == NodeState.Launched) @@ -481,7 +481,7 @@ private bool IsNodeProcessAliveOrUninitialized(int nodeId) if (isUninitialized) { - return true; + return true; } bool isInvalidProcessId = nodeData[nodeId].ProcessId == LocalNodeInfo.invalidProcessId; @@ -490,7 +490,7 @@ private bool IsNodeProcessAliveOrUninitialized(int nodeId) { return true; } - } + } catch (ArgumentException) { // Process already exited @@ -531,7 +531,7 @@ private void IncreaseActiveNodeCount() /// internal void RecordNodeResponse(int nodeId, Node.NodeShutdownLevel shutdownLevel, int totalTaskTime) { - // If the node is shutting down - decrease the count of active nodes + // If the node is shutting down - decrease the count of active nodes if (shutdownLevel == Node.NodeShutdownLevel.ErrorShutdown || shutdownLevel == Node.NodeShutdownLevel.PoliteShutdown) { @@ -727,7 +727,7 @@ private void InitializeNode(int nodeIndex) /// for a given index. The node is running if the global mutex with a /// "Node_" + nodeId + "_ActiveReady" as a name was created /// - private static bool checkIfNodeActive(int nodeNumber) + private static bool checkIfNodeActive(int nodeNumber) { bool nodeIsActive = false; EventWaitHandle nodeActiveHandle = null; @@ -756,7 +756,7 @@ private void LaunchNode(int nodeIndex) EventWaitHandle nodeReadyEvent = null; string msbuildLocation = Path.Combine(locationOfMSBuildExe, "MSBuild.exe"); - ErrorUtilities.VerifyThrow(File.Exists(msbuildLocation),"Msbuild.exe cannot be found at: "+msbuildLocation); + ErrorUtilities.VerifyThrow(File.Exists(msbuildLocation), "Msbuild.exe cannot be found at: " + msbuildLocation); bool exitedDueToError = true; try @@ -971,13 +971,13 @@ private void SharedMemoryReaderThread() nodeData[i].SharedMemoryFromNode = null; } } - } + } #endregion #region Data private IEngineCallback engineCallback; - private ManualResetEvent exitCommunicationThreads; + private ManualResetEvent exitCommunicationThreads; private ManualResetEvent responseCountChangeEvent; private int activeNodeCount; diff --git a/src/Deprecated/Engine/LocalProvider/LocalNodeProviderGlobalNames.cs b/src/Deprecated/Engine/LocalProvider/LocalNodeProviderGlobalNames.cs index f1b17e6902e..7712d1cd550 100644 --- a/src/Deprecated/Engine/LocalProvider/LocalNodeProviderGlobalNames.cs +++ b/src/Deprecated/Engine/LocalProvider/LocalNodeProviderGlobalNames.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; @@ -8,7 +8,7 @@ namespace Microsoft.Build.BuildEngine /// /// This class is shared between LocalNode and LocalNodeProvider and contains all the global name generation logic /// - static class LocalNodeProviderGlobalNames + internal static class LocalNodeProviderGlobalNames { #region Methods @@ -18,7 +18,7 @@ static class LocalNodeProviderGlobalNames /// /// /// - static internal string NodeActiveEventName(int nodeNumber) + internal static string NodeActiveEventName(int nodeNumber) { if (nodePostfix == null) { @@ -32,7 +32,7 @@ static internal string NodeActiveEventName(int nodeNumber) /// /// /// - static internal string NodeInUseEventName(int nodeNumber) + internal static string NodeInUseEventName(int nodeNumber) { if (nodePostfix == null) { @@ -47,7 +47,7 @@ static internal string NodeInUseEventName(int nodeNumber) /// /// /// - static internal string NodeErrorShutdownEventName(int nodeNumber) + internal static string NodeErrorShutdownEventName(int nodeNumber) { if (nodePostfix == null) { @@ -63,7 +63,7 @@ static internal string NodeErrorShutdownEventName(int nodeNumber) /// /// /// - static internal string NodeReserveEventName(int nodeNumber) + internal static string NodeReserveEventName(int nodeNumber) { if (nodePostfix == null) { @@ -110,7 +110,7 @@ internal static string NodeActivedEventName(int nodeNumber) /// /// /// - static internal string NodeInputMemoryName(int nodeNumber) + internal static string NodeInputMemoryName(int nodeNumber) { if (nodePostfix == null) { @@ -124,7 +124,7 @@ static internal string NodeInputMemoryName(int nodeNumber) /// /// /// - static internal string NodeOutputMemoryName(int nodeNumber) + internal static string NodeOutputMemoryName(int nodeNumber) { if (nodePostfix == null) { @@ -138,7 +138,7 @@ static internal string NodeOutputMemoryName(int nodeNumber) /// /// Use reflection to figure out the version of Microsoft.Build.Engine.dll /// - static private void InitializeGlobalNamePostFixValues() + private static void InitializeGlobalNamePostFixValues() { AssemblyName name = new AssemblyName(Assembly.GetExecutingAssembly().FullName); string engineVersion = name.Version.ToString(); @@ -160,7 +160,7 @@ static private void InitializeGlobalNamePostFixValues() #endregion #region Data - static string nodePostfix = null; + private static string nodePostfix = null; #endregion } } diff --git a/src/Deprecated/Engine/LocalProvider/NativeMethods.cs b/src/Deprecated/Engine/LocalProvider/NativeMethods.cs index d2be3516f56..549e63b93e9 100644 --- a/src/Deprecated/Engine/LocalProvider/NativeMethods.cs +++ b/src/Deprecated/Engine/LocalProvider/NativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Win32.SafeHandles; @@ -20,17 +20,17 @@ internal static class NativeMethods 0x0008 | 0x0010; internal const uint NORMAL_PRIORITY_CLASS = 0x0020; - internal const uint CREATE_NO_WINDOW = 0x08000000; + internal const uint CREATE_NO_WINDOW = 0x08000000; internal const Int32 STARTF_USESTDHANDLES = 0x00000100; internal const uint PAGE_SIZE = 4096; internal const int SECURITY_DESCRIPTOR_REVISION = 1; - internal const int ERROR_SUCCESS = 0; + internal const int ERROR_SUCCESS = 0; - internal const string ADMINONLYSDDL = "D:" + //Discretionary ACL + internal const string ADMINONLYSDDL = "D:" + //Discretionary ACL "(A;OICI;GA;;;BA)" + //Allow full control to administrators "(A;OICI;GA;;;SY)"; //Allow full control to System - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CheckTokenMembership ( @@ -40,16 +40,16 @@ internal static extern bool CheckTokenMembership out bool IsMember ); - [DllImport("advapi32.dll", SetLastError=true)] + [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool AllocateAndInitializeSid ( - IntPtr siaNtAuthority, - byte nSubAuthorityCount, - int dwSubAuthority0, int dwSubAuthority1, - int dwSubAuthority2, int dwSubAuthority3, - int dwSubAuthority4, int dwSubAuthority5, - int dwSubAuthority6, int dwSubAuthority7, + IntPtr siaNtAuthority, + byte nSubAuthorityCount, + int dwSubAuthority0, int dwSubAuthority1, + int dwSubAuthority2, int dwSubAuthority3, + int dwSubAuthority4, int dwSubAuthority5, + int dwSubAuthority6, int dwSubAuthority7, out IntPtr pSid ); @@ -66,7 +66,7 @@ out IntPtr pSid internal static bool IsUserAdministrator() { int SECURITY_BUILTIN_DOMAIN_RID = 0x00000020; - int DOMAIN_ALIAS_RID_ADMINS = 0x00000220; + int DOMAIN_ALIAS_RID_ADMINS = 0x00000220; IntPtr pNtAuthority = Marshal.AllocHGlobal(6); Marshal.WriteInt32(pNtAuthority, 0, 0); Marshal.WriteByte(pNtAuthority, 4, 0); @@ -136,24 +136,24 @@ internal static extern bool UnmapViewOfFile IntPtr lpBaseAddress ); - [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CreateProcess ( string lpApplicationName, - string lpCommandLine, + string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes, ref SECURITY_ATTRIBUTES lpThreadAttributes, [In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandles, - uint dwCreationFlags, - IntPtr lpEnvironment, + uint dwCreationFlags, + IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation ); - [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)] + [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor ( @@ -201,10 +201,10 @@ internal struct SECURITY_DESCRIPTOR [StructLayout(LayoutKind.Sequential)] internal struct PROCESS_INFORMATION { - IntPtr hProcess; - IntPtr hThread; - int dwProcessId; - int dwThreadId; + private IntPtr hProcess; + private IntPtr hThread; + private int dwProcessId; + private int dwThreadId; } [StructLayout(LayoutKind.Sequential)] diff --git a/src/Deprecated/Engine/LocalProvider/SharedMemory.cs b/src/Deprecated/Engine/LocalProvider/SharedMemory.cs index 30bb926fc11..0872834d068 100644 --- a/src/Deprecated/Engine/LocalProvider/SharedMemory.cs +++ b/src/Deprecated/Engine/LocalProvider/SharedMemory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -174,19 +174,19 @@ private void InitializeMemoryMapping(string memoryMapName, bool allowExistingMap Marshal.StructureToPtr(saAttr, pointerToSecurityAttributes, true); } - // The file mapping has either the default (current user) security permissions or - // permissions restricted to only administrator users depending on the check above. - // If pointerToSecurityAttributes is null the default permissions are used. - this.pageFileMapping = - NativeMethods.CreateFileMapping - ( - NativeMethods.InvalidHandle, - pointerToSecurityAttributes, - NativeMethods.PAGE_READWRITE, - 0, - size + 4, - memoryMapName - ); + // The file mapping has either the default (current user) security permissions or + // permissions restricted to only administrator users depending on the check above. + // If pointerToSecurityAttributes is null the default permissions are used. + this.pageFileMapping = + NativeMethods.CreateFileMapping + ( + NativeMethods.InvalidHandle, + pointerToSecurityAttributes, + NativeMethods.PAGE_READWRITE, + 0, + size + 4, + memoryMapName + ); // If only new mappings are allowed and the current one has been created by somebody else // delete the mapping. Note that we would like to compare the GetLastError value against @@ -218,8 +218,8 @@ private void InitializeMemoryMapping(string memoryMapName, bool allowExistingMap NativeMethods.FILE_MAP_ALL_ACCESS, // Give the map read, write, and copy access 0, // Start mapped view at high order offset 0 0, // Start mapped view at low order offset 0 - // The size of the shared memory plus some extra space for an int - // to write the number of bytes written + // The size of the shared memory plus some extra space for an int + // to write the number of bytes written (IntPtr)(size + 4) ); @@ -930,8 +930,8 @@ internal void Reset() private Semaphore unreadBatchCounter; //Used to inform the shared memory reader threads the writer thread has written something in shared memory to read. - //The semaphore is incremented when the shared memory is full and when there is an unreadBatch availiable to be read or the shared memory is full. - //The semaphore is decremented when the shared memory reader thread is about to read from the shared memory. + //The semaphore is incremented when the shared memory is full and when there is an unreadBatch availiable to be read or the shared memory is full. + //The semaphore is decremented when the shared memory reader thread is about to read from the shared memory. private Semaphore readActionCounter; // Whether or not the shared memory is full diff --git a/src/Deprecated/Engine/Logging/BaseConsoleLogger.cs b/src/Deprecated/Engine/Logging/BaseConsoleLogger.cs index bc9f6226b04..00b1ed66480 100644 --- a/src/Deprecated/Engine/Logging/BaseConsoleLogger.cs +++ b/src/Deprecated/Engine/Logging/BaseConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -15,7 +15,7 @@ namespace Microsoft.Build.BuildEngine internal delegate void WriteLinePrettyFromResourceDelegate(int indentLevel, string resourceString, params object[] args); #endregion - abstract internal class BaseConsoleLogger : INodeLogger + internal abstract class BaseConsoleLogger : INodeLogger { #region Properties /// @@ -218,7 +218,7 @@ internal void WriteNewLine() /// /// /// - internal void WriteLinePrettyFromResource(string resourceString, params object[] args) + internal void WriteLinePrettyFromResource(string resourceString, params object[] args) { int indentLevel = IsVerbosityAtLeast(LoggerVerbosity.Normal) ? this.currentIndentLevel : 0; WriteLinePrettyFromResource(indentLevel, resourceString, args); @@ -227,7 +227,7 @@ internal void WriteLinePrettyFromResource(string resourceString, params object[ /// /// Writes a line from a resource string to the log, using the specified indentation. /// - internal void WriteLinePrettyFromResource(int indentLevel, string resourceString, params object[] args) + internal void WriteLinePrettyFromResource(int indentLevel, string resourceString, params object[] args) { string formattedString = ResourceUtilities.FormatResourceString(resourceString, args); WriteLinePretty(indentLevel, formattedString); @@ -237,7 +237,7 @@ internal void WriteLinePrettyFromResource(int indentLevel, string resourceStrin /// Writes to the log, using the default indentation. Does not /// terminate with a newline. /// - internal void WritePretty(string formattedString) + internal void WritePretty(string formattedString) { int indentLevel = IsVerbosityAtLeast(LoggerVerbosity.Normal) ? this.currentIndentLevel : 0; WritePretty(indentLevel, formattedString); @@ -634,7 +634,7 @@ internal void DisplayCounters(Hashtable counters) { reentrantCounterExists = true; } - + counter.PrintCounterMessage(lineWriter, setColor, resetColor); } @@ -701,7 +701,7 @@ internal bool ReenteredScope /// /// Whether or not this task or target is executing right now. /// - internal bool InScope + internal bool InScope { get { return inScope; } set @@ -735,36 +735,36 @@ internal bool InScope internal virtual void PrintCounterMessage(WriteLinePrettyFromResourceDelegate WriteLinePrettyFromResource, ColorSetter setColor, ColorResetter resetColor) { - string time; - if (!reenteredScope) - { - // round: submillisecond values are not meaningful - time = String.Format(CultureInfo.CurrentCulture, - "{0,5}", Math.Round(elapsedTime.TotalMilliseconds, 0)); - } - else - { - // no value available; instead display an asterisk - time = " *"; - } + string time; + if (!reenteredScope) + { + // round: submillisecond values are not meaningful + time = String.Format(CultureInfo.CurrentCulture, + "{0,5}", Math.Round(elapsedTime.TotalMilliseconds, 0)); + } + else + { + // no value available; instead display an asterisk + time = " *"; + } - WriteLinePrettyFromResource - ( - 2, - "PerformanceLine", - time, - String.Format(CultureInfo.CurrentCulture, - "{0,-40}" /* pad to 40 align left */, scopeName), - String.Format(CultureInfo.CurrentCulture, - "{0,3}", calls) - ); + WriteLinePrettyFromResource + ( + 2, + "PerformanceLine", + time, + String.Format(CultureInfo.CurrentCulture, + "{0,-40}" /* pad to 40 align left */, scopeName), + String.Format(CultureInfo.CurrentCulture, + "{0,3}", calls) + ); } /// /// Returns an IComparer that will put erformance counters /// in descending order by elapsed time. /// - static internal IComparer DescendingByElapsedTimeComparer + internal static IComparer DescendingByElapsedTimeComparer { get { return new DescendingByElapsedTime(); } } @@ -957,7 +957,7 @@ internal virtual bool ApplyParameter(string parameterName, string parameterValue public abstract void BuildStartedHandler(object sender, BuildStartedEventArgs e); - public abstract void BuildFinishedHandler(object sender, BuildFinishedEventArgs e); + public abstract void BuildFinishedHandler(object sender, BuildFinishedEventArgs e); public abstract void ProjectStartedHandler(object sender, ProjectStartedEventArgs e); @@ -1005,13 +1005,13 @@ internal virtual bool ApplyParameter(string parameterName, string parameterValue /// Delegate used to change text color. /// /// t-jeffv, sumedhk - internal ColorSetter setColor = null; + internal ColorSetter setColor = null; /// /// Delegate used to reset text color /// /// t-jeffv, sumedhk - internal ColorResetter resetColor = null; + internal ColorResetter resetColor = null; /// /// Indicates if project header should not be displayed. diff --git a/src/Deprecated/Engine/Logging/ConsoleLogger.cs b/src/Deprecated/Engine/Logging/ConsoleLogger.cs index c82db95717a..71fa548ca55 100644 --- a/src/Deprecated/Engine/Logging/ConsoleLogger.cs +++ b/src/Deprecated/Engine/Logging/ConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -111,7 +111,7 @@ private void InitializeBaseConsoleLogger() bool useMPLogger = false; if (!string.IsNullOrEmpty(parameters)) { - string [] parameterComponents = parameters.Split(BaseConsoleLogger.parameterDelimiters); + string[] parameterComponents = parameters.Split(BaseConsoleLogger.parameterDelimiters); for (int param = 0; param < parameterComponents.Length; param++) { if (parameterComponents[param].Length > 0) diff --git a/src/Deprecated/Engine/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs b/src/Deprecated/Engine/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs index f9f56bff848..1f20320e013 100644 --- a/src/Deprecated/Engine/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs +++ b/src/Deprecated/Engine/Logging/DistributedLoggers/ConfigurableForwardingLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -13,7 +13,7 @@ namespace Microsoft.Build.BuildEngine /// Logger that forwards events to a central logger (e.g ConsoleLogger) /// residing on the parent node. /// - public class ConfigurableForwardingLogger: IForwardingLogger + public class ConfigurableForwardingLogger : IForwardingLogger { #region Constructors /// @@ -529,7 +529,7 @@ private bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) /// Id of the node the logger is attached to /// private int nodeId; - + #endregion #endregion diff --git a/src/Deprecated/Engine/Logging/DistributedLoggers/DistributedFileLogger.cs b/src/Deprecated/Engine/Logging/DistributedLoggers/DistributedFileLogger.cs index 5bcd93e943b..d1e84706dfa 100644 --- a/src/Deprecated/Engine/Logging/DistributedLoggers/DistributedFileLogger.cs +++ b/src/Deprecated/Engine/Logging/DistributedLoggers/DistributedFileLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -171,7 +171,7 @@ public LoggerVerbosity Verbosity } set { - // Dont really care about verbosity at this point, but dont want to throw exception as it is set for all distributed loggers + // Dont really care about verbosity at this point, but dont want to throw exception as it is set for all distributed loggers } } @@ -194,12 +194,15 @@ public string Parameters private FileLogger nodeFileLogger; // Reference for the central logger private IEventRedirector buildEventRedirector; + // The Id of the node the forwardingLogger is attached to - int nodeId; + private int nodeId; + // Directory to place the log files, by default this will be in the current directory when the node is created - string logFile = "msbuild.log"; + private string logFile = "msbuild.log"; + // Logger parameters - string parameters; + private string parameters; // File logger parameters delimiters. private static readonly char[] fileLoggerParameterDelimiters = { ';' }; // File logger parameter value split character. diff --git a/src/Deprecated/Engine/Logging/FileLogger.cs b/src/Deprecated/Engine/Logging/FileLogger.cs index a8bfd10fa98..a97cea4dba6 100644 --- a/src/Deprecated/Engine/Logging/FileLogger.cs +++ b/src/Deprecated/Engine/Logging/FileLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -33,7 +33,7 @@ public FileLogger() : base(LoggerVerbosity.Normal) { this.WriteHandler = new WriteHandler(Write); } - + #endregion /// @@ -90,12 +90,15 @@ private void InitializeFileLogger(IEventSource eventSource, int nodeCount) catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) - throw; + { + throw; + } + string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", logFileName, e.Message); fileWriter?.Close(); - throw new LoggerException(message,e.InnerException,errorCode, helpKeyword); + throw new LoggerException(message, e.InnerException, errorCode, helpKeyword); } } @@ -121,7 +124,10 @@ private void Write(string text) catch (Exception ex) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(ex)) - throw; + { + throw; + } + string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", logFileName, ex.Message); diff --git a/src/Deprecated/Engine/Logging/LogFormatter.cs b/src/Deprecated/Engine/Logging/LogFormatter.cs index 104ddd98f57..d22c2fbb40c 100644 --- a/src/Deprecated/Engine/Logging/LogFormatter.cs +++ b/src/Deprecated/Engine/Logging/LogFormatter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -10,7 +10,7 @@ namespace Microsoft.Build.BuildEngine /// Utility helper functions for formatting logger output. /// /// JomoF - static internal class LogFormatter + internal static class LogFormatter { /// /// Formats the timestamp in the log as Hours:Minutes:Seconds.Milliseconds @@ -42,7 +42,7 @@ internal static string FormatLogTimeStamp(DateTime timeStamp) /// JomoF /// /// String representation of time-span. - internal static string FormatTimeSpan(TimeSpan t) + internal static string FormatTimeSpan(TimeSpan t) { string rawTime = t.ToString(); // Timespan is a value type and can't be null. int rawTimeLength = rawTime.Length; diff --git a/src/Deprecated/Engine/Logging/LoggerDescription.cs b/src/Deprecated/Engine/Logging/LoggerDescription.cs index 4550081d3e9..01872c8b8b4 100644 --- a/src/Deprecated/Engine/Logging/LoggerDescription.cs +++ b/src/Deprecated/Engine/Logging/LoggerDescription.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -72,7 +72,7 @@ internal string Name { return this.loggerClassName + ":" + this.loggerAssembly.AssemblyFile; } - else if ( !string.IsNullOrEmpty(this.loggerClassName) ) + else if (!string.IsNullOrEmpty(this.loggerClassName)) { return this.loggerClassName; } @@ -229,7 +229,7 @@ internal void ConvertPathsToFullPaths() { if (loggerAssembly.AssemblyFile != null) { - loggerAssembly = + loggerAssembly = new AssemblyLoadInfo(loggerAssembly.AssemblyName, Path.GetFullPath(loggerAssembly.AssemblyFile)); } } @@ -239,7 +239,7 @@ internal void ConvertPathsToFullPaths() #region Data private string loggerClassName; private string loggerSwitchParameters; - private AssemblyLoadInfo loggerAssembly; + private AssemblyLoadInfo loggerAssembly; private LoggerVerbosity verbosity; private int loggerId; #endregion @@ -305,7 +305,7 @@ internal void WriteToStream(BinaryWriter writer) internal void CreateFromStream(BinaryReader reader) { #region LoggerClassName - if (reader.ReadByte() ==0) + if (reader.ReadByte() == 0) { loggerClassName = null; } diff --git a/src/Deprecated/Engine/Logging/NullCentralLogger.cs b/src/Deprecated/Engine/Logging/NullCentralLogger.cs index d6eaf88b342..0b72010b66f 100644 --- a/src/Deprecated/Engine/Logging/NullCentralLogger.cs +++ b/src/Deprecated/Engine/Logging/NullCentralLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Logging/ParallelLogger/ParallelConsoleLogger.cs b/src/Deprecated/Engine/Logging/ParallelLogger/ParallelConsoleLogger.cs index 180d133c560..ae58a2c5112 100644 --- a/src/Deprecated/Engine/Logging/ParallelLogger/ParallelConsoleLogger.cs +++ b/src/Deprecated/Engine/Logging/ParallelLogger/ParallelConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -187,7 +187,10 @@ public override void BuildStartedHandler(object sender, BuildStartedEventArgs e) buildStarted = e.Timestamp; hasBuildStarted = true; - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } if (IsVerbosityAtLeast(LoggerVerbosity.Normal)) { @@ -295,8 +298,8 @@ public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs } } - ResetConsoleLoggerState(); - CheckIfOutputSupportsAlignment(); + ResetConsoleLoggerState(); + CheckIfOutputSupportsAlignment(); } /// @@ -306,12 +309,18 @@ public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs /// private void ShowFlatErrorWarningSummary() { - if (warningList.Count == 0 && errorList.Count == 0) return; + if (warningList.Count == 0 && errorList.Count == 0) + { + return; + } // If we're showing only warnings and/or errors, don't summarize. // This is the buildc.err case. There's no point summarizing since we'd just // repeat the entire log content again. - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } // Make some effort to distinguish this summary from the output above, since otherwise // it's not clear in lower verbosities @@ -345,12 +354,18 @@ private void ShowFlatErrorWarningSummary() /// private void ShowNestedErrorWarningSummary() { - if (warningList.Count == 0 && errorList.Count == 0) return; + if (warningList.Count == 0 && errorList.Count == 0) + { + return; + } // If we're showing only warnings and/or errors, don't summarize. // This is the buildc.err case. There's no point summarizing since we'd just // repeat the entire log content again. - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } if (warningCount > 0) { @@ -432,7 +447,7 @@ private void ShowErrorWarningSummary(ArrayList listToProcess) where T : Build if (!String.Equals(previousTarget, valuePair.Key.TargetName, StringComparison.OrdinalIgnoreCase)) { //If no targetName was specified then do not show the target where the error occurred - if (! string.IsNullOrEmpty(valuePair.Key.TargetName)) + if (!string.IsNullOrEmpty(valuePair.Key.TargetName)) { WriteMessageAligned(ResourceUtilities.FormatResourceString("ErrorWarningInTarget", valuePair.Key.TargetName), false); } @@ -464,7 +479,7 @@ public override void ProjectStartedHandler(object sender, ProjectStartedEventArg { ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); ErrorUtilities.VerifyThrowArgumentNull(e.ParentProjectBuildEventContext, "ParentProjectBuildEventContext"); - + // Add the project to the BuildManager so we can use the start information later in the build process buildEventManager.AddProjectStartedEvent(e); @@ -500,7 +515,7 @@ public override void ProjectStartedHandler(object sender, ProjectStartedEventArg } if (e.Properties != null) { - WriteProperties(e, e.Properties); + WriteProperties(e, e.Properties); } if (e.Items != null) @@ -518,8 +533,8 @@ public override void ProjectStartedHandler(object sender, ProjectStartedEventArg public override void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs e) { ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); - - + + //Get the project started event so we can use its information to properly display a project finished event ProjectStartedEventMinimumFields startedEvent = buildEventManager.GetProjectStartedEvent(e.BuildEventContext); ErrorUtilities.VerifyThrow(startedEvent != null, "Started event should not be null in the finished event handler"); @@ -547,7 +562,7 @@ public override void ProjectFinishedHandler(object sender, ProjectFinishedEventA // should be shown string targets = startedEvent.TargetNames; string projectName = startedEvent.ProjectFile ?? string.Empty; - + // Show which targets were built as part of this project if (string.IsNullOrEmpty(targets)) { @@ -598,7 +613,11 @@ public override void ProjectFinishedHandler(object sender, ProjectFinishedEventA /// List of properties internal void WriteProperties(BuildEventArgs e, IEnumerable properties) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } + ArrayList propertyList = ExtractPropertyList(properties); // if there are no properties to display return out of the method and dont print out anything related to displaying @@ -607,7 +626,7 @@ internal void WriteProperties(BuildEventArgs e, IEnumerable properties) { return; } - + WriteLinePrefix(e.BuildEventContext, e.Timestamp, false); WriteProperties(propertyList); ShownBuildEventContext(e.BuildEventContext); @@ -636,9 +655,13 @@ internal override void OutputProperties(ArrayList list) /// List of items internal void WriteItems(BuildEventArgs e, IEnumerable items) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } + SortedList itemList = ExtractItemList(items); - + // if there are no Items to display return out of the method and dont print out anything related to displaying // the items, this includes the multiproc prefix information or the Initial items header if (itemList.Count == 0) @@ -659,7 +682,7 @@ internal override void OutputItems(string itemType, ArrayList itemTypeList) string itemString = null; if (!haveWrittenItemType) { - itemString=itemType; + itemString = itemType; setColor(ConsoleColor.DarkGray); WriteMessageAligned(itemType, false); haveWrittenItemType = true; @@ -669,7 +692,7 @@ internal override void OutputItems(string itemType, ArrayList itemTypeList) // Indent the text by two tab lengths StringBuilder result = new StringBuilder(); result.Append(' ', 2 * tabWidth).Append(item.ItemSpec); - WriteMessageAligned(result.ToString() , false); + WriteMessageAligned(result.ToString(), false); } resetColor(); } @@ -681,7 +704,7 @@ internal override void OutputItems(string itemType, ArrayList itemTypeList) public override void TargetStartedHandler(object sender, TargetStartedEventArgs e) { ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); - + // Add the target started information to the buildEventManager so its information can be used // later in the build buildEventManager.AddTargetStartedEvent(e); @@ -838,7 +861,7 @@ public override void ErrorHandler(object sender, BuildErrorEventArgs e) { targetStartedEvent.ErrorInTarget = true; } - + DisplayDeferredStartedEvents(e.BuildEventContext); // Display only if showOnlyWarnings is false; @@ -917,7 +940,10 @@ public override void WarningHandler(object sender, BuildWarningEventArgs e) /// public override void MessageHandler(object sender, BuildMessageEventArgs e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); bool print = false; @@ -957,8 +983,8 @@ public override void MessageHandler(object sender, BuildMessageEventArgs e) // If the event has a valid Project contextId but the project started event has not been fired, the message needs to be // buffered until the project started event is fired if ( - hasBuildStarted - && e.BuildEventContext.ProjectContextId != BuildEventContext.InvalidProjectContextId + hasBuildStarted + && e.BuildEventContext.ProjectContextId != BuildEventContext.InvalidProjectContextId && buildEventManager.GetProjectStartedEvent(e.BuildEventContext) == null && IsVerbosityAtLeast(LoggerVerbosity.Normal) ) @@ -987,7 +1013,10 @@ public override void MessageHandler(object sender, BuildMessageEventArgs e) private void DisplayDeferredStartedEvents(BuildEventContext e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } // Display any project started events which were deferred until a visible // message from their project is displayed @@ -1021,9 +1050,9 @@ private void PrintMessage(BuildMessageEventArgs e, bool lightenText) { setColor(ConsoleColor.DarkGray); } - + PrintTargetNamePerMessage(e, lightenText); - + // On diagnostic or if showEventId is set the task message should also display the taskId to assist debugging if ((IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || showEventId) && e.BuildEventContext.TaskId != BuildEventContext.InvalidTaskId) { @@ -1052,57 +1081,57 @@ private void PrintMessage(BuildMessageEventArgs e, bool lightenText) private void PrintTargetNamePerMessage(BuildMessageEventArgs e, bool lightenText) { - // Event Context of the current message - BuildEventContext currentBuildEventContext = e.BuildEventContext; + // Event Context of the current message + BuildEventContext currentBuildEventContext = e.BuildEventContext; - // Should the target name be written before the message - bool writeTargetName = false; - string targetName = string.Empty; + // Should the target name be written before the message + bool writeTargetName = false; + string targetName = string.Empty; - // Does the context (Project, Node, Context, Target, NOT task) of the previous event match the current message - bool contextAreEqual = compareContextNodeIdTargetId.Equals(currentBuildEventContext, lastDisplayedBuildEventContext ?? null); + // Does the context (Project, Node, Context, Target, NOT task) of the previous event match the current message + bool contextAreEqual = compareContextNodeIdTargetId.Equals(currentBuildEventContext, lastDisplayedBuildEventContext ?? null); - TargetStartedEventMinimumFields targetStartedEvent = null; - // If the previous event does not have the same target context information, the target name needs to be printed to the console - // to give the message some more contextual information - if (!contextAreEqual) + TargetStartedEventMinimumFields targetStartedEvent = null; + // If the previous event does not have the same target context information, the target name needs to be printed to the console + // to give the message some more contextual information + if (!contextAreEqual) + { + targetStartedEvent = buildEventManager.GetTargetStartedEvent(currentBuildEventContext); + // Some messages such as engine messages will not have a target started event, in their case, dont print the targetName + if (targetStartedEvent != null) { - targetStartedEvent = buildEventManager.GetTargetStartedEvent(currentBuildEventContext); - // Some messages such as engine messages will not have a target started event, in their case, dont print the targetName - if (targetStartedEvent != null) - { - targetName = targetStartedEvent.TargetName; - writeTargetName = true; - } + targetName = targetStartedEvent.TargetName; + writeTargetName = true; + } + } + else + { + writeTargetName = false; + } + + if (writeTargetName) + { + bool prefixAlreadyWritten = WriteTargetMessagePrefix(e, targetStartedEvent.ProjectBuildEventContext, targetStartedEvent.TimeStamp); + + setColor(ConsoleColor.Cyan); + if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || showEventId) + { + WriteMessageAligned(ResourceUtilities.FormatResourceString("TargetMessageWithId", targetName, e.BuildEventContext.TargetId), prefixAlreadyWritten); } else { - writeTargetName = false; + WriteMessageAligned(targetName + ":", prefixAlreadyWritten); } - if (writeTargetName) + if (lightenText) { - bool prefixAlreadyWritten = WriteTargetMessagePrefix(e, targetStartedEvent.ProjectBuildEventContext, targetStartedEvent.TimeStamp); - - setColor(ConsoleColor.Cyan); - if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || showEventId) - { - WriteMessageAligned(ResourceUtilities.FormatResourceString("TargetMessageWithId", targetName, e.BuildEventContext.TargetId), prefixAlreadyWritten); - } - else - { - WriteMessageAligned(targetName + ":", prefixAlreadyWritten); - } - - if (lightenText) - { - setColor(ConsoleColor.DarkGray); - } - else - { - resetColor(); - } + setColor(ConsoleColor.DarkGray); } + else + { + resetColor(); + } + } } private bool WriteTargetMessagePrefix(BuildEventArgs e, BuildEventContext context, DateTime timeStamp) @@ -1208,7 +1237,10 @@ private void WriteBasedOnPrefix(string nonNullMessage, bool prefixAlreadyWritten /// private void DisplayDeferredTargetStartedEvent(BuildEventContext e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } // Get the deferred target started event TargetStartedEventMinimumFields targetStartedEvent = buildEventManager.GetTargetStartedEvent(e); @@ -1218,14 +1250,14 @@ private void DisplayDeferredTargetStartedEvent(BuildEventContext e) { //Since the target started event has been shows, the target finished event should also be shown targetStartedEvent.ShowTargetFinishedEvent = true; - + // If there are any other started events waiting and we are the first message, show them DisplayDeferredStartedEvents(targetStartedEvent.ProjectBuildEventContext); WriteLinePrefix(targetStartedEvent.ProjectBuildEventContext, targetStartedEvent.TimeStamp, false); - + setColor(ConsoleColor.Cyan); - + ProjectStartedEventMinimumFields startedEvent = buildEventManager.GetProjectStartedEvent(e); ErrorUtilities.VerifyThrow(startedEvent != null, "Project Started should not be null in deferred target started"); string currentProjectFile = startedEvent.ProjectFile ?? string.Empty; @@ -1233,7 +1265,7 @@ private void DisplayDeferredTargetStartedEvent(BuildEventContext e) string targetName; if (IsVerbosityAtLeast(LoggerVerbosity.Diagnostic) || showEventId) { - targetName = ResourceUtilities.FormatResourceString("TargetMessageWithId", targetStartedEvent.TargetName, targetStartedEvent.ProjectBuildEventContext.TargetId); + targetName = ResourceUtilities.FormatResourceString("TargetMessageWithId", targetStartedEvent.TargetName, targetStartedEvent.ProjectBuildEventContext.TargetId); } else { @@ -1259,7 +1291,10 @@ private void DisplayDeferredTargetStartedEvent(BuildEventContext e) /// private void DisplayDeferredProjectStartedEvent(BuildEventContext e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } if (!SkipProjectStartedText) { @@ -1327,7 +1362,10 @@ private void DisplayDeferredProjectStartedEvent(BuildEventContext e) /// public override void CustomEventHandler(object sender, CustomBuildEventArgs e) { - if (showOnlyErrors || showOnlyWarnings) return; + if (showOnlyErrors || showOnlyWarnings) + { + return; + } ErrorUtilities.VerifyThrowArgumentNull(e.BuildEventContext, "BuildEventContext"); if (IsVerbosityAtLeast(LoggerVerbosity.Detailed)) @@ -1410,14 +1448,14 @@ private ProjectFullKey GetFullProjectKey(BuildEventContext e) return new ProjectFullKey(startedEvent.ProjectKey, startedEvent.EntryPointKey); } } - + /// /// Returns a performance counter for a given scope (either task name or target name) /// from the given table. /// /// Task name or target name. /// Table that has tasks or targets. - internal new static MPPerformanceCounter GetPerformanceCounter(string scopeName, ref Hashtable table) + internal static new MPPerformanceCounter GetPerformanceCounter(string scopeName, ref Hashtable table) { // Lazily construct the performance counter table. if (table == null) diff --git a/src/Deprecated/Engine/Logging/ParallelLogger/ParallelLoggerHelpers.cs b/src/Deprecated/Engine/Logging/ParallelLogger/ParallelLoggerHelpers.cs index 8470aca7630..a14b5902881 100644 --- a/src/Deprecated/Engine/Logging/ParallelLogger/ParallelLoggerHelpers.cs +++ b/src/Deprecated/Engine/Logging/ParallelLogger/ParallelLoggerHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -174,7 +174,7 @@ internal string[] ProjectCallStackFromProject(BuildEventContext e) internal ProjectStartedEventMinimumFields GetProjectStartedEvent(BuildEventContext e) { ProjectStartedEventMinimumFields buildEvent; - if ( projectStartedEvents.ContainsKey(e) ) + if (projectStartedEvents.ContainsKey(e)) { buildEvent = projectStartedEvents[e]; } @@ -191,7 +191,7 @@ internal ProjectStartedEventMinimumFields GetProjectStartedEvent(BuildEventConte internal TargetStartedEventMinimumFields GetTargetStartedEvent(BuildEventContext e) { TargetStartedEventMinimumFields buildEvent; - if ( targetStartedEvents.ContainsKey(e)) + if (targetStartedEvents.ContainsKey(e)) { buildEvent = targetStartedEvents[e]; } @@ -560,7 +560,7 @@ public override bool Equals(object obj) { return false; } - return eventComparer.Equals(entryPointContext, key.EntryPointContext) && (String.Equals(targetName, key.TargetName, StringComparison.OrdinalIgnoreCase)); + return eventComparer.Equals(entryPointContext, key.EntryPointContext) && (String.Equals(targetName, key.TargetName, StringComparison.OrdinalIgnoreCase)); } public override int GetHashCode() @@ -607,7 +607,7 @@ internal ProjectFullKey(int projectKey, int entryPointKey) /// /// Output the projectKey or the projectKey and the entrypointKey depending on the verbosity level of the logger /// - + public string ToString(LoggerVerbosity verbosity) { string fullProjectKey; diff --git a/src/Deprecated/Engine/Logging/SerialConsoleLogger.cs b/src/Deprecated/Engine/Logging/SerialConsoleLogger.cs index 7fc7d154a32..607b952275c 100644 --- a/src/Deprecated/Engine/Logging/SerialConsoleLogger.cs +++ b/src/Deprecated/Engine/Logging/SerialConsoleLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -183,7 +183,10 @@ public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs /// private void ShowErrorWarningSummary() { - if (warningCount == 0 && errorCount == 0) return; + if (warningCount == 0 && errorCount == 0) + { + return; + } // Make some effort to distinguish the summary from the previous output WriteNewLine(); @@ -191,7 +194,7 @@ private void ShowErrorWarningSummary() if (warningCount > 0) { setColor(ConsoleColor.Yellow); - foreach(BuildWarningEventArgs warningEventArgs in warningList) + foreach (BuildWarningEventArgs warningEventArgs in warningList) { WriteLinePretty(EventArgsFormatting.FormatEventMessage(warningEventArgs, runningWithCharacterFileType)); } diff --git a/src/Deprecated/Engine/Properties/BuildProperty.cs b/src/Deprecated/Engine/Properties/BuildProperty.cs index 6d1d947f2e5..34990b9cc8d 100644 --- a/src/Deprecated/Engine/Properties/BuildProperty.cs +++ b/src/Deprecated/Engine/Properties/BuildProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -116,7 +116,7 @@ internal void WriteToStream(BinaryWriter writer) else { writer.Write((byte)0); - writer.Write(finalValueEscaped); + writer.Write(finalValueEscaped); } writer.Write((Int32)type); } @@ -181,8 +181,8 @@ internal static void ClearInternTable() /// rgoel internal BuildProperty ( - XmlElement propertyElement, - PropertyType propertyType + XmlElement propertyElement, + PropertyType propertyType ) : this(propertyElement, propertyElement != null ? Utilities.GetXmlNodeInnerContents(propertyElement) : null, @@ -425,7 +425,9 @@ internal void SetValue(string value) // NO OP if the value we set is the same we already have // This will prevent making the project dirty if (value == this.propertyValue) + { return; + } // NOTE: allow output properties to be modified -- they're just like normal properties (except for their // precedence), and it doesn't really matter if they are modified, since they are transient (virtual) @@ -577,7 +579,7 @@ internal BuildPropertyGroup ParentPersistedPropertyGroup set { - ErrorUtilities.VerifyThrow( ((value == null) && (this.parentPersistedPropertyGroup != null)) || ((value != null) && (this.parentPersistedPropertyGroup == null)), + ErrorUtilities.VerifyThrow(((value == null) && (this.parentPersistedPropertyGroup != null)) || ((value != null) && (this.parentPersistedPropertyGroup == null)), "Either new parent cannot be assigned because we already have a parent, or old parent cannot be removed because none exists."); this.parentPersistedPropertyGroup = value; @@ -697,9 +699,9 @@ BuildProperty compareToProperty return (compareToProperty != null) && (String.Equals(compareToProperty.propertyName, this.propertyName, StringComparison.OrdinalIgnoreCase)) && - (compareToProperty.propertyValue == this.propertyValue) && - (compareToProperty.FinalValue == this.FinalValue) && - (compareToProperty.type == this.type); + (compareToProperty.propertyValue == this.propertyValue) && + (compareToProperty.FinalValue == this.FinalValue) && + (compareToProperty.type == this.type); } /// @@ -710,7 +712,7 @@ public override string ToString ( ) { - return (string) this; + return (string)this; } #endregion diff --git a/src/Deprecated/Engine/Properties/BuildPropertyGroup.cs b/src/Deprecated/Engine/Properties/BuildPropertyGroup.cs index 672eaee766f..8a6481c2675 100644 --- a/src/Deprecated/Engine/Properties/BuildPropertyGroup.cs +++ b/src/Deprecated/Engine/Properties/BuildPropertyGroup.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -251,7 +251,7 @@ internal BuildPropertyGroup(Project parentProject, XmlElement propertyGroupEleme { // Handle XML comments under the node (just ignore them). case XmlNodeType.Comment: - // fall through + // fall through case XmlNodeType.Whitespace: // ignore whitespace break; @@ -443,7 +443,7 @@ internal XmlElement ParentElement { if (this.propertyGroupElement.ParentNode is XmlElement) { - return (XmlElement) this.propertyGroupElement.ParentNode; + return (XmlElement)this.propertyGroupElement.ParentNode; } } @@ -491,11 +491,20 @@ internal string ImportedFromFilename get { if (!this.importedFromAnotherProject) + { return string.Empty; + } + if (this.importedFromFilename != null) + { return this.importedFromFilename; + } + if (this.PropertyGroupElement != null) + { return XmlUtilities.GetXmlNodeFile(this.PropertyGroupElement, string.Empty); + } + ErrorUtilities.VerifyThrow(false, "BuildPropertyGroup is imported, doesn't have an ownerDocument, and importedFilename is null."); return string.Empty; } diff --git a/src/Deprecated/Engine/Properties/BuildPropertyGroupCollection.cs b/src/Deprecated/Engine/Properties/BuildPropertyGroupCollection.cs index 40da4c5f1e2..b5b6abd506c 100644 --- a/src/Deprecated/Engine/Properties/BuildPropertyGroupCollection.cs +++ b/src/Deprecated/Engine/Properties/BuildPropertyGroupCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Deprecated/Engine/Properties/BuildPropertyGroupProxy.cs b/src/Deprecated/Engine/Properties/BuildPropertyGroupProxy.cs index 46109721ae2..e0286ea54ba 100644 --- a/src/Deprecated/Engine/Properties/BuildPropertyGroupProxy.cs +++ b/src/Deprecated/Engine/Properties/BuildPropertyGroupProxy.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -21,7 +21,7 @@ internal class BuildPropertyGroupProxy : IEnumerable private BuildPropertyGroup backingPropertyGroup; private BuildPropertyGroupProxy() - { + { // Do nothing } diff --git a/src/Deprecated/Engine/Resources/AssemblyResources.cs b/src/Deprecated/Engine/Resources/AssemblyResources.cs index 294e3b103f4..d6601ae9317 100644 --- a/src/Deprecated/Engine/Resources/AssemblyResources.cs +++ b/src/Deprecated/Engine/Resources/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; @@ -11,7 +11,7 @@ namespace Microsoft.Build.BuildEngine.Shared /// This class provides access to the assembly's resources. /// /// SumedhK - static internal class AssemblyResources + internal static class AssemblyResources { /// /// A slot for msbuild.exe to add a resource manager over its own resources, that can also be consulted. @@ -98,7 +98,7 @@ private static string GetStringFromMSBuildExeResources(string name) // Try MSBuild.exe's resources resource = msbuildExeResourceManager.GetString(name, CultureInfo.CurrentUICulture); } - + return resource; } diff --git a/src/Deprecated/Engine/Resources/Constants.cs b/src/Deprecated/Engine/Resources/Constants.cs index fa46c5249ee..dffb0f06a08 100644 --- a/src/Deprecated/Engine/Resources/Constants.cs +++ b/src/Deprecated/Engine/Resources/Constants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -14,23 +14,23 @@ namespace Microsoft.Build.BuildEngine /// RGoel internal static class ReservedPropertyNames { - internal const string projectDirectory = "MSBuildProjectDirectory"; - internal const string projectDirectoryNoRoot = "MSBuildProjectDirectoryNoRoot"; - internal const string projectFile = "MSBuildProjectFile"; - internal const string projectExtension = "MSBuildProjectExtension"; - internal const string projectFullPath = "MSBuildProjectFullPath"; - internal const string projectName = "MSBuildProjectName"; - internal const string binPath = "MSBuildBinPath"; - internal const string projectDefaultTargets = "MSBuildProjectDefaultTargets"; - internal const string extensionsPath = "MSBuildExtensionsPath"; - internal const string extensionsPath32 = "MSBuildExtensionsPath32"; - internal const string toolsPath = "MSBuildToolsPath"; - internal const string toolsVersion = "MSBuildToolsVersion"; - internal const string startupDirectory = "MSBuildStartupDirectory"; - internal const string buildNodeCount = "MSBuildNodeCount"; - internal const string extensionsPathSuffix = "MSBuild"; - internal const string programFiles32 = "MSBuildProgramFiles32"; - internal const string assemblyVersion = "MSBuildAssemblyVersion"; + internal const string projectDirectory = "MSBuildProjectDirectory"; + internal const string projectDirectoryNoRoot = "MSBuildProjectDirectoryNoRoot"; + internal const string projectFile = "MSBuildProjectFile"; + internal const string projectExtension = "MSBuildProjectExtension"; + internal const string projectFullPath = "MSBuildProjectFullPath"; + internal const string projectName = "MSBuildProjectName"; + internal const string binPath = "MSBuildBinPath"; + internal const string projectDefaultTargets = "MSBuildProjectDefaultTargets"; + internal const string extensionsPath = "MSBuildExtensionsPath"; + internal const string extensionsPath32 = "MSBuildExtensionsPath32"; + internal const string toolsPath = "MSBuildToolsPath"; + internal const string toolsVersion = "MSBuildToolsVersion"; + internal const string startupDirectory = "MSBuildStartupDirectory"; + internal const string buildNodeCount = "MSBuildNodeCount"; + internal const string extensionsPathSuffix = "MSBuild"; + internal const string programFiles32 = "MSBuildProgramFiles32"; + internal const string assemblyVersion = "MSBuildAssemblyVersion"; /// /// Indicates if the given property is a reserved property. @@ -73,7 +73,7 @@ internal static class Constants /// internal const string defaultFallbackToolsVersion = "4.0"; - + internal const string defaultSolutionWrapperProjectToolsVersion = "4.0"; /// diff --git a/src/Deprecated/Engine/Shared/AssemblyLoadInfo.cs b/src/Deprecated/Engine/Shared/AssemblyLoadInfo.cs index cf9e5f80249..51120f353b7 100644 --- a/src/Deprecated/Engine/Shared/AssemblyLoadInfo.cs +++ b/src/Deprecated/Engine/Shared/AssemblyLoadInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -101,7 +101,7 @@ public override int GetHashCode() /// /// /// RGoel - public override bool Equals(Object obj) + public override bool Equals(Object obj) { if (obj == null) { @@ -109,7 +109,7 @@ public override bool Equals(Object obj) } AssemblyLoadInfo otherAssemblyInfo = obj as AssemblyLoadInfo; - + if (otherAssemblyInfo == null) { return false; diff --git a/src/Deprecated/Engine/Shared/AssemblyNameExtension.cs b/src/Deprecated/Engine/Shared/AssemblyNameExtension.cs index 1cac0aa734f..d4fda64c5ba 100644 --- a/src/Deprecated/Engine/Shared/AssemblyNameExtension.cs +++ b/src/Deprecated/Engine/Shared/AssemblyNameExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -17,12 +17,12 @@ namespace Microsoft.Build.BuildEngine.Shared /// between the two is done lazily on demand. /// [Serializable] - sealed internal class AssemblyNameExtension + internal sealed class AssemblyNameExtension { private AssemblyName asAssemblyName = null; private string asString = null; - static private AssemblyNameExtension unnamedAssembly = new AssemblyNameExtension(); + private static AssemblyNameExtension unnamedAssembly = new AssemblyNameExtension(); /// /// Construct an unnamed assembly. @@ -62,7 +62,7 @@ internal AssemblyNameExtension(string assemblyName) /// Used when the assembly name comes from a user-controlled source like a project file or config file. /// Does extra checking on the assembly name and will throw exceptions if something is invalid. /// - internal AssemblyNameExtension(string assemblyName, bool validate) + internal AssemblyNameExtension(string assemblyName, bool validate) { asString = assemblyName; @@ -87,7 +87,7 @@ internal static AssemblyNameExtension GetAssemblyNameEx(string path) } return new AssemblyNameExtension(assemblyName); } - + /// /// Assume there is a string version, create the AssemblyName version. /// @@ -247,7 +247,7 @@ internal int CompareTo(AssemblyNameExtension that) /// Get a hash code for this assembly name. /// /// - new internal int GetHashCode() + internal new int GetHashCode() { // Ok, so this isn't a great hashing algorithm. However, basenames with different // versions or PKTs are relatively uncommon and so collisions should be low. @@ -348,7 +348,7 @@ private static int CompareBaseNamesStringWise(string asString1, string asString2 } // If the lengths are the same then we can compare without copying. - if (baseLenThis == baseLenThat) + if (baseLenThis == baseLenThat) { return String.Compare(asString1, 0, asString2, 0, baseLenThis, StringComparison.OrdinalIgnoreCase); } @@ -356,7 +356,7 @@ private static int CompareBaseNamesStringWise(string asString1, string asString2 // Lengths are different, so string copy is required. string nameThis = asString1.Substring(0, baseLenThis); string nameThat = asString2.Substring(0, baseLenThat); - return String.Compare(nameThis, nameThat, StringComparison.OrdinalIgnoreCase); + return String.Compare(nameThis, nameThat, StringComparison.OrdinalIgnoreCase); } /// @@ -392,7 +392,7 @@ internal bool Equals(AssemblyNameExtension that) // If they weren't identical then they might still differ only by // case. So we can't assume that they don't match. So fall through... - + } // Do the names match? @@ -500,7 +500,7 @@ internal static string EscapeDisplayNameCharacters(string displayName) /// Convert to a string for display. /// /// - override public string ToString() + public override string ToString() { CreateFullName(); return this.asString; diff --git a/src/Deprecated/Engine/Shared/BuildEventFileInfo.cs b/src/Deprecated/Engine/Shared/BuildEventFileInfo.cs index 372d9cf2e67..7dc0de6c962 100644 --- a/src/Deprecated/Engine/Shared/BuildEventFileInfo.cs +++ b/src/Deprecated/Engine/Shared/BuildEventFileInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Deprecated/Engine/Shared/ConfigurationInSolution.cs b/src/Deprecated/Engine/Shared/ConfigurationInSolution.cs index 5f77245afff..7541e3c074e 100644 --- a/src/Deprecated/Engine/Shared/ConfigurationInSolution.cs +++ b/src/Deprecated/Engine/Shared/ConfigurationInSolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; diff --git a/src/Deprecated/Engine/Shared/ConversionUtilities.cs b/src/Deprecated/Engine/Shared/ConversionUtilities.cs index faa3cc499c3..454cda81a46 100644 --- a/src/Deprecated/Engine/Shared/ConversionUtilities.cs +++ b/src/Deprecated/Engine/Shared/ConversionUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -12,7 +12,7 @@ namespace Microsoft.Build.BuildEngine.Shared /// This class contains only static methods, which are useful throughout many /// of the MSBuild classes and don't really belong in any specific class. /// - internal static class ConversionUtilities + internal static class ConversionUtilities { /// /// Converts a string to a bool. We consider "true/false", "on/off", and diff --git a/src/Deprecated/Engine/Shared/Delegate.cs b/src/Deprecated/Engine/Shared/Delegate.cs index 26f42a67b90..9721c12bbac 100644 --- a/src/Deprecated/Engine/Shared/Delegate.cs +++ b/src/Deprecated/Engine/Shared/Delegate.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine.Shared { diff --git a/src/Deprecated/Engine/Shared/ErrorUtilities.cs b/src/Deprecated/Engine/Shared/ErrorUtilities.cs index 1af0f4ceb05..359b726d9ab 100644 --- a/src/Deprecated/Engine/Shared/ErrorUtilities.cs +++ b/src/Deprecated/Engine/Shared/ErrorUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Deprecated/Engine/Shared/EscapingUtilities.cs b/src/Deprecated/Engine/Shared/EscapingUtilities.cs index d339c3e0492..ce1ae808288 100644 --- a/src/Deprecated/Engine/Shared/EscapingUtilities.cs +++ b/src/Deprecated/Engine/Shared/EscapingUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -12,7 +12,7 @@ namespace Microsoft.Build.BuildEngine.Shared /// in the MSBuild file format. /// /// RGoel - static internal class EscapingUtilities + internal static class EscapingUtilities { /// /// Replaces all instances of %XX in the input string with the character represented @@ -64,7 +64,7 @@ out bool escapingWasNecessary { // There must be two hex characters following the percent sign // for us to even consider doing anything with this. - if ( + if ( (indexOfPercent <= (escapedString.Length - 3)) && Uri.IsHexDigit(escapedString[indexOfPercent + 1]) && Uri.IsHexDigit(escapedString[indexOfPercent + 2]) @@ -76,7 +76,7 @@ out bool escapingWasNecessary // Convert the %XX to an actual real character. string hexString = escapedString.Substring(indexOfPercent + 1, 2); - char unescapedCharacter = (char) int.Parse(hexString, System.Globalization.NumberStyles.HexNumber, + char unescapedCharacter = (char)int.Parse(hexString, System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); // if the unescaped character is not on the exception list, append it @@ -164,7 +164,7 @@ string escapedString if (-1 != escapedString.IndexOf('%')) { // It has a '%' sign. We have promise. - if ( + if ( (-1 != escapedString.IndexOf("%2", StringComparison.Ordinal)) || (-1 != escapedString.IndexOf("%3", StringComparison.Ordinal)) ) diff --git a/src/Deprecated/Engine/Shared/EventArgsFormatting.cs b/src/Deprecated/Engine/Shared/EventArgsFormatting.cs index 5e4fa1fe365..955a9c7e289 100644 --- a/src/Deprecated/Engine/Shared/EventArgsFormatting.cs +++ b/src/Deprecated/Engine/Shared/EventArgsFormatting.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Deprecated/Engine/Shared/ExceptionHandling.cs b/src/Deprecated/Engine/Shared/ExceptionHandling.cs index f1d72ddd637..1b51a59b06e 100644 --- a/src/Deprecated/Engine/Shared/ExceptionHandling.cs +++ b/src/Deprecated/Engine/Shared/ExceptionHandling.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -26,7 +26,7 @@ internal static bool IsCriticalException(Exception e) e is StackOverflowException || e is OutOfMemoryException || e is AccessViolationException - // ExecutionEngineException has been deprecated by the CLR + // ExecutionEngineException has been deprecated by the CLR ) { return true; diff --git a/src/Deprecated/Engine/Shared/FileMatcher.cs b/src/Deprecated/Engine/Shared/FileMatcher.cs index 3292f664426..4d3757b8a3a 100644 --- a/src/Deprecated/Engine/Shared/FileMatcher.cs +++ b/src/Deprecated/Engine/Shared/FileMatcher.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -17,8 +17,8 @@ internal static class FileMatcher { private const string recursiveDirectoryMatch = "**"; private const string dotdot = ".."; - private static readonly string directorySeparator = new string(Path.DirectorySeparatorChar,1); - private static readonly string altDirectorySeparator = new string(Path.AltDirectorySeparatorChar,1); + private static readonly string directorySeparator = new string(Path.DirectorySeparatorChar, 1); + private static readonly string altDirectorySeparator = new string(Path.AltDirectorySeparatorChar, 1); private static readonly char[] wildcardCharacters = { '*', '?' }; internal static readonly char[] directorySeparatorCharacters = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; @@ -143,7 +143,7 @@ private static string[] GetAccessibleFiles string path, string filespec, // can be null string projectDirectory, - bool stripProjectDirectory + bool stripProjectDirectory ) { try @@ -299,7 +299,7 @@ GetFileSystemEntries getFileSystemEntries // If there is a zero-length part, then that means there was an extra slash. if (parts[i].Length == 0) { - longParts[i-startingElement] = String.Empty; + longParts[i - startingElement] = String.Empty; } else { @@ -318,7 +318,7 @@ GetFileSystemEntries getFileSystemEntries { // The next part doesn't exist. Therefore, no more of the path will exist. // Just return the rest. - for (int j = i; j @@ -446,9 +446,9 @@ out string filenamePart */ // We know the fixed director part now. - fixedDirectoryPart = filespec.Substring (0, indexOfLastDirectorySeparator + 1); + fixedDirectoryPart = filespec.Substring(0, indexOfLastDirectorySeparator + 1); wildcardDirectoryPart = String.Empty; - filenamePart = filespec.Substring (indexOfLastDirectorySeparator + 1); + filenamePart = filespec.Substring(indexOfLastDirectorySeparator + 1); return; } @@ -469,17 +469,17 @@ out string filenamePart * dir?\** */ fixedDirectoryPart = String.Empty; - wildcardDirectoryPart = filespec.Substring (0, indexOfLastDirectorySeparator + 1); - filenamePart = filespec.Substring (indexOfLastDirectorySeparator + 1); + wildcardDirectoryPart = filespec.Substring(0, indexOfLastDirectorySeparator + 1); + filenamePart = filespec.Substring(indexOfLastDirectorySeparator + 1); return; } /* * There is at least one wildcard and one dir separator, split parts out. */ - fixedDirectoryPart = filespec.Substring(0, indexOfSeparatorBeforeWildCard+1); - wildcardDirectoryPart = filespec.Substring(indexOfSeparatorBeforeWildCard+1, indexOfLastDirectorySeparator-indexOfSeparatorBeforeWildCard); - filenamePart = filespec.Substring(indexOfLastDirectorySeparator+1); + fixedDirectoryPart = filespec.Substring(0, indexOfSeparatorBeforeWildCard + 1); + wildcardDirectoryPart = filespec.Substring(indexOfSeparatorBeforeWildCard + 1, indexOfLastDirectorySeparator - indexOfSeparatorBeforeWildCard); + filenamePart = filespec.Substring(indexOfLastDirectorySeparator + 1); } /// @@ -491,7 +491,7 @@ private static void RemoveInitialDotSlash string[] paths ) { - for (int i=0; i < paths.Length; i++) + for (int i = 0; i < paths.Length; i++) { if (paths[i].StartsWith(".\\", StringComparison.Ordinal)) { @@ -500,7 +500,7 @@ string[] paths } } - + /// /// Checks if the char is a DirectorySeparatorChar or a AltDirectorySeparatorChar /// @@ -522,7 +522,7 @@ string projectDirectory ) { bool directoryLastCharIsSeparator = IsDirectorySeparator(projectDirectory[projectDirectory.Length - 1]); - for (int i = 0; i < paths.Length; i++) + for (int i = 0; i < paths.Length; i++) { if (paths[i].StartsWith(projectDirectory, StringComparison.Ordinal)) { @@ -567,7 +567,7 @@ private static void GetFilesRecursive Regex regexFileMatch, // can be null bool needsRecursion, string projectDirectory, - bool stripProjectDirectory, + bool stripProjectDirectory, GetFileSystemEntries getFileSystemEntries ) { @@ -577,7 +577,7 @@ GetFileSystemEntries getFileSystemEntries ErrorUtilities.VerifyThrow((filespec != null) || (regexFileMatch != null), "Need either a file-spec or a regular expression to match files."); - ErrorUtilities.VerifyThrow(remainingWildcardDirectory!=null, "Expected non-null remaning wildcard directory."); + ErrorUtilities.VerifyThrow(remainingWildcardDirectory != null, "Expected non-null remaning wildcard directory."); /* * Get the matching files. @@ -621,7 +621,7 @@ GetFileSystemEntries getFileSystemEntries /* * Recurse into subdirectories. */ - if (needsRecursion && remainingWildcardDirectory.Length>0) + if (needsRecursion && remainingWildcardDirectory.Length > 0) { // Find the next directory piece. string pattern = null; @@ -1153,7 +1153,7 @@ DirectoryExists directoryExists * might potentially do a lot of that. */ System.Collections.ArrayList arrayListOfFiles = new System.Collections.ArrayList(); - System.Collections.IList listOfFiles = (System.Collections.IList) arrayListOfFiles; + System.Collections.IList listOfFiles = (System.Collections.IList)arrayListOfFiles; /* * Analyze the file spec and get the information we need to do the matching. @@ -1226,7 +1226,7 @@ DirectoryExists directoryExists (wildcardDirectoryPart.Length > 0) && // the specification is not a simple "**" (wildcardDirectoryPart != (recursiveDirectoryMatch + directorySeparator)); - // then we need to use the regular expression + // then we need to use the regular expression // if we're not using the regular expression, get the file pattern extension string extensionPart = matchWithRegex diff --git a/src/Deprecated/Engine/Shared/FileUtilities.cs b/src/Deprecated/Engine/Shared/FileUtilities.cs index a86d5e08b5a..077f878c844 100644 --- a/src/Deprecated/Engine/Shared/FileUtilities.cs +++ b/src/Deprecated/Engine/Shared/FileUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -17,7 +17,7 @@ namespace Microsoft.Build.BuildEngine.Shared /// each class get pulled into the resulting assembly. /// /// SumedhK - static internal class FileUtilities + internal static class FileUtilities { #region Item-spec modifiers @@ -25,7 +25,7 @@ static internal class FileUtilities /// Encapsulates the definitions of the item-spec modifiers a.k.a. reserved item metadata. /// /// SumedhK - static internal class ItemSpecModifiers + internal static class ItemSpecModifiers { // NOTE: If you add an item here that starts with a new letter, you need to update the case // statements in IsItemSpecModifier and IsDerivableItemSpecModifier. @@ -109,7 +109,7 @@ internal static bool IsItemSpecModifier(string name) * therefore is not an item spec modifier. * */ - switch (name.Length) + switch (name.Length) { case 7: // RootDir switch (name[0]) @@ -122,12 +122,12 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'r': + case 'r': break; } break; case 8: // FullPath, Filename, Identity - + switch (name[0]) { default: @@ -150,7 +150,7 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'i': + case 'i': break; } break; @@ -165,7 +165,7 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'd': + case 'd': break; case 'E': // Extension if (name == ItemSpecModifiers.Extension) @@ -173,9 +173,9 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'e': + case 'e': break; - } + } break; case 11: // RelativeDir, CreatedTime switch (name[0]) @@ -196,10 +196,10 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'r': + case 'r': break; } - break; + break; case 12: // RecursiveDir, ModifiedTime, AccessedTime switch (name[0]) @@ -212,7 +212,7 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'a': + case 'a': break; case 'M': // ModifiedTime if (name == ItemSpecModifiers.ModifiedTime) @@ -220,7 +220,7 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'm': + case 'm': break; case 'R': // RecursiveDir if (name == ItemSpecModifiers.RecursiveDir) @@ -228,7 +228,7 @@ internal static bool IsItemSpecModifier(string name) return true; } break; - case 'r': + case 'r': break; } break; @@ -236,7 +236,7 @@ internal static bool IsItemSpecModifier(string name) // Not the right length for a match. return false; } - + // Could still be a case-insensitive match. bool result = ItemSpecModifiers.TableOfItemSpecModifiers.ContainsKey(name); @@ -266,7 +266,7 @@ internal static bool IsDerivableItemSpecModifier(string name) } return isItemSpecModifier; - } + } /// /// Performs path manipulations on the given item-spec as directed. @@ -485,7 +485,10 @@ internal static string GetItemSpecModifier(string currentDirectory, string itemS catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } + ErrorUtilities.VerifyThrowInvalidOperation(false, "Shared.InvalidFilespecForTransform", modifier, itemSpec, e.Message); } @@ -497,7 +500,7 @@ internal static string GetItemSpecModifier(string currentDirectory, string itemS if (cachedModifiers == null) { cachedModifiers = new Hashtable(StringComparer.OrdinalIgnoreCase); - + // mark the cache to indicate the item-spec for which it was created // NOTE: we've intentionally picked a key here that will never conflict with any modifier name -- if we // use the item-spec as the key, it's possible for it to conflict with the name of a modifier @@ -733,7 +736,9 @@ internal static FileInfo GetFileInfoNoThrow(string filePath) catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } // Invalid or inaccessible path: treat as if nonexistent file, just as File.Exists does return null; diff --git a/src/Deprecated/Engine/Shared/FileUtilitiesRegex.cs b/src/Deprecated/Engine/Shared/FileUtilitiesRegex.cs index 493d9ebbbc6..7561372e55a 100644 --- a/src/Deprecated/Engine/Shared/FileUtilitiesRegex.cs +++ b/src/Deprecated/Engine/Shared/FileUtilitiesRegex.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Deprecated/Engine/Shared/FrameworkLocationHelper.cs b/src/Deprecated/Engine/Shared/FrameworkLocationHelper.cs index 20c1c45cb27..2d2b3ee0024 100644 --- a/src/Deprecated/Engine/Shared/FrameworkLocationHelper.cs +++ b/src/Deprecated/Engine/Shared/FrameworkLocationHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -42,7 +42,7 @@ internal static class FrameworkLocationHelper internal const string dotNetFrameworkVersionFolderPrefixV30 = "v3.0"; // v3.0 is for WinFx. private const string dotNetFrameworkVersionV30 = "v3.0"; // full WinFx version to pass to NativeMethodsShared.GetRequestedRuntimeInfo(). private const string dotNetFrameworkAssemblyFoldersRegistryKeyV30 = dotNetFrameworkAssemblyFoldersRegistryPath + "\\" + dotNetFrameworkVersionFolderPrefixV30; - private const string dotNetFrameworkRegistryKeyV30 = dotNetFrameworkSetupRegistryPath + "\\" + dotNetFrameworkVersionFolderPrefixV30 +"\\Setup"; + private const string dotNetFrameworkRegistryKeyV30 = dotNetFrameworkSetupRegistryPath + "\\" + dotNetFrameworkVersionFolderPrefixV30 + "\\Setup"; private const string dotNetFrameworkSdkRegistryPathV35 = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v7.0A"; internal const string fullDotNetFrameworkSdkRegistryKeyV35 = "HKEY_LOCAL_MACHINE\\" + dotNetFrameworkSdkRegistryPathV35; @@ -357,7 +357,7 @@ internal static string PathToDotNetFrameworkReferenceAssembliesV40 if (FrameworkLocationHelper.pathToDotNetFrameworkReferenceAssembliesV40 == null) { - FrameworkLocationHelper.pathToDotNetFrameworkReferenceAssembliesV40 = GenerateReferenceAssemblyDirectory(dotNetFrameworkVersionFolderPrefixV40); + FrameworkLocationHelper.pathToDotNetFrameworkReferenceAssembliesV40 = GenerateReferenceAssemblyDirectory(dotNetFrameworkVersionFolderPrefixV40); } } @@ -448,7 +448,7 @@ string registryKeyName /// True if the registry key is 1 false if it is not there. This method also return true if the complus enviornment variables are set. internal static bool CheckForFrameworkInstallation(string registryEntryToCheckInstall, string registryValueToCheckInstall) { - // Get the complus install root and version + // Get the complus install root and version string complusInstallRoot = Environment.GetEnvironmentVariable("COMPLUS_INSTALLROOT"); string complusVersion = Environment.GetEnvironmentVariable("COMPLUS_VERSION"); diff --git a/src/Deprecated/Engine/Shared/InternalErrorException.cs b/src/Deprecated/Engine/Shared/InternalErrorException.cs index 4cef1bf4699..344c55e2fe6 100644 --- a/src/Deprecated/Engine/Shared/InternalErrorException.cs +++ b/src/Deprecated/Engine/Shared/InternalErrorException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -73,8 +73,8 @@ private InternalErrorException(SerializationInfo info, StreamingContext context) // Do nothing: no fields } - // Base implementation of GetObjectData() is sufficient; we have no fields + // Base implementation of GetObjectData() is sufficient; we have no fields #endregion - } + } } diff --git a/src/Deprecated/Engine/Shared/LoadedType.cs b/src/Deprecated/Engine/Shared/LoadedType.cs index 6cbb2758453..69a2055632a 100644 --- a/src/Deprecated/Engine/Shared/LoadedType.cs +++ b/src/Deprecated/Engine/Shared/LoadedType.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -70,7 +70,7 @@ public Dictionary GetNamesOfPropertiesWithOutputAttribute() /// property name /// PropertyInfo public PropertyInfo GetProperty(string propertyName) - { + { if (propertyInfoCache == null) { PopulatePropertyInfoCache(); diff --git a/src/Deprecated/Engine/Shared/NativeMethodsShared.cs b/src/Deprecated/Engine/Shared/NativeMethodsShared.cs index 2ca73148bb5..120a1639181 100644 --- a/src/Deprecated/Engine/Shared/NativeMethodsShared.cs +++ b/src/Deprecated/Engine/Shared/NativeMethodsShared.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -147,7 +147,7 @@ internal static extern uint GetRequestedRuntimeInfo(String pExe, /// /// Gets the fully qualified filename of the currently executing .exe /// - [DllImport(kernel32Dll, SetLastError=true, CharSet = CharSet.Unicode)] + [DllImport(kernel32Dll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length); [DllImport("kernel32.dll")] diff --git a/src/Deprecated/Engine/Shared/ProjectConfigurationInSolution.cs b/src/Deprecated/Engine/Shared/ProjectConfigurationInSolution.cs index 474f6b711d9..778606a8504 100644 --- a/src/Deprecated/Engine/Shared/ProjectConfigurationInSolution.cs +++ b/src/Deprecated/Engine/Shared/ProjectConfigurationInSolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -46,10 +46,12 @@ internal bool IncludeInBuild /// /// /// LukaszG - static private string RemoveSpaceFromAnyCpuPlatform(string platformName) + private static string RemoveSpaceFromAnyCpuPlatform(string platformName) { if (string.Equals(platformName, "Any CPU", StringComparison.OrdinalIgnoreCase)) + { return "AnyCPU"; + } return platformName; } diff --git a/src/Deprecated/Engine/Shared/ProjectErrorUtilities.cs b/src/Deprecated/Engine/Shared/ProjectErrorUtilities.cs index 187f375ce8e..775a3ed6b13 100644 --- a/src/Deprecated/Engine/Shared/ProjectErrorUtilities.cs +++ b/src/Deprecated/Engine/Shared/ProjectErrorUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; diff --git a/src/Deprecated/Engine/Shared/ProjectFileErrorUtilities.cs b/src/Deprecated/Engine/Shared/ProjectFileErrorUtilities.cs index 7f34c4a6499..52dca01cc3a 100644 --- a/src/Deprecated/Engine/Shared/ProjectFileErrorUtilities.cs +++ b/src/Deprecated/Engine/Shared/ProjectFileErrorUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine.Shared { @@ -7,7 +7,7 @@ namespace Microsoft.Build.BuildEngine.Shared /// This class contains methods that are useful for error checking and validation of project files. /// /// SumedhK - static internal class ProjectFileErrorUtilities + internal static class ProjectFileErrorUtilities { /// /// This method is used to flag errors in the project file being processed. Do NOT use this method in place of diff --git a/src/Deprecated/Engine/Shared/ProjectInSolution.cs b/src/Deprecated/Engine/Shared/ProjectInSolution.cs index c3cf27ccd70..da716c0358f 100644 --- a/src/Deprecated/Engine/Shared/ProjectInSolution.cs +++ b/src/Deprecated/Engine/Shared/ProjectInSolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -337,7 +337,7 @@ internal string GetUniqueProjectName() /// The name to be cleansed /// string /// KieranMo - static private string CleanseProjectName(string projectName) + private static string CleanseProjectName(string projectName) { ErrorUtilities.VerifyThrow(projectName != null, "Null strings not allowed."); @@ -368,7 +368,7 @@ static private string CleanseProjectName(string projectName) /// The unique name for the project /// string /// KieranMo - static internal string DisambiguateProjectTargetName(string uniqueProjectName) + internal static string DisambiguateProjectTargetName(string uniqueProjectName) { // Test our unique project name against those names that collide with Solution // entry point targets diff --git a/src/Deprecated/Engine/Shared/ProjectWriter.cs b/src/Deprecated/Engine/Shared/ProjectWriter.cs index cfd98bf6e8e..391665594f5 100644 --- a/src/Deprecated/Engine/Shared/ProjectWriter.cs +++ b/src/Deprecated/Engine/Shared/ProjectWriter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Xml; @@ -33,7 +33,7 @@ internal sealed class ProjectWriter : XmlTextWriter (?(?\s*->\s*)(?'[^']*')) (?\s*,\s*'[^']*')? (?\s*\))"; - // ) + // ) // regular expression used to match item vector transforms // internal for unit testing only @@ -112,8 +112,8 @@ internal void Initialize(XmlDocument project, XmlDeclaration projectXmlDeclarati } // don't write an XML declaration unless the project already has one or has non-default encoding - writeXmlDeclaration = - ((projectXmlDeclaration != null) || + writeXmlDeclaration = + ((projectXmlDeclaration != null) || ((documentEncoding != Encoding.UTF8) && (documentEncoding != null))); } @@ -183,7 +183,7 @@ public override void WriteString(string text) } // write the terminal piece of text after the last transform - base.WriteString(surroundingTextPieces[surroundingTextPieces.Length-1]); + base.WriteString(surroundingTextPieces[surroundingTextPieces.Length - 1]); } // if the string has no item vector transforms in it, write it out as usual else diff --git a/src/Deprecated/Engine/Shared/ResourceUtilities.cs b/src/Deprecated/Engine/Shared/ResourceUtilities.cs index 3be5976f2aa..7444182984e 100644 --- a/src/Deprecated/Engine/Shared/ResourceUtilities.cs +++ b/src/Deprecated/Engine/Shared/ResourceUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; #if !BUILDINGAPPXTASKS && DEBUG @@ -127,7 +127,7 @@ internal static string FormatString(string unformatted, params object[] args) { #if DEBUG - #if VALIDATERESOURCESTRINGS +#if VALIDATERESOURCESTRINGS // The code below reveals many places in our codebase where // we're not using all of the data given to us to format // strings -- but there are too many to presently fix. @@ -166,8 +166,8 @@ internal static string FormatString(string unformatted, params object[] args) caughtFormatException, String.Format("The provided format string '{0}' had fewer format parameters than the number of format args, '{1}'.", unformatted, args.Length) ); - #endif - +#endif + #endif // Format the string, using the variable arguments passed in. // NOTE: all String methods are thread-safe diff --git a/src/Deprecated/Engine/Shared/SolutionParser.cs b/src/Deprecated/Engine/Shared/SolutionParser.cs index 7790ff7d26e..a6847afb3f2 100644 --- a/src/Deprecated/Engine/Shared/SolutionParser.cs +++ b/src/Deprecated/Engine/Shared/SolutionParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -29,8 +29,8 @@ internal class SolutionParser ( "^" // Beginning of line + "Project\\(\"(?.*)\"\\)" - +"\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace - +"\"(?.*)\"" + + "\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace + + "\"(?.*)\"" + "\\s*,\\s*" // Any amount of whitespace plus "," plus any amount of whitespace + "\"(?.*)\"" + "\\s*,\\s*" // Any amount of whitespace plus "," plus any amount of whitespace @@ -45,13 +45,13 @@ internal class SolutionParser ( "^" // Beginning of line + "(?[^=]*)" - +"\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace - +"(?[^=]*)" + + "\\s*=\\s*" // Any amount of whitespace plus "=" plus any amount of whitespace + + "(?[^=]*)" + "$" // End-of-line ); internal const int slnFileMinUpgradableVersion = 7; // Minimum version for MSBuild to give a nice message - internal const int slnFileMinVersion = 9; // Minimum version for MSBuild to actually do anything useful + internal const int slnFileMinVersion = 9; // Minimum version for MSBuild to actually do anything useful internal const int slnFileMaxVersion = VisualStudioConstants.CurrentVisualStudioSolutionFileVersion; private const string vbProjectGuid = "{F184B08F-C81C-45F6-A57F-5ABD9991F28F}"; @@ -93,9 +93,8 @@ internal class SolutionParser // unit-testing only private ArrayList solutionParserErrorCodes = null; - - StreamReader reader = null; - int currentLineNumber = 0; + private StreamReader reader = null; + private int currentLineNumber = 0; #endregion @@ -264,7 +263,7 @@ internal ProjectInSolution[] Projects { get { - return (ProjectInSolution[]) this.projectsInOrder.ToArray(typeof(ProjectInSolution)); + return (ProjectInSolution[])this.projectsInOrder.ToArray(typeof(ProjectInSolution)); } } @@ -425,7 +424,7 @@ private void ParseFileHeader() const string slnFileHeaderNoVersion = "Microsoft Visual Studio Solution File, Format Version "; // Read the file header. This can be on either of the first two lines. - for (int i=1 ; i<=2 ; i++) + for (int i = 1; i <= 2; i++) { string str = ReadLine(); if (str == null) @@ -473,14 +472,14 @@ private void ValidateSolutionFileVersion(string versionString) // This happens if the version stamp wasn't a properly formed version number, // as in "1.a.b.c". ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", - new BuildEventFileInfo(SolutionFile, this.currentLineNumber, 0), "SolutionParseVersionMismatchError", + new BuildEventFileInfo(SolutionFile, this.currentLineNumber, 0), "SolutionParseVersionMismatchError", slnFileMinUpgradableVersion, slnFileMaxVersion); } catch (ArgumentException) { // This happens if the version stamp wasn't a properly formed version number. ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", - new BuildEventFileInfo(SolutionFile, this.currentLineNumber, 0), "SolutionParseVersionMismatchError", + new BuildEventFileInfo(SolutionFile, this.currentLineNumber, 0), "SolutionParseVersionMismatchError", slnFileMinUpgradableVersion, slnFileMaxVersion); } @@ -490,8 +489,8 @@ private void ValidateSolutionFileVersion(string versionString) ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( this.slnFileActualVersion >= slnFileMinUpgradableVersion, "SubCategoryForSolutionParsingErrors", - new BuildEventFileInfo(SolutionFile, this.currentLineNumber, 0), - "SolutionParseVersionMismatchError", + new BuildEventFileInfo(SolutionFile, this.currentLineNumber, 0), + "SolutionParseVersionMismatchError", slnFileMinUpgradableVersion, slnFileMaxVersion); // If the solution file version is greater than the maximum one we will create a comment rather than warn @@ -642,7 +641,7 @@ internal void ParseEtpProject(ProjectInSolution etpProj) { etpProjectDocument.Load(xmlReader); } - + // We need to parse the .etp project file to get the names of projects contained // in the .etp Project. The projects are listed under /EFPROJECT/GENERAL/References/Reference node in the .etp project file. // The /EFPROJECT/GENERAL/Views/ProjectExplorer node will not necessarily contain @@ -743,7 +742,7 @@ internal void ParseEtpProject(ProjectInSolution etpProj) etpProj.RelativePath, e.Message); solutionParserWarnings.Add(warning); solutionParserErrorCodes.Add(errorCode); - } + } } /// @@ -758,7 +757,7 @@ private void AddProjectToSolution(ProjectInSolution proj) } projectsInOrder.Add(proj); } - + /// /// Checks whether a given project has a .etp extension. /// @@ -952,7 +951,7 @@ string propertyValue // Cut out the guid part if ((indexOfOpeningBrace != -1) && (indexOfClosingBrace != -1)) { - string referencedProjectGuid = projectReferenceEntry.Substring(indexOfOpeningBrace, + string referencedProjectGuid = projectReferenceEntry.Substring(indexOfOpeningBrace, indexOfClosingBrace - indexOfOpeningBrace + 1); proj.Dependencies.Add(referencedProjectGuid); @@ -1009,10 +1008,10 @@ ProjectInSolution proj proj.ProjectName = match.Groups["PROJECTNAME"].Value.Trim(); proj.RelativePath = match.Groups["RELATIVEPATH"].Value.Trim(); proj.ProjectGuid = match.Groups["PROJECTGUID"].Value.Trim(); - + // Validate project relative path ValidateProjectRelativePath(proj); - + // Figure out what type of project this is. if ((String.Equals(projectTypeGuid, vbProjectGuid, StringComparison.OrdinalIgnoreCase)) || (String.Equals(projectTypeGuid, csProjectGuid, StringComparison.OrdinalIgnoreCase)) || @@ -1109,7 +1108,9 @@ internal void ParseSolutionConfigurations() //Fixing bug 555577: Solution file can have description information, in which case we ignore. if (String.Equals(fullConfigurationName, "DESCRIPTION", StringComparison.OrdinalIgnoreCase)) + { continue; + } // Both names must be identical ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(fullConfigurationName == configurationNames[1].Trim(), "SubCategoryForSolutionParsingErrors", @@ -1188,7 +1189,7 @@ internal void ProcessProjectConfigurationSection(Hashtable rawProjectConfigurati // the entry name instead of constructing it and looking it up. Although it's pretty unlikely that // this would ever be a problem, it's safer to do it the same way VS IDE does it. char[] configPlatformSeparators = new char[] { ConfigurationInSolution.configurationPlatformSeparator }; - + foreach (ProjectInSolution project in this.projectsInOrder) { // Solution folders don't have configurations @@ -1198,7 +1199,7 @@ internal void ProcessProjectConfigurationSection(Hashtable rawProjectConfigurati { // The "ActiveCfg" entry defines the active project configuration in the given solution configuration // This entry must be present for every possible solution configuration/project combination. - string entryNameActiveConfig = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.ActiveCfg", + string entryNameActiveConfig = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.ActiveCfg", project.ProjectGuid, solutionConfiguration.FullName); // The "Build.0" entry tells us whether to build the project configuration in the given solution configuration. @@ -1206,7 +1207,7 @@ internal void ProcessProjectConfigurationSection(Hashtable rawProjectConfigurati // more flexible design of solution configurations (as well as the '.0' suffix - no higher values are ever used). // The configuration name is not used, and the whole entry means "build the project configuration" // if it's present in the solution file, and "don't build" if it's not. - string entryNameBuild = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.Build.0", + string entryNameBuild = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.Build.0", project.ProjectGuid, solutionConfiguration.FullName); if (rawProjectConfigurationsEntries.ContainsKey(entryNameActiveConfig)) @@ -1310,7 +1311,7 @@ internal string GetDefaultPlatformName() /// RGoel internal string GetProjectUniqueNameByGuid(string projectGuid) { - ProjectInSolution proj = (ProjectInSolution) projects[projectGuid]; + ProjectInSolution proj = (ProjectInSolution)projects[projectGuid]; return proj?.GetUniqueProjectName(); } @@ -1323,7 +1324,7 @@ internal string GetProjectUniqueNameByGuid(string projectGuid) /// RGoel internal string GetProjectRelativePathByGuid(string projectGuid) { - ProjectInSolution proj = (ProjectInSolution) projects[projectGuid]; + ProjectInSolution proj = (ProjectInSolution)projects[projectGuid]; return proj?.RelativePath; } diff --git a/src/Deprecated/Engine/Shared/TypeLoader.cs b/src/Deprecated/Engine/Shared/TypeLoader.cs index 03fc8616fdd..b3ac7ddc635 100644 --- a/src/Deprecated/Engine/Shared/TypeLoader.cs +++ b/src/Deprecated/Engine/Shared/TypeLoader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Deprecated/Engine/Shared/VisualStudioConstants.cs b/src/Deprecated/Engine/Shared/VisualStudioConstants.cs index b48c284f147..80fd4d70191 100644 --- a/src/Deprecated/Engine/Shared/VisualStudioConstants.cs +++ b/src/Deprecated/Engine/Shared/VisualStudioConstants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.BuildEngine.Shared { diff --git a/src/Deprecated/Engine/Shared/XMakeAttributes.cs b/src/Deprecated/Engine/Shared/XMakeAttributes.cs index 33bef0d06d8..416adfd76ba 100644 --- a/src/Deprecated/Engine/Shared/XMakeAttributes.cs +++ b/src/Deprecated/Engine/Shared/XMakeAttributes.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -11,50 +11,50 @@ namespace Microsoft.Build.BuildEngine.Shared /// RGoel internal static class XMakeAttributes { - internal const string condition = "Condition"; - internal const string executeTargets = "ExecuteTargets"; - internal const string name = "Name"; - internal const string msbuildVersion = "MSBuildVersion"; - internal const string xmlns = "xmlns"; - internal const string defaultTargets = "DefaultTargets"; - internal const string initialTargets = "InitialTargets"; - internal const string dependsOnTargets = "DependsOnTargets"; - internal const string beforeTargets = "BeforeTargets"; - internal const string afterTargets = "AfterTargets"; - internal const string include = "Include"; - internal const string exclude = "Exclude"; - internal const string remove = "Remove"; - internal const string keepMetadata = "KeepMetadata"; - internal const string removeMetadata = "RemoveMetadata"; - internal const string keepDuplicates = "KeepDuplicates"; - internal const string inputs = "Inputs"; - internal const string outputs = "Outputs"; - internal const string keepDuplicateOutputs = "KeepDuplicateOutputs"; - internal const string assemblyName = "AssemblyName"; - internal const string assemblyFile = "AssemblyFile"; - internal const string taskName = "TaskName"; - internal const string continueOnError = "ContinueOnError"; - internal const string project = "Project"; - internal const string taskParameter = "TaskParameter"; - internal const string itemName = "ItemName"; - internal const string propertyName = "PropertyName"; - internal const string toolsVersion = "ToolsVersion"; - internal const string requiredRuntime = "RequiredRuntime"; - internal const string requiredPlatform = "RequiredPlatform"; - internal const string runtime = "Runtime"; - internal const string msbuildRuntime = "MSBuildRuntime"; - internal const string architecture = "Architecture"; - internal const string msbuildArchitecture = "MSBuildArchitecture"; - internal const string taskFactory = "TaskFactory"; - internal const string parameterType = "ParameterType"; - internal const string required = "Required"; - internal const string output = "Output"; - internal const string defaultValue = "DefaultValue"; - internal const string evaluate = "Evaluate"; - internal const string label = "Label"; - internal const string returns = "Returns"; + internal const string condition = "Condition"; + internal const string executeTargets = "ExecuteTargets"; + internal const string name = "Name"; + internal const string msbuildVersion = "MSBuildVersion"; + internal const string xmlns = "xmlns"; + internal const string defaultTargets = "DefaultTargets"; + internal const string initialTargets = "InitialTargets"; + internal const string dependsOnTargets = "DependsOnTargets"; + internal const string beforeTargets = "BeforeTargets"; + internal const string afterTargets = "AfterTargets"; + internal const string include = "Include"; + internal const string exclude = "Exclude"; + internal const string remove = "Remove"; + internal const string keepMetadata = "KeepMetadata"; + internal const string removeMetadata = "RemoveMetadata"; + internal const string keepDuplicates = "KeepDuplicates"; + internal const string inputs = "Inputs"; + internal const string outputs = "Outputs"; + internal const string keepDuplicateOutputs = "KeepDuplicateOutputs"; + internal const string assemblyName = "AssemblyName"; + internal const string assemblyFile = "AssemblyFile"; + internal const string taskName = "TaskName"; + internal const string continueOnError = "ContinueOnError"; + internal const string project = "Project"; + internal const string taskParameter = "TaskParameter"; + internal const string itemName = "ItemName"; + internal const string propertyName = "PropertyName"; + internal const string toolsVersion = "ToolsVersion"; + internal const string requiredRuntime = "RequiredRuntime"; + internal const string requiredPlatform = "RequiredPlatform"; + internal const string runtime = "Runtime"; + internal const string msbuildRuntime = "MSBuildRuntime"; + internal const string architecture = "Architecture"; + internal const string msbuildArchitecture = "MSBuildArchitecture"; + internal const string taskFactory = "TaskFactory"; + internal const string parameterType = "ParameterType"; + internal const string required = "Required"; + internal const string output = "Output"; + internal const string defaultValue = "DefaultValue"; + internal const string evaluate = "Evaluate"; + internal const string label = "Label"; + internal const string returns = "Returns"; - internal const string defaultXmlNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; + internal const string defaultXmlNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; /// /// Returns true if and only if the specified attribute is one of the attributes that the engine specifically recognizes diff --git a/src/Deprecated/Engine/Shared/XMakeElements.cs b/src/Deprecated/Engine/Shared/XMakeElements.cs index 49205e6f6db..0f8c108fd5b 100644 --- a/src/Deprecated/Engine/Shared/XMakeElements.cs +++ b/src/Deprecated/Engine/Shared/XMakeElements.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Xml; diff --git a/src/Deprecated/Engine/Shared/XmlUtilities.cs b/src/Deprecated/Engine/Shared/XmlUtilities.cs index 69b8ea969ea..5e76b57a9a4 100644 --- a/src/Deprecated/Engine/Shared/XmlUtilities.cs +++ b/src/Deprecated/Engine/Shared/XmlUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -10,7 +10,7 @@ namespace Microsoft.Build.BuildEngine.Shared /// This class contains utility methods for XML manipulation. /// /// SumedhK - static internal class XmlUtilities + internal static class XmlUtilities { /// /// This method renames an XML element. Well, actually you can't directly @@ -43,11 +43,11 @@ internal static XmlElement RenameXmlElement(XmlElement oldElement, string newEle newElement.AppendChild(newChildNode); } - - - // Add the new element in the same place the old element was. - oldElement.ParentNode?.ReplaceChild(newElement, oldElement); - + + + // Add the new element in the same place the old element was. + oldElement.ParentNode?.ReplaceChild(newElement, oldElement); + return newElement; } @@ -231,7 +231,7 @@ string attributeName } } } - catch(XmlException) + catch (XmlException) { // Ignore any XML exceptions as it will be caught later on } diff --git a/src/Deprecated/Engine/Solution/SolutionWrapperProject.cs b/src/Deprecated/Engine/Solution/SolutionWrapperProject.cs index 6dc05efbbac..146bd7020d4 100644 --- a/src/Deprecated/Engine/Solution/SolutionWrapperProject.cs +++ b/src/Deprecated/Engine/Solution/SolutionWrapperProject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -18,7 +18,7 @@ namespace Microsoft.Build.BuildEngine /// This class is used to generate an MSBuild wrapper project for a solution file or standalone VC project. /// /// LukaszG, RGoel - static public class SolutionWrapperProject + public static class SolutionWrapperProject { private const string webProjectOverrideFolder = "_PublishedWebsites"; private const string cacheSolutionConfigurationPropertyName = "_SolutionProjectConfiguration"; @@ -34,7 +34,7 @@ static public class SolutionWrapperProject /// May be null. If non-null, contains the ToolsVersion passed in on the command line\ /// An event context for logging purposes. /// - static public string Generate(string solutionPath, string toolsVersionOverride, BuildEventContext projectBuildEventContext) + public static string Generate(string solutionPath, string toolsVersionOverride, BuildEventContext projectBuildEventContext) { Project msbuildProject = new Project(); @@ -57,7 +57,7 @@ static public string Generate(string solutionPath, string toolsVersionOverride, /// Any /tv:xxx switch would cause a value here. /// /// RGoel - static internal void Generate(SolutionParser solution, Project msbuildProject, string toolsVersionOverride, BuildEventContext projectBuildEventContext) + internal static void Generate(SolutionParser solution, Project msbuildProject, string toolsVersionOverride, BuildEventContext projectBuildEventContext) { // Validate against our minimum for upgradable projects ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(solution.Version >= SolutionParser.slnFileMinVersion, @@ -134,7 +134,9 @@ static internal void Generate(SolutionParser solution, Project msbuildProject, s catch (Exception ex) { if (ExceptionHandling.IsCriticalException(ex)) + { throw; + } // Eat any regular exceptions: we'll just not use the cache parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheReadError", solutionProjectCache, ex.Message); } @@ -160,7 +162,9 @@ private static void UpdateCache(Engine parentEngine, Project msbuildProject, str catch (Exception ex) { if (ExceptionHandling.IsCriticalException(ex)) + { throw; + } // Eat any regular exceptions: we'll just not use the cache parentEngine.LoggingServices.LogComment(projectBuildEventContext, "SolutionCacheWriteError", solutionProjectCache, ex.Message); } @@ -180,7 +184,7 @@ private static bool IsSolutionCacheEnabled() /// Given a cache loaded into a project, determines whether it is up to date with respect to the projects and the solution file listed /// with it, and was created with the same configuration/platform and tools version values as the ones currently in use. /// - private static bool IsCacheUpToDate(Engine parentEngine, string solutionFile, string solutionFileDirectory, Project msbuildProject, BuildEventContext projectBuildEventContext, string fullSolutionConfigurationName, string wrapperProjectToolsVersion) + private static bool IsCacheUpToDate(Engine parentEngine, string solutionFile, string solutionFileDirectory, Project msbuildProject, BuildEventContext projectBuildEventContext, string fullSolutionConfigurationName, string wrapperProjectToolsVersion) { // Check the full solution configuration matches, eg "Debug|AnyCPU" string cacheSolutionConfigurationName = msbuildProject.GetEvaluatedProperty(cacheSolutionConfigurationPropertyName); @@ -205,8 +209,8 @@ private static bool IsCacheUpToDate(Engine parentEngine, string solutionFile, s return false; } - // We also store the version of MSBuild that wrote the file and verify it's the same as ours: that ensures that we - // don't read possibly incompatible caches. + // We also store the version of MSBuild that wrote the file and verify it's the same as ours: that ensures that we + // don't read possibly incompatible caches. string thisVersion = Constants.AssemblyVersion; if (!String.Equals(cacheVersion, thisVersion, StringComparison.OrdinalIgnoreCase)) { @@ -499,7 +503,7 @@ private static string DetermineChildProjectToolsVersion(Engine parentEngine, str /// /// /// RGoel, LukaszG - static private BuildTask AddMSBuildTaskElement + private static BuildTask AddMSBuildTaskElement ( Target target, string projectPath, @@ -544,7 +548,7 @@ bool specifyProjectToolsVersion /// The name of the item exposing this target's outputs. May be null. /// /// RGoel, LukaszG - static private void AddTargetForManagedProject + private static void AddTargetForManagedProject ( Project msbuildProject, SolutionParser solution, @@ -653,7 +657,7 @@ string subTargetName /// /// /// LukaszG - static private BuildTask AddResolveVCProjectOutputTaskElement + private static BuildTask AddResolveVCProjectOutputTaskElement ( Target target, string solutionPath, @@ -686,7 +690,7 @@ string fullConfigurationName /// /// /// LukaszG - static private void AddResolveProjectReferenceTasks + private static void AddResolveProjectReferenceTasks ( SolutionParser solution, Project msbuildProject, @@ -804,7 +808,7 @@ out string addedReferenceGuids /// /// The path to the temporary project file /// LukaszG - static private string AddCreateTemporaryVCProjectTasks + private static string AddCreateTemporaryVCProjectTasks ( SolutionParser solution, Project msbuildProject, @@ -834,7 +838,9 @@ string projectConfigurationName referenceItemName.ToString(), importLibraryItemName.ToString(), out referenceGuidsToRemove); if (string.IsNullOrEmpty(referenceGuidsToRemove)) + { referenceGuidsToRemove = string.Empty; + } string fullProjectPath = null; string projectPath = null; @@ -848,7 +854,9 @@ string projectConfigurationName catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", @@ -882,7 +890,7 @@ string projectConfigurationName /// /// /// LukaszG, RGoel - static private void AddTargetForVCProject + private static void AddTargetForVCProject ( Project msbuildProject, SolutionParser solution, @@ -921,7 +929,9 @@ string subTargetName catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", @@ -990,7 +1000,7 @@ string subTargetName /// /// /// RGoel - static private void AddTargetForGetFrameworkPathAndRedistList + private static void AddTargetForGetFrameworkPathAndRedistList ( Project msbuildProject ) @@ -1052,7 +1062,7 @@ Project msbuildProject /// /// /// RGoel - static private void AddTaskForAspNetCompiler + private static void AddTaskForAspNetCompiler ( Target target, ProjectInSolution proj, @@ -1087,7 +1097,7 @@ string conditionDescribingValidConfigurations /// /// /// RGoel - static private void AddTasksToCopyAllDependenciesIntoBinDir + private static void AddTasksToCopyAllDependenciesIntoBinDir ( Target target, ProjectInSolution proj, @@ -1146,7 +1156,7 @@ string conditionDescribingValidConfigurations /// /// /// RGoel - static private void AddPropertyGroupForAspNetConfiguration + private static void AddPropertyGroupForAspNetConfiguration ( Project msbuildProject, ProjectInSolution proj, @@ -1195,7 +1205,9 @@ string solutionFile catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) + { throw; + } ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, "SubCategoryForSolutionParsingErrors", @@ -1229,7 +1241,7 @@ string solutionFile /// /// /// RGoel - static private void AddTasksToResolveAutoRefreshFileReferences + private static void AddTasksToResolveAutoRefreshFileReferences ( Target target, ProjectInSolution proj, @@ -1270,7 +1282,7 @@ string referenceItemName /// /// /// RGoel - static private string ComputeTargetConditionForWebProject + private static string ComputeTargetConditionForWebProject ( SolutionParser solution, ProjectInSolution proj @@ -1321,7 +1333,7 @@ ProjectInSolution proj /// /// /// RGoel - static private void AddTargetForWebProject + private static void AddTargetForWebProject ( Project msbuildProject, SolutionParser solution, @@ -1442,7 +1454,7 @@ string subTargetName /// /// A safe property name that can be used as an XML element name. /// RGoel - static private string GenerateSafePropertyName + private static string GenerateSafePropertyName ( ProjectInSolution proj, string propertyName @@ -1486,7 +1498,7 @@ private static string MakeIntoSafeItemName(string name) /// Resource string name to use in the tag text /// Additional parameters to pass to FormatString /// LukaszG - static internal BuildTask AddErrorWarningMessageElement(Target target, string elementType, + internal static BuildTask AddErrorWarningMessageElement(Target target, string elementType, bool treatAsLiteral, string textResourceName, params object[] args) { string code; @@ -1518,7 +1530,7 @@ static internal BuildTask AddErrorWarningMessageElement(Target target, string el /// Optional detailed error message to print out in case we already tried accessing the /// project file before and failed. /// RGoel - static private void AddTargetForUnknownProjectType + private static void AddTargetForUnknownProjectType ( Project msbuildProject, SolutionParser solution, @@ -1583,7 +1595,7 @@ string errorMessage /// The target to call within the project that's being added. /// /// RGoel - static private Target AddAllDependencyTarget + private static Target AddAllDependencyTarget ( Project msbuildProject, string targetName, @@ -1659,7 +1671,7 @@ Dictionary> projectsByDependencyLevel /// /// /// RGoel - static private string GetProjectDependencies(SolutionParser solution, ProjectInSolution project, string subTargetName) + private static string GetProjectDependencies(SolutionParser solution, ProjectInSolution project, string subTargetName) { ErrorUtilities.VerifyThrow(project != null, "We should always have a project for this method"); StringBuilder dependencies = new StringBuilder(); @@ -1696,7 +1708,7 @@ static private string GetProjectDependencies(SolutionParser solution, ProjectInS /// /// /// - static private string GetAllNonMSBuildProjectDependencies + private static string GetAllNonMSBuildProjectDependencies ( Dictionary> projectsByDependencyLevel, int dependencyLevel, @@ -1744,7 +1756,7 @@ string subTargetName /// /// /// LukaszG - static private string GetConditionStringForConfiguration(ConfigurationInSolution configuration) + private static string GetConditionStringForConfiguration(ConfigurationInSolution configuration) { return string.Format(CultureInfo.InvariantCulture, " ('$(Configuration)' == '{0}') and ('$(Platform)' == '{1}') ", EscapingUtilities.Escape(configuration.ConfigurationName), @@ -1757,7 +1769,7 @@ static private string GetConditionStringForConfiguration(ConfigurationInSolution /// /// /// LukaszG - static private void AddConfigurationPlatformDefaults + private static void AddConfigurationPlatformDefaults ( Project msbuildProject, SolutionParser solution @@ -1780,7 +1792,7 @@ SolutionParser solution /// /// /// LukaszG - static internal void AddPropertyGroupForSolutionConfiguration + internal static void AddPropertyGroupForSolutionConfiguration ( Project msbuildProject, SolutionParser solution, @@ -1825,7 +1837,7 @@ ConfigurationInSolution solutionConfiguration /// /// /// LukaszG - static private void AddVenusConfigurationDefaults + private static void AddVenusConfigurationDefaults ( Project msbuildProject ) @@ -1841,7 +1853,7 @@ Project msbuildProject /// /// /// LukaszG - static private void AddGlobalProperties(Project msbuildProject, SolutionParser solution) + private static void AddGlobalProperties(Project msbuildProject, SolutionParser solution) { BuildPropertyGroup propertyGroup = msbuildProject.AddNewPropertyGroup(true /* insertAtEndOfProject = true */); @@ -1882,7 +1894,7 @@ static private void AddGlobalProperties(Project msbuildProject, SolutionParser s /// /// /// LukaszG - static private void AddFakeReleaseSolutionConfigurationIfNecessary(SolutionParser solution) + private static void AddFakeReleaseSolutionConfigurationIfNecessary(SolutionParser solution) { if (solution.ContainsWebProjects) { @@ -1908,7 +1920,7 @@ static private void AddFakeReleaseSolutionConfigurationIfNecessary(SolutionParse /// /// /// LukaszG - static private void AddInitialTargets(Project msbuildProject) + private static void AddInitialTargets(Project msbuildProject) { Target initialTarget = msbuildProject.Targets.AddNewTarget("ValidateSolutionConfiguration"); @@ -1940,7 +1952,7 @@ static private void AddInitialTargets(Project msbuildProject) /// /// /// LukaszG - static internal string PredictActiveSolutionConfigurationName(SolutionParser solution, Engine parentEngine) + internal static string PredictActiveSolutionConfigurationName(SolutionParser solution, Engine parentEngine) { string candidateFullSolutionConfigurationName = DetermineLikelyActiveSolutionConfiguration(solution, parentEngine); @@ -1973,7 +1985,7 @@ private static string DetermineLikelyActiveSolutionConfiguration(SolutionParser if (configurationProperty != null) { - activeSolutionConfiguration= configurationProperty.FinalValue; + activeSolutionConfiguration = configurationProperty.FinalValue; } else { @@ -1982,7 +1994,7 @@ private static string DetermineLikelyActiveSolutionConfiguration(SolutionParser if (platformProperty != null) { - activeSolutionPlatform = platformProperty.FinalValue; + activeSolutionPlatform = platformProperty.FinalValue; } else { @@ -1999,7 +2011,7 @@ private static string DetermineLikelyActiveSolutionConfiguration(SolutionParser /// we know what build order we should use when building the solution. /// /// LukaszG - static private void ScanProjectDependencies(SolutionParser solution, Engine parentEngine, string childProjectToolsVersion, string fullSolutionConfigurationName, BuildEventContext projectBuildEventContext) + private static void ScanProjectDependencies(SolutionParser solution, Engine parentEngine, string childProjectToolsVersion, string fullSolutionConfigurationName, BuildEventContext projectBuildEventContext) { // Don't bother with all this if the solution configuration doesn't even exist. if (fullSolutionConfigurationName == null) @@ -2080,7 +2092,10 @@ static private void ScanProjectDependencies(SolutionParser solution, Engine pare // We don't want any problems scanning the project file to result in aborting the build. catch (Exception e) { - if (ExceptionHandling.IsCriticalException(e)) throw; + if (ExceptionHandling.IsCriticalException(e)) + { + throw; + } parentEngine.LoggingServices.LogWarning(projectBuildEventContext, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(project.RelativePath), "SolutionScanProjectDependenciesFailed", project.RelativePath, e.Message); @@ -2119,7 +2134,10 @@ static private void ScanProjectDependencies(SolutionParser solution, Engine pare // We don't want any problems scanning the project file to result in aborting the build. catch (Exception e) { - if (ExceptionHandling.IsCriticalException(e)) throw; + if (ExceptionHandling.IsCriticalException(e)) + { + throw; + } parentEngine.LoggingServices.LogWarning(projectBuildEventContext, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(project.RelativePath), "SolutionScanProjectDependenciesFailed", project.RelativePath, e.Message); @@ -2139,7 +2157,7 @@ static private void ScanProjectDependencies(SolutionParser solution, Engine pare /// The engine handling the conversion /// The build event context /// The guid, in string form, of the dependency project - static private void AddDependencyByGuid(SolutionParser solution, ProjectInSolution project, Engine parentEngine, BuildEventContext projectBuildEventContext, string dependencyGuid) + private static void AddDependencyByGuid(SolutionParser solution, ProjectInSolution project, Engine parentEngine, BuildEventContext projectBuildEventContext, string dependencyGuid) { if (!String.IsNullOrEmpty(dependencyGuid)) { @@ -2165,7 +2183,7 @@ static private void AddDependencyByGuid(SolutionParser solution, ProjectInSoluti /// /// /// LukaszG - static internal void ConvertVcToVcDependenciesToReferences(SolutionParser solution, Engine parentEngine, BuildEventContext projectBuildEventContext) + internal static void ConvertVcToVcDependenciesToReferences(SolutionParser solution, Engine parentEngine, BuildEventContext projectBuildEventContext) { // Go through the list of the projects in solution looking for VC projects foreach (ProjectInSolution project in solution.ProjectsInOrder) @@ -2203,7 +2221,7 @@ static internal void ConvertVcToVcDependenciesToReferences(SolutionParser soluti /// /// /// - static private void AssignDependencyLevel(ProjectInSolution project, SolutionParser solution, Dictionary> projectsByDependencyLevel) + private static void AssignDependencyLevel(ProjectInSolution project, SolutionParser solution, Dictionary> projectsByDependencyLevel) { // if we ever try to recurse into a project whose dependency level we're calculating above, // we have a circular dependency. @@ -2221,7 +2239,7 @@ static private void AssignDependencyLevel(ProjectInSolution project, SolutionPar // First, go through dependencies and ensure they have their dependency level set correctly. foreach (string dependencyGuid in project.Dependencies) { - ProjectInSolution referencedProject = (ProjectInSolution) solution.ProjectsByGuid[dependencyGuid]; + ProjectInSolution referencedProject = (ProjectInSolution)solution.ProjectsByGuid[dependencyGuid]; AssignDependencyLevel(referencedProject, solution, projectsByDependencyLevel); @@ -2251,7 +2269,7 @@ static private void AssignDependencyLevel(ProjectInSolution project, SolutionPar /// /// /// - static private void AssignDependencyLevels(SolutionParser solution, Dictionary> projectsByDependencyLevel) + private static void AssignDependencyLevels(SolutionParser solution, Dictionary> projectsByDependencyLevel) { foreach (ProjectInSolution project in solution.ProjectsInOrder) { diff --git a/src/Deprecated/Engine/Solution/VCProjectParser.cs b/src/Deprecated/Engine/Solution/VCProjectParser.cs index 725f09023a3..1358ada8d73 100644 --- a/src/Deprecated/Engine/Solution/VCProjectParser.cs +++ b/src/Deprecated/Engine/Solution/VCProjectParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -7,15 +7,15 @@ namespace Microsoft.Build.BuildEngine { - static internal class VCProjectParser - { + internal static class VCProjectParser + { /// /// For a given VC project, retrieves the projects it references /// /// /// /// LukaszG - static internal List GetReferencedProjectGuids(XmlDocument project) + internal static List GetReferencedProjectGuids(XmlDocument project) { List referencedProjectGuids = new List(); diff --git a/src/Deprecated/Engine/Solution/VCWrapperProject.cs b/src/Deprecated/Engine/Solution/VCWrapperProject.cs index e20945c6112..68562a18442 100644 --- a/src/Deprecated/Engine/Solution/VCWrapperProject.cs +++ b/src/Deprecated/Engine/Solution/VCWrapperProject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -20,7 +20,7 @@ internal class VCWrapperProject /// /// /// RGoel - static private void AddVCBuildTarget + private static void AddVCBuildTarget ( Project msbuildProject, string projectPath, @@ -55,7 +55,7 @@ string subTargetName /// The platform parameter to VCBuild /// Configuration property value /// - static internal BuildTask AddVCBuildTaskElement + internal static BuildTask AddVCBuildTaskElement ( Project msbuildProject, Target target, @@ -133,7 +133,7 @@ string fullConfigurationName /// This method generates an XmlDocument representing an MSBuild project wrapper for a VC project /// /// LukaszG - static internal XmlDocument GenerateVCWrapperProject(Engine parentEngine, string vcProjectFilename, string toolsVersion) + internal static XmlDocument GenerateVCWrapperProject(Engine parentEngine, string vcProjectFilename, string toolsVersion) { string projectPath = Path.GetFullPath(vcProjectFilename); Project msbuildProject; @@ -187,13 +187,13 @@ static internal XmlDocument GenerateVCWrapperProject(Engine parentEngine, string /// /// Hint to give the VCBuild task to help it find vcbuild.exe. /// - static private string path; + private static string path; /// /// Hint to give the VCBuild task to help it find vcbuild.exe. /// Directory in which vcbuild.exe is found. /// - static internal string VCBuildLocationHint + internal static string VCBuildLocationHint { get { diff --git a/src/Deprecated/Engine/Tasks/IntrinsicTask.cs b/src/Deprecated/Engine/Tasks/IntrinsicTask.cs index 2633ca633bd..54ee215a411 100644 --- a/src/Deprecated/Engine/Tasks/IntrinsicTask.cs +++ b/src/Deprecated/Engine/Tasks/IntrinsicTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -29,7 +29,7 @@ internal IntrinsicTask(XmlElement taskNodeXmlElement, EngineLoggingServices logg this.buildEventContext = eventContext; this.executionDirectory = executionDirectory; this.itemDefinitionLibrary = itemDefinitionLibrary; - + ErrorUtilities.VerifyThrow(IsIntrinsicTaskName(taskNodeXmlElement.Name), "Only PropertyGroup and ItemGroup are known intrinsic tasks"); switch (taskNodeXmlElement.Name) @@ -70,7 +70,7 @@ internal void ExecuteTask(Lookup lookup) { ErrorUtilities.VerifyThrow(lookup != null, "Need to specify lookup."); - if ((conditionAttribute != null) + if ((conditionAttribute != null) && !Utilities.EvaluateCondition(conditionAttribute.Value, conditionAttribute, new Expander(lookup.ReadOnlyLookup), null, ParserOptions.AllowPropertiesAndItemLists, loggingServices, buildEventContext)) { return; @@ -93,7 +93,7 @@ internal void ExecuteTask(Lookup lookup) /// Execute a PropertyGroup element, including each child property /// private void ExecutePropertyGroup(Lookup lookup) - { + { foreach (BuildProperty property in backingPropertyGroup) { ArrayList buckets = null; @@ -325,16 +325,21 @@ private static void AddIfNotEmptyString(List list, string value) private EngineLoggingServices loggingServices; // event contextual information where the event is fired from private BuildEventContext buildEventContext; + // whether the backing type is a property group, or an item group - BackingType backingType; + private BackingType backingType; + // backing property group, if any - BuildPropertyGroup backingPropertyGroup; + private BuildPropertyGroup backingPropertyGroup; + // backing xml for a backing item group, if any - BuildItemGroupXml backingItemGroupXml; + private BuildItemGroupXml backingItemGroupXml; + // children of the backing item group, if any - List backingBuildItemGroupChildren = null; + private List backingBuildItemGroupChildren = null; + // directory in which the project is executing -- the current directory needed to expand wildcards - string executionDirectory; + private string executionDirectory; // the conditional expression that controls task execution private XmlAttribute conditionAttribute; // the library of default metadata that any new items should inherit diff --git a/src/Deprecated/Engine/Utilities/EngineFileUtilities.cs b/src/Deprecated/Engine/Utilities/EngineFileUtilities.cs index 34b8a79a3bc..1a5ee68930c 100644 --- a/src/Deprecated/Engine/Utilities/EngineFileUtilities.cs +++ b/src/Deprecated/Engine/Utilities/EngineFileUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.BuildEngine.Shared; diff --git a/src/Deprecated/Engine/Xml/BuildItemGroupChildXml.cs b/src/Deprecated/Engine/Xml/BuildItemGroupChildXml.cs index deb2b0749b8..2a33816c7f2 100644 --- a/src/Deprecated/Engine/Xml/BuildItemGroupChildXml.cs +++ b/src/Deprecated/Engine/Xml/BuildItemGroupChildXml.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -45,7 +45,7 @@ internal BuildItemGroupChildXml(XmlElement element, ChildType childTypeExpected) ProjectXmlUtilities.VerifyThrowProjectValidNameAndNamespace(element); this.element = element; - + // Loop through each of the attributes on the item element. foreach (XmlAttribute attribute in element.Attributes) { @@ -55,7 +55,7 @@ internal BuildItemGroupChildXml(XmlElement element, ChildType childTypeExpected) this.includeAttribute = attribute; break; - case XMakeAttributes.exclude: + case XMakeAttributes.exclude: this.excludeAttribute = attribute; break; @@ -159,7 +159,7 @@ internal BuildItemGroupChildXml(XmlElement element, ChildType childTypeExpected) internal string Name { get - { + { return element.Name; } @@ -252,7 +252,7 @@ internal ChildType ChildType { get { return childType; } } - + #endregion #region Methods diff --git a/src/Deprecated/Engine/Xml/BuildItemGroupXml.cs b/src/Deprecated/Engine/Xml/BuildItemGroupXml.cs index 2dacb63d74e..34f44ca8e7e 100644 --- a/src/Deprecated/Engine/Xml/BuildItemGroupXml.cs +++ b/src/Deprecated/Engine/Xml/BuildItemGroupXml.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -19,9 +19,9 @@ internal class BuildItemGroupXml private XmlElement element; // The Condition attribute on it, if any, to save lookup private XmlAttribute conditionAttribute; - + #endregion - + #region Constructors /// @@ -46,7 +46,7 @@ internal BuildItemGroupXml(XmlDocument owner) } #endregion - + #region Properties internal string Condition diff --git a/src/Deprecated/Engine/Xml/ProjectXmlUtilities.cs b/src/Deprecated/Engine/Xml/ProjectXmlUtilities.cs index 50cb627cc52..10c64fa1bc5 100644 --- a/src/Deprecated/Engine/Xml/ProjectXmlUtilities.cs +++ b/src/Deprecated/Engine/Xml/ProjectXmlUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -65,7 +65,7 @@ internal static void VerifyThrowProjectNoChildElements(XmlElement element) if (childElements.Count > 0) { ThrowProjectInvalidChildElement(element.FirstChild); - } + } } /// @@ -110,7 +110,7 @@ internal static void VerifyThrowProjectValidNamespace(XmlElement element) /// internal static void VerifyThrowProjectNoAttributes(XmlElement element) { - foreach(XmlAttribute attribute in element.Attributes) + foreach (XmlAttribute attribute in element.Attributes) { ThrowProjectInvalidAttribute(attribute); } diff --git a/src/Framework.UnitTests/AssemblyInfo.cs b/src/Framework.UnitTests/AssemblyInfo.cs index 7f6f30fcef9..3b5d7bbb185 100644 --- a/src/Framework.UnitTests/AssemblyInfo.cs +++ b/src/Framework.UnitTests/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Framework.UnitTests/Attribute_Tests.cs b/src/Framework.UnitTests/Attribute_Tests.cs index f4badad23d1..981047ff9a3 100644 --- a/src/Framework.UnitTests/Attribute_Tests.cs +++ b/src/Framework.UnitTests/Attribute_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; diff --git a/src/Framework.UnitTests/BuildErrorEventArgs_Tests.cs b/src/Framework.UnitTests/BuildErrorEventArgs_Tests.cs index cdbbb599b85..280ac6a4d97 100644 --- a/src/Framework.UnitTests/BuildErrorEventArgs_Tests.cs +++ b/src/Framework.UnitTests/BuildErrorEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/BuildFinishedEventArgs_Tests.cs b/src/Framework.UnitTests/BuildFinishedEventArgs_Tests.cs index eca867cd1cc..94b459b2d28 100644 --- a/src/Framework.UnitTests/BuildFinishedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/BuildFinishedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/BuildMessageEventArgs_Tests.cs b/src/Framework.UnitTests/BuildMessageEventArgs_Tests.cs index 7ae7d967b34..94df096ada3 100644 --- a/src/Framework.UnitTests/BuildMessageEventArgs_Tests.cs +++ b/src/Framework.UnitTests/BuildMessageEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/BuildStartedEventArgs_Tests.cs b/src/Framework.UnitTests/BuildStartedEventArgs_Tests.cs index 1d3afacb3ba..16c9b493af0 100644 --- a/src/Framework.UnitTests/BuildStartedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/BuildStartedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Framework.UnitTests/BuildWarningEventArgs_Tests.cs b/src/Framework.UnitTests/BuildWarningEventArgs_Tests.cs index ceadce87f69..ed32552b268 100644 --- a/src/Framework.UnitTests/BuildWarningEventArgs_Tests.cs +++ b/src/Framework.UnitTests/BuildWarningEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/CriticalBuildMessageEventArgs_Tests.cs b/src/Framework.UnitTests/CriticalBuildMessageEventArgs_Tests.cs index 8f6cf3d8a76..fe1dec9a784 100644 --- a/src/Framework.UnitTests/CriticalBuildMessageEventArgs_Tests.cs +++ b/src/Framework.UnitTests/CriticalBuildMessageEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Framework.UnitTests/CustomEventArgSerialization_Tests.cs b/src/Framework.UnitTests/CustomEventArgSerialization_Tests.cs index d2af49af234..1c882b2ef53 100644 --- a/src/Framework.UnitTests/CustomEventArgSerialization_Tests.cs +++ b/src/Framework.UnitTests/CustomEventArgSerialization_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -19,12 +19,10 @@ public class CustomEventArgSerialization_Tests : IDisposable // Generic build class to test custom serialization of abstract class BuildEventArgs internal class GenericBuildEventArg : BuildEventArgs { - internal GenericBuildEventArg - ( + internal GenericBuildEventArg( string message, string helpKeyword, - string senderName - ) + string senderName) : base(message, helpKeyword, senderName) { // Do Nothing diff --git a/src/Framework.UnitTests/EventArgs_Tests.cs b/src/Framework.UnitTests/EventArgs_Tests.cs index aeab16776af..002efd3710a 100644 --- a/src/Framework.UnitTests/EventArgs_Tests.cs +++ b/src/Framework.UnitTests/EventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Framework.UnitTests/ExternalProjectFinishedEventArgs_Tests.cs b/src/Framework.UnitTests/ExternalProjectFinishedEventArgs_Tests.cs index d9cfee51e0c..b78bc8a56a3 100644 --- a/src/Framework.UnitTests/ExternalProjectFinishedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/ExternalProjectFinishedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/ExternalProjectStartedEventArgs_Tests.cs b/src/Framework.UnitTests/ExternalProjectStartedEventArgs_Tests.cs index 9f94de41320..d59c1326059 100644 --- a/src/Framework.UnitTests/ExternalProjectStartedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/ExternalProjectStartedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/FileClassifier_Tests.cs b/src/Framework.UnitTests/FileClassifier_Tests.cs index de8585434e0..5bf6c04f4ce 100644 --- a/src/Framework.UnitTests/FileClassifier_Tests.cs +++ b/src/Framework.UnitTests/FileClassifier_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using Microsoft.Build.Shared; @@ -24,7 +24,7 @@ public void IsNonModifiable_EvaluatesModifiability() FileClassifier classifier = new(); var volume = NativeMethodsShared.IsWindows ? @"X:\" : "/home/usr"; - classifier.RegisterImmutableDirectory($"{Path.Combine(volume,"Test1")}"); + classifier.RegisterImmutableDirectory($"{Path.Combine(volume, "Test1")}"); classifier.RegisterImmutableDirectory($"{Path.Combine(volume, "Test2")}"); classifier.IsNonModifiable(Path.Combine(volume, "Test1", "File.ext")).ShouldBeTrue(); diff --git a/src/Framework.UnitTests/LoggerException_Tests.cs b/src/Framework.UnitTests/LoggerException_Tests.cs index f7f9b9023ea..91ba8b2eae5 100644 --- a/src/Framework.UnitTests/LoggerException_Tests.cs +++ b/src/Framework.UnitTests/LoggerException_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Framework.UnitTests/ProjectFinishedEventArgs_Tests.cs b/src/Framework.UnitTests/ProjectFinishedEventArgs_Tests.cs index 94a52973afb..e83658633c7 100644 --- a/src/Framework.UnitTests/ProjectFinishedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/ProjectFinishedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Framework.UnitTests/ProjectStartedEventArgs_Tests.cs b/src/Framework.UnitTests/ProjectStartedEventArgs_Tests.cs index 309efaccb98..abe90d6e73f 100644 --- a/src/Framework.UnitTests/ProjectStartedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/ProjectStartedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -59,8 +59,7 @@ public void ItemsAndPropertiesDifferentEquals() { ArrayList itemsList = new ArrayList(); ArrayList propertiesList = new ArrayList(); - ProjectStartedEventArgs differentItemsAndProperties = new ProjectStartedEventArgs - ( + ProjectStartedEventArgs differentItemsAndProperties = new ProjectStartedEventArgs( s_baseProjectStartedEvent.ProjectId, s_baseProjectStartedEvent.Message, s_baseProjectStartedEvent.HelpKeyword, @@ -69,8 +68,7 @@ public void ItemsAndPropertiesDifferentEquals() propertiesList, itemsList, s_baseProjectStartedEvent.ParentProjectBuildEventContext, - s_baseProjectStartedEvent.Timestamp - ); + s_baseProjectStartedEvent.Timestamp); s_baseProjectStartedEvent.Properties.ShouldNotBe(propertiesList); s_baseProjectStartedEvent.Items.ShouldNotBe(itemsList); diff --git a/src/Framework.UnitTests/SdkReference_Tests.cs b/src/Framework.UnitTests/SdkReference_Tests.cs index dbcb6a68f7e..bc63f3b8c23 100644 --- a/src/Framework.UnitTests/SdkReference_Tests.cs +++ b/src/Framework.UnitTests/SdkReference_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Xunit; using Shouldly; diff --git a/src/Framework.UnitTests/TargetFinishedEventArgs_Tests.cs b/src/Framework.UnitTests/TargetFinishedEventArgs_Tests.cs index c69a345484f..71505177e31 100644 --- a/src/Framework.UnitTests/TargetFinishedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/TargetFinishedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework.UnitTests/TargetStartedEventArgs_Tests.cs b/src/Framework.UnitTests/TargetStartedEventArgs_Tests.cs index 3706d0eb554..fc4773f126c 100644 --- a/src/Framework.UnitTests/TargetStartedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/TargetStartedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/TaskCommandLineEventArgs_Tests.cs b/src/Framework.UnitTests/TaskCommandLineEventArgs_Tests.cs index 12cbc45dd39..1d9b383c585 100644 --- a/src/Framework.UnitTests/TaskCommandLineEventArgs_Tests.cs +++ b/src/Framework.UnitTests/TaskCommandLineEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/TaskFinishedEventArgs_Tests.cs b/src/Framework.UnitTests/TaskFinishedEventArgs_Tests.cs index 2c528d3ea90..24e32d25aa4 100644 --- a/src/Framework.UnitTests/TaskFinishedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/TaskFinishedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework.UnitTests/TaskStartedEventArgs_Tests.cs b/src/Framework.UnitTests/TaskStartedEventArgs_Tests.cs index 6bdd960c208..381f0f3ec4f 100644 --- a/src/Framework.UnitTests/TaskStartedEventArgs_Tests.cs +++ b/src/Framework.UnitTests/TaskStartedEventArgs_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/AssemblyUtilities.cs b/src/Framework/AssemblyUtilities.cs index e625642076d..dcb013b3a0d 100644 --- a/src/Framework/AssemblyUtilities.cs +++ b/src/Framework/AssemblyUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -75,7 +75,7 @@ public static Type GetTypeInfo(this Type t) public static AssemblyName CloneIfPossible(this AssemblyName assemblyNameToClone) { #if CLR2COMPATIBILITY - return (AssemblyName) assemblyNameToClone.Clone(); + return (AssemblyName)assemblyNameToClone.Clone(); #else // NOTE: In large projects, this is called a lot. Avoid calling AssemblyName.Clone @@ -139,7 +139,10 @@ public static CultureInfo[] GetAllCultures() /// private static void Initialize() { - if (s_initialized) return; + if (s_initialized) + { + return; + } s_assemblylocationProperty = typeof(Assembly).GetProperty("Location", typeof(string)); s_cultureInfoGetCultureMethod = typeof(CultureInfo).GetMethod("GetCultures"); @@ -164,7 +167,7 @@ private static CultureInfo[] GetValidCultures() var allCulturesEnumValue = Enum.Parse(cultureTypesType, "AllCultures", true); - var cultures = s_cultureInfoGetCultureMethod.Invoke(null, new[] {allCulturesEnumValue}) as CultureInfo[]; + var cultures = s_cultureInfoGetCultureMethod.Invoke(null, new[] { allCulturesEnumValue }) as CultureInfo[]; FrameworkErrorUtilities.VerifyThrowInternalNull(cultures, "CultureInfo.GetCultures should work if all reflection checks pass"); diff --git a/src/Framework/BuildEngineResult.cs b/src/Framework/BuildEngineResult.cs index 7d1af72ffaa..9bb2a0c0b08 100644 --- a/src/Framework/BuildEngineResult.cs +++ b/src/Framework/BuildEngineResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/BuildErrorEventArgs.cs b/src/Framework/BuildErrorEventArgs.cs index c8b9e23f432..543f71e1ec3 100644 --- a/src/Framework/BuildErrorEventArgs.cs +++ b/src/Framework/BuildErrorEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -79,8 +79,7 @@ public class BuildErrorEventArgs : LazyFormattedBuildEventArgs /// text message /// help keyword /// name of event sender - public BuildErrorEventArgs - ( + public BuildErrorEventArgs( string subcategory, string code, string file, @@ -90,8 +89,7 @@ public BuildErrorEventArgs int endColumnNumber, string message, string helpKeyword, - string senderName - ) + string senderName) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, DateTime.UtcNow) { } @@ -110,8 +108,7 @@ string senderName /// help keyword /// name of event sender /// Timestamp when event was created - public BuildErrorEventArgs - ( + public BuildErrorEventArgs( string subcategory, string code, string file, @@ -122,8 +119,7 @@ public BuildErrorEventArgs string message, string helpKeyword, string senderName, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, null, eventTimestamp, null) { // do nothing @@ -145,8 +141,7 @@ DateTime eventTimestamp /// name of event sender /// Timestamp when event was created /// message arguments - public BuildErrorEventArgs - ( + public BuildErrorEventArgs( string subcategory, string code, string file, @@ -158,8 +153,7 @@ public BuildErrorEventArgs string helpKeyword, string senderName, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, null, eventTimestamp, messageArgs) { // do nothing @@ -181,8 +175,7 @@ params object[] messageArgs /// name of event sender /// Timestamp when event was created /// message arguments - public BuildErrorEventArgs - ( + public BuildErrorEventArgs( string subcategory, string code, string file, @@ -195,8 +188,7 @@ public BuildErrorEventArgs string senderName, string helpLink, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) : base(message, helpKeyword, senderName, eventTimestamp, messageArgs) { this.subcategory = subcategory; diff --git a/src/Framework/BuildEventArgs.cs b/src/Framework/BuildEventArgs.cs index df29067bea9..01daed1341a 100644 --- a/src/Framework/BuildEventArgs.cs +++ b/src/Framework/BuildEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -175,7 +175,7 @@ public BuildEventContext? BuildEventContext set => buildEventContext = value; } -#region CustomSerializationToStream + #region CustomSerializationToStream /// /// Serializes to a stream through a binary writer /// @@ -249,9 +249,9 @@ internal virtual void CreateFromStream(BinaryReader reader, int version) } } } -#endregion + #endregion -#region SetSerializationDefaults + #region SetSerializationDefaults /// /// Run before the object has been deserialized /// UNDONE (Logging.) Can this and the next function go away, and instead return a BuildEventContext.Invalid from diff --git a/src/Framework/BuildEventContext.cs b/src/Framework/BuildEventContext.cs index 92e7673f67a..e27b37f3f67 100644 --- a/src/Framework/BuildEventContext.cs +++ b/src/Framework/BuildEventContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -56,13 +56,11 @@ public class BuildEventContext /// /// This is the original constructor. No one should ever use this except internally for backward compatibility. /// - public BuildEventContext - ( + public BuildEventContext( int nodeId, int targetId, int projectContextId, - int taskId - ) + int taskId) : this(InvalidSubmissionId, nodeId, InvalidEvaluationId, InvalidProjectInstanceId, projectContextId, targetId, taskId) { // UNDONE: This is obsolete. @@ -71,14 +69,12 @@ int taskId /// /// Constructs a BuildEventContext with a specified project instance id. /// - public BuildEventContext - ( + public BuildEventContext( int nodeId, int projectInstanceId, int projectContextId, int targetId, - int taskId - ) + int taskId) : this(InvalidSubmissionId, nodeId, InvalidEvaluationId, projectInstanceId, projectContextId, targetId, taskId) { } @@ -86,15 +82,13 @@ int taskId /// /// Constructs a BuildEventContext with a specific submission id /// - public BuildEventContext - ( + public BuildEventContext( int submissionId, int nodeId, int projectInstanceId, int projectContextId, int targetId, - int taskId - ) + int taskId) : this(submissionId, nodeId, InvalidEvaluationId, projectInstanceId, projectContextId, targetId, taskId) { } @@ -102,16 +96,14 @@ int taskId /// /// Constructs a BuildEventContext /// - public BuildEventContext - ( + public BuildEventContext( int submissionId, int nodeId, int evaluationId, int projectInstanceId, int projectContextId, int targetId, - int taskId - ) + int taskId) { _submissionId = submissionId; _nodeId = nodeId; diff --git a/src/Framework/BuildFinishedEventArgs.cs b/src/Framework/BuildFinishedEventArgs.cs index a496eefb701..ed5eb92295a 100644 --- a/src/Framework/BuildFinishedEventArgs.cs +++ b/src/Framework/BuildFinishedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -39,12 +39,10 @@ protected BuildFinishedEventArgs() /// text message /// help keyword /// True indicates a successful build - public BuildFinishedEventArgs - ( + public BuildFinishedEventArgs( string? message, string? helpKeyword, - bool succeeded - ) + bool succeeded) : this(message, helpKeyword, succeeded, DateTime.UtcNow) { } @@ -56,13 +54,11 @@ bool succeeded /// help keyword /// True indicates a successful build /// Timestamp when the event was created - public BuildFinishedEventArgs - ( + public BuildFinishedEventArgs( string? message, string? helpKeyword, bool succeeded, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(message, helpKeyword, succeeded, eventTimestamp, null) { // do nothing @@ -76,14 +72,12 @@ DateTime eventTimestamp /// True indicates a successful build /// Timestamp when the event was created /// message arguments - public BuildFinishedEventArgs - ( + public BuildFinishedEventArgs( string? message, string? helpKeyword, bool succeeded, DateTime eventTimestamp, - params object[]? messageArgs - ) + params object[]? messageArgs) : base(message, helpKeyword, "MSBuild", eventTimestamp, messageArgs) { this.succeeded = succeeded; diff --git a/src/Framework/BuildMessageEventArgs.cs b/src/Framework/BuildMessageEventArgs.cs index e65cf09bb59..23083d8cd6a 100644 --- a/src/Framework/BuildMessageEventArgs.cs +++ b/src/Framework/BuildMessageEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -60,13 +60,11 @@ protected BuildMessageEventArgs() /// help keyword /// name of event sender /// importance of the message - public BuildMessageEventArgs - ( + public BuildMessageEventArgs( string message, string helpKeyword, string senderName, - MessageImportance importance - ) + MessageImportance importance) : this(message, helpKeyword, senderName, importance, DateTime.UtcNow) { } @@ -79,14 +77,12 @@ MessageImportance importance /// name of event sender /// importance of the message /// Timestamp when event was created - public BuildMessageEventArgs - ( + public BuildMessageEventArgs( string message, string helpKeyword, string senderName, MessageImportance importance, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(message, helpKeyword, senderName, importance, eventTimestamp, null) { // do nothing @@ -101,15 +97,13 @@ DateTime eventTimestamp /// importance of the message /// Timestamp when event was created /// message arguments - public BuildMessageEventArgs - ( + public BuildMessageEventArgs( string message, string helpKeyword, string senderName, MessageImportance importance, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) : this(null, null, null, 0, 0, 0, 0, message, helpKeyword, senderName, importance, eventTimestamp, messageArgs) { // do nothing @@ -129,8 +123,7 @@ params object[] messageArgs /// help keyword /// name of event sender /// importance of the message - public BuildMessageEventArgs - ( + public BuildMessageEventArgs( string subcategory, string code, string file, @@ -141,8 +134,7 @@ public BuildMessageEventArgs string message, string helpKeyword, string senderName, - MessageImportance importance - ) + MessageImportance importance) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, importance, DateTime.UtcNow) { // do nothing @@ -163,8 +155,7 @@ MessageImportance importance /// name of event sender /// importance of the message /// custom timestamp for the event - public BuildMessageEventArgs - ( + public BuildMessageEventArgs( string subcategory, string code, string file, @@ -176,8 +167,7 @@ public BuildMessageEventArgs string helpKeyword, string senderName, MessageImportance importance, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, importance, eventTimestamp, messageArgs: null) { // do nothing @@ -199,8 +189,7 @@ DateTime eventTimestamp /// importance of the message /// custom timestamp for the event /// message arguments - public BuildMessageEventArgs - ( + public BuildMessageEventArgs( string subcategory, string code, string file, @@ -213,8 +202,7 @@ public BuildMessageEventArgs string senderName, MessageImportance importance, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) : base(message, helpKeyword, senderName, eventTimestamp, messageArgs) { this.importance = importance; diff --git a/src/Framework/BuildStartedEventArgs.cs b/src/Framework/BuildStartedEventArgs.cs index ff0b6415c95..d4c2882c4f9 100644 --- a/src/Framework/BuildStartedEventArgs.cs +++ b/src/Framework/BuildStartedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -35,11 +35,9 @@ protected BuildStartedEventArgs() /// /// text message /// help keyword - public BuildStartedEventArgs - ( + public BuildStartedEventArgs( string message, - string helpKeyword - ) + string helpKeyword) : this(message, helpKeyword, DateTime.UtcNow) { // do nothing @@ -52,12 +50,10 @@ string helpKeyword /// text message /// help keyword /// A dictionary which lists the environment of the build when the build is started. - public BuildStartedEventArgs - ( + public BuildStartedEventArgs( string? message, string? helpKeyword, - IDictionary environmentOfBuild - ) + IDictionary environmentOfBuild) : this(message, helpKeyword, DateTime.UtcNow) { environmentOnBuildStart = environmentOfBuild; @@ -69,12 +65,10 @@ IDictionary environmentOfBuild /// text message /// help keyword /// Timestamp when the event was created - public BuildStartedEventArgs - ( + public BuildStartedEventArgs( string? message, string? helpKeyword, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(message, helpKeyword, eventTimestamp, null) { // do nothing @@ -87,13 +81,11 @@ DateTime eventTimestamp /// help keyword /// Timestamp when the event was created /// message args - public BuildStartedEventArgs - ( + public BuildStartedEventArgs( string? message, string? helpKeyword, DateTime eventTimestamp, - params object[]? messageArgs - ) + params object[]? messageArgs) : base(message, helpKeyword, "MSBuild", eventTimestamp, messageArgs) { // do nothing diff --git a/src/Framework/BuildStatusEventArgs.cs b/src/Framework/BuildStatusEventArgs.cs index c7a9e9ad0d5..c6edef25c8a 100644 --- a/src/Framework/BuildStatusEventArgs.cs +++ b/src/Framework/BuildStatusEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -35,12 +35,10 @@ protected BuildStatusEventArgs() /// text message /// help keyword /// name of event sender - protected BuildStatusEventArgs - ( + protected BuildStatusEventArgs( string? message, string? helpKeyword, - string? senderName - ) + string? senderName) : this(message, helpKeyword, senderName, DateTime.UtcNow) { // do nothing @@ -54,13 +52,11 @@ protected BuildStatusEventArgs /// help keyword /// name of event sender /// Timestamp when event was created - protected BuildStatusEventArgs - ( + protected BuildStatusEventArgs( string? message, string? helpKeyword, string? senderName, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(message, helpKeyword, senderName, eventTimestamp, messageArgs: null) { // do nothing @@ -74,14 +70,12 @@ DateTime eventTimestamp /// name of event sender /// Timestamp when event was created /// Optional arguments for formatting the message string. - protected BuildStatusEventArgs - ( + protected BuildStatusEventArgs( string? message, string? helpKeyword, string? senderName, DateTime eventTimestamp, - params object[]? messageArgs - ) + params object[]? messageArgs) : base(message, helpKeyword, senderName, eventTimestamp, messageArgs) { // do nothing diff --git a/src/Framework/BuildWarningEventArgs.cs b/src/Framework/BuildWarningEventArgs.cs index ea8d963afc3..8e2e522147b 100644 --- a/src/Framework/BuildWarningEventArgs.cs +++ b/src/Framework/BuildWarningEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -43,8 +43,7 @@ protected BuildWarningEventArgs() /// text message /// help keyword /// name of event sender - public BuildWarningEventArgs - ( + public BuildWarningEventArgs( string subcategory, string code, string file, @@ -54,8 +53,7 @@ public BuildWarningEventArgs int endColumnNumber, string message, string helpKeyword, - string senderName - ) + string senderName) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, DateTime.UtcNow) { } @@ -74,8 +72,7 @@ string senderName /// help keyword /// name of event sender /// custom timestamp for the event - public BuildWarningEventArgs - ( + public BuildWarningEventArgs( string subcategory, string code, string file, @@ -86,8 +83,7 @@ public BuildWarningEventArgs string message, string helpKeyword, string senderName, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, eventTimestamp, null) { // do nothing @@ -108,8 +104,7 @@ DateTime eventTimestamp /// name of event sender /// custom timestamp for the event /// message arguments - public BuildWarningEventArgs - ( + public BuildWarningEventArgs( string subcategory, string code, string file, @@ -121,8 +116,7 @@ public BuildWarningEventArgs string helpKeyword, string senderName, DateTime eventTimestamp, - params object[] messageArgs - ) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, null, eventTimestamp, messageArgs) + params object[] messageArgs) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, null, eventTimestamp, messageArgs) { // do nothing } @@ -143,8 +137,7 @@ params object[] messageArgs /// name of event sender /// custom timestamp for the event /// message arguments - public BuildWarningEventArgs - ( + public BuildWarningEventArgs( string subcategory, string code, string file, @@ -157,8 +150,7 @@ public BuildWarningEventArgs string senderName, string helpLink, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) : base(message, helpKeyword, senderName, eventTimestamp, messageArgs) { this.subcategory = subcategory; diff --git a/src/Framework/ChangeWaves.cs b/src/Framework/ChangeWaves.cs index 91acdc9bc59..9b2de23aa47 100644 --- a/src/Framework/ChangeWaves.cs +++ b/src/Framework/ChangeWaves.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Linq; diff --git a/src/Framework/CriticalBuildMessageEventArgs.cs b/src/Framework/CriticalBuildMessageEventArgs.cs index 9fe9544de38..7cac3c342f2 100644 --- a/src/Framework/CriticalBuildMessageEventArgs.cs +++ b/src/Framework/CriticalBuildMessageEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -32,8 +32,7 @@ public class CriticalBuildMessageEventArgs : BuildMessageEventArgs /// text message /// help keyword /// name of event sender - public CriticalBuildMessageEventArgs - ( + public CriticalBuildMessageEventArgs( string subcategory, string code, string file, @@ -43,8 +42,7 @@ public CriticalBuildMessageEventArgs int endColumnNumber, string message, string helpKeyword, - string senderName - ) + string senderName) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, DateTime.UtcNow) { // do nothing @@ -64,8 +62,7 @@ string senderName /// help keyword /// name of event sender /// custom timestamp for the event - public CriticalBuildMessageEventArgs - ( + public CriticalBuildMessageEventArgs( string subcategory, string code, string file, @@ -76,8 +73,7 @@ public CriticalBuildMessageEventArgs string message, string helpKeyword, string senderName, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, eventTimestamp, null) { // do nothing @@ -98,8 +94,7 @@ DateTime eventTimestamp /// name of event sender /// custom timestamp for the event /// message arguments - public CriticalBuildMessageEventArgs - ( + public CriticalBuildMessageEventArgs( string subcategory, string code, string file, @@ -111,8 +106,7 @@ public CriticalBuildMessageEventArgs string helpKeyword, string senderName, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) //// Force importance to High. : base(subcategory, code, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, helpKeyword, senderName, MessageImportance.High, eventTimestamp, messageArgs) { diff --git a/src/Framework/CustomBuildEventArgs.cs b/src/Framework/CustomBuildEventArgs.cs index 69523a573b3..3310b398844 100644 --- a/src/Framework/CustomBuildEventArgs.cs +++ b/src/Framework/CustomBuildEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -34,12 +34,10 @@ protected CustomBuildEventArgs() /// text message /// help keyword /// name of sender - protected CustomBuildEventArgs - ( + protected CustomBuildEventArgs( string message, string helpKeyword, - string senderName - ) + string senderName) : this(message, helpKeyword, senderName, DateTime.UtcNow) { // do nothing @@ -52,13 +50,11 @@ string senderName /// help keyword /// name of sender /// Timestamp when event was created - protected CustomBuildEventArgs - ( + protected CustomBuildEventArgs( string message, string helpKeyword, string senderName, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(message, helpKeyword, senderName, eventTimestamp, null) { // do nothing @@ -72,14 +68,12 @@ DateTime eventTimestamp /// name of sender /// Timestamp when event was created /// Message arguments - protected CustomBuildEventArgs - ( + protected CustomBuildEventArgs( string message, string helpKeyword, string senderName, DateTime eventTimestamp, - params object[] messageArgs - ) + params object[] messageArgs) : base(message, helpKeyword, senderName, eventTimestamp, messageArgs) { // do nothing diff --git a/src/Framework/Debugging/CommonWriter.cs b/src/Framework/Debugging/CommonWriter.cs index db17705ce15..8249abd4e55 100644 --- a/src/Framework/Debugging/CommonWriter.cs +++ b/src/Framework/Debugging/CommonWriter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/EngineServices.cs b/src/Framework/EngineServices.cs index 43b8d10f7c6..7270bb0b681 100644 --- a/src/Framework/EngineServices.cs +++ b/src/Framework/EngineServices.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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,7 +24,7 @@ public abstract class EngineServices /// An explicit version of this class. Must be incremented whenever new members are added. Derived classes should override /// the property to return the version actually being implemented. /// - public virtual int Version => Version1; // Not updated since we have not shipped 17.0 yet + public virtual int Version => Version1; // Not updated since we have not shipped 17.0 yet. This comment is meant to bypass RequiredVersionBumps check in build.ps1 for PR #8336. If the changes in the file are cosmetic, change PR# in this comment to silence the build error on CI build. /// /// Returns if the given message importance is not guaranteed to be ignored by registered loggers. diff --git a/src/Framework/EnvironmentVariableReadEventArgs.cs b/src/Framework/EnvironmentVariableReadEventArgs.cs index 83391fe7def..3d246fb6c03 100644 --- a/src/Framework/EnvironmentVariableReadEventArgs.cs +++ b/src/Framework/EnvironmentVariableReadEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/ErrorUtilities.cs b/src/Framework/ErrorUtilities.cs index f90c6cc9d82..ca0375ee54d 100644 --- a/src/Framework/ErrorUtilities.cs +++ b/src/Framework/ErrorUtilities.cs @@ -29,11 +29,9 @@ internal class FrameworkErrorUtilities /// /// /// - internal static void VerifyThrow - ( + internal static void VerifyThrow( bool condition, - string unformattedMessage - ) + string unformattedMessage) { if (!condition) { diff --git a/src/Framework/ExternalProjectFinishedEventArgs.cs b/src/Framework/ExternalProjectFinishedEventArgs.cs index 94d5b7da698..e3960625c3a 100644 --- a/src/Framework/ExternalProjectFinishedEventArgs.cs +++ b/src/Framework/ExternalProjectFinishedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -36,14 +36,12 @@ protected ExternalProjectFinishedEventArgs() /// name of the object sending this event /// project name /// true indicates project built successfully - public ExternalProjectFinishedEventArgs - ( + public ExternalProjectFinishedEventArgs( string message, string helpKeyword, string senderName, string projectFile, - bool succeeded - ) + bool succeeded) : this(message, helpKeyword, senderName, projectFile, succeeded, DateTime.UtcNow) { } @@ -57,15 +55,13 @@ bool succeeded /// project name /// true indicates project built successfully /// Timestamp when event was created - public ExternalProjectFinishedEventArgs - ( + public ExternalProjectFinishedEventArgs( string message, string helpKeyword, string senderName, string projectFile, bool succeeded, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, senderName, eventTimestamp) { this.projectFile = projectFile; diff --git a/src/Framework/ExternalProjectStartedEventArgs.cs b/src/Framework/ExternalProjectStartedEventArgs.cs index 6828ae736a9..80488df82e9 100644 --- a/src/Framework/ExternalProjectStartedEventArgs.cs +++ b/src/Framework/ExternalProjectStartedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -36,14 +36,12 @@ protected ExternalProjectStartedEventArgs() /// name of the object sending this event /// project name /// targets we are going to build (empty indicates default targets) - public ExternalProjectStartedEventArgs - ( + public ExternalProjectStartedEventArgs( string message, string helpKeyword, string senderName, string projectFile, - string targetNames - ) + string targetNames) : this(message, helpKeyword, senderName, projectFile, targetNames, DateTime.UtcNow) { } @@ -57,15 +55,13 @@ string targetNames /// project name /// targets we are going to build (empty indicates default targets) /// Timestamp when the event was created - public ExternalProjectStartedEventArgs - ( + public ExternalProjectStartedEventArgs( string message, string helpKeyword, string senderName, string projectFile, string targetNames, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, senderName, eventTimestamp) { this.projectFile = projectFile; diff --git a/src/Framework/FileClassifier.cs b/src/Framework/FileClassifier.cs index 9ea92f4fccb..966f51bd5c4 100644 --- a/src/Framework/FileClassifier.cs +++ b/src/Framework/FileClassifier.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Framework/IBuildEngine.cs b/src/Framework/IBuildEngine.cs index 68aac5eea4f..1a9cef48139 100644 --- a/src/Framework/IBuildEngine.cs +++ b/src/Framework/IBuildEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -94,12 +94,10 @@ string ProjectFileOfTaskNode /// to the child project (can be null). The key and value should both be strings. /// The outputs of each specified target (can be null). /// true, if build was successful - bool BuildProjectFile - ( + bool BuildProjectFile( string projectFileName, string[] targetNames, IDictionary globalProperties, - IDictionary targetOutputs - ); + IDictionary targetOutputs); } } diff --git a/src/Framework/IBuildEngine10.cs b/src/Framework/IBuildEngine10.cs index e8ac6071e21..63b58e79d1f 100644 --- a/src/Framework/IBuildEngine10.cs +++ b/src/Framework/IBuildEngine10.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IBuildEngine2.cs b/src/Framework/IBuildEngine2.cs index 169c1a8f7ba..7ffd55e9844 100644 --- a/src/Framework/IBuildEngine2.cs +++ b/src/Framework/IBuildEngine2.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -40,14 +40,12 @@ bool IsRunningMultipleNodes /// The outputs of each specified target (can be null). /// A tools version recognized by the Engine that will be used during this build (can be null). /// true, if build was successful - bool BuildProjectFile - ( + bool BuildProjectFile( string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs, - string toolsVersion - ); + string toolsVersion); /// /// This method allows tasks to initiate a build on a @@ -72,15 +70,13 @@ string toolsVersion /// If true the project will be unloaded once the /// operation is completed /// true, if build was successful - bool BuildProjectFilesInParallel - ( + bool BuildProjectFilesInParallel( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, - bool unloadProjectsOnCompletion - ); + bool unloadProjectsOnCompletion); } } diff --git a/src/Framework/IBuildEngine3.cs b/src/Framework/IBuildEngine3.cs index 0ab02ddaafc..faa0459699d 100644 --- a/src/Framework/IBuildEngine3.cs +++ b/src/Framework/IBuildEngine3.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; @@ -33,15 +33,13 @@ public interface IBuildEngine3 : IBuildEngine2 /// A tools version recognized by the Engine that will be used during this build (can be null). /// Should the target outputs be returned in the BuildEngineResult /// Returns a structure containing the success or failure of the build and the target outputs by project. - BuildEngineResult BuildProjectFilesInParallel - ( + BuildEngineResult BuildProjectFilesInParallel( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList[] removeGlobalProperties, string[] toolsVersion, - bool returnTargetOutputs - ); + bool returnTargetOutputs); /// /// Informs the system that this task has a long-running out-of-process component and other work can be done in the diff --git a/src/Framework/IBuildEngine4.cs b/src/Framework/IBuildEngine4.cs index 09fa5277ba0..650c60b9760 100644 --- a/src/Framework/IBuildEngine4.cs +++ b/src/Framework/IBuildEngine4.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; diff --git a/src/Framework/IBuildEngine5.cs b/src/Framework/IBuildEngine5.cs index 3bb99e30e6e..9d09c7ee4d2 100644 --- a/src/Framework/IBuildEngine5.cs +++ b/src/Framework/IBuildEngine5.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Framework/IBuildEngine6.cs b/src/Framework/IBuildEngine6.cs index 4a0fdf41710..2c3763d229b 100644 --- a/src/Framework/IBuildEngine6.cs +++ b/src/Framework/IBuildEngine6.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Framework/IBuildEngine7.cs b/src/Framework/IBuildEngine7.cs index d08af94fc04..c5fcd4c18a4 100644 --- a/src/Framework/IBuildEngine7.cs +++ b/src/Framework/IBuildEngine7.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IBuildEngine8.cs b/src/Framework/IBuildEngine8.cs index f337b27694a..7d08daa0c4d 100644 --- a/src/Framework/IBuildEngine8.cs +++ b/src/Framework/IBuildEngine8.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IBuildEngine9.cs b/src/Framework/IBuildEngine9.cs index aac0cc87141..aa000422db9 100644 --- a/src/Framework/IBuildEngine9.cs +++ b/src/Framework/IBuildEngine9.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/ICancelableTask.cs b/src/Framework/ICancelableTask.cs index e91d51ecd78..6fc51d271fa 100644 --- a/src/Framework/ICancelableTask.cs +++ b/src/Framework/ICancelableTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IEventRedirector.cs b/src/Framework/IEventRedirector.cs index 4b385c39c69..00437843e32 100644 --- a/src/Framework/IEventRedirector.cs +++ b/src/Framework/IEventRedirector.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IEventSource.cs b/src/Framework/IEventSource.cs index 8f49eccf2d1..3c2599fceba 100644 --- a/src/Framework/IEventSource.cs +++ b/src/Framework/IEventSource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IEventSource2.cs b/src/Framework/IEventSource2.cs index 32be40c2abd..6a7121df87d 100644 --- a/src/Framework/IEventSource2.cs +++ b/src/Framework/IEventSource2.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IEventSource3.cs b/src/Framework/IEventSource3.cs index e461ed4865d..db6fd8c0ef6 100644 --- a/src/Framework/IEventSource3.cs +++ b/src/Framework/IEventSource3.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IEventSource4.cs b/src/Framework/IEventSource4.cs index b16ec11ee9a..872024911f1 100644 --- a/src/Framework/IEventSource4.cs +++ b/src/Framework/IEventSource4.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IForwardingLogger.cs b/src/Framework/IForwardingLogger.cs index 95550550dad..d68921fc550 100644 --- a/src/Framework/IForwardingLogger.cs +++ b/src/Framework/IForwardingLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/IGeneratedTask.cs b/src/Framework/IGeneratedTask.cs index 3629d679b70..f635874e89b 100644 --- a/src/Framework/IGeneratedTask.cs +++ b/src/Framework/IGeneratedTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; diff --git a/src/Framework/ILogger.cs b/src/Framework/ILogger.cs index 873677cc9cb..5d999b7b08d 100644 --- a/src/Framework/ILogger.cs +++ b/src/Framework/ILogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Framework/IMetadataContainer.cs b/src/Framework/IMetadataContainer.cs index eacb445c576..7762bc33e31 100644 --- a/src/Framework/IMetadataContainer.cs +++ b/src/Framework/IMetadataContainer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Framework/INodeLogger.cs b/src/Framework/INodeLogger.cs index fabcbc70ec9..4865646daf9 100644 --- a/src/Framework/INodeLogger.cs +++ b/src/Framework/INodeLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Framework/IProjectElement.cs b/src/Framework/IProjectElement.cs index 913f06b0e51..d7f74708af0 100644 --- a/src/Framework/IProjectElement.cs +++ b/src/Framework/IProjectElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/ITask.cs b/src/Framework/ITask.cs index f4cc8979a6c..b4265a70113 100644 --- a/src/Framework/ITask.cs +++ b/src/Framework/ITask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/ITaskFactory.cs b/src/Framework/ITaskFactory.cs index a7b07159679..65e1dd7690d 100644 --- a/src/Framework/ITaskFactory.cs +++ b/src/Framework/ITaskFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/ITaskFactory2.cs b/src/Framework/ITaskFactory2.cs index c498b989789..14fb266c913 100644 --- a/src/Framework/ITaskFactory2.cs +++ b/src/Framework/ITaskFactory2.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Framework/ITaskHost.cs b/src/Framework/ITaskHost.cs index cbad16b9efe..d4a0f207409 100644 --- a/src/Framework/ITaskHost.cs +++ b/src/Framework/ITaskHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; diff --git a/src/Framework/ITaskItem.cs b/src/Framework/ITaskItem.cs index b1de1f3bf4f..a69eeec483c 100644 --- a/src/Framework/ITaskItem.cs +++ b/src/Framework/ITaskItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Framework/ITaskItem2.cs b/src/Framework/ITaskItem2.cs index f55467b85e9..d9095e42038 100644 --- a/src/Framework/ITaskItem2.cs +++ b/src/Framework/ITaskItem2.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Framework/ITaskItemExtensions.cs b/src/Framework/ITaskItemExtensions.cs index 090a95eeb07..9c4f18ea8ef 100644 --- a/src/Framework/ITaskItemExtensions.cs +++ b/src/Framework/ITaskItemExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Framework/ImmutableFilesTimestampCache.cs b/src/Framework/ImmutableFilesTimestampCache.cs index c20b768b74f..dd8f2e8465b 100644 --- a/src/Framework/ImmutableFilesTimestampCache.cs +++ b/src/Framework/ImmutableFilesTimestampCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Framework/InternalErrorException.cs b/src/Framework/InternalErrorException.cs index b87f1a32a6d..86383e09bbb 100644 --- a/src/Framework/InternalErrorException.cs +++ b/src/Framework/InternalErrorException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -30,10 +30,8 @@ internal InternalErrorException() : base() /// /// Creates an instance of this exception using the given message. /// - internal InternalErrorException - ( - String message - ) : + internal InternalErrorException( + String message) : base("MSB0001: Internal MSBuild Error: " + message) { ConsiderDebuggerLaunch(message, null); @@ -44,11 +42,9 @@ String message /// Adds the inner exception's details to the exception message because most bug reporters don't bother /// to provide the inner exception details which is typically what we care about. /// - internal InternalErrorException - ( + internal InternalErrorException( String message, - Exception innerException - ) : + Exception innerException) : base("MSB0001: Internal MSBuild Error: " + message + (innerException == null ? String.Empty : ("\n=============\n" + innerException.ToString() + "\n\n")), innerException) { ConsiderDebuggerLaunch(message, innerException); diff --git a/src/Framework/LazyFormattedBuildEventArgs.cs b/src/Framework/LazyFormattedBuildEventArgs.cs index 2597304fee5..4b4dc6493a6 100644 --- a/src/Framework/LazyFormattedBuildEventArgs.cs +++ b/src/Framework/LazyFormattedBuildEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -40,12 +40,10 @@ private protected override string? FormattedMessage /// text message. /// help keyword. /// name of event sender. - public LazyFormattedBuildEventArgs - ( + public LazyFormattedBuildEventArgs( string? message, string? helpKeyword, - string? senderName - ) + string? senderName) : this(message, helpKeyword, senderName, DateTime.Now, null) { } @@ -58,14 +56,12 @@ public LazyFormattedBuildEventArgs /// name of event sender. /// Timestamp when event was created. /// Message arguments. - public LazyFormattedBuildEventArgs - ( + public LazyFormattedBuildEventArgs( string? message, string? helpKeyword, string? senderName, DateTime eventTimestamp, - params object[]? messageArgs - ) + params object[]? messageArgs) : base(message, helpKeyword, senderName, eventTimestamp) { argumentsOrFormattedMessage = messageArgs; diff --git a/src/Framework/LoadInSeparateAppDomainAttribute.cs b/src/Framework/LoadInSeparateAppDomainAttribute.cs index 9a26afec1f4..801e4df43da 100644 --- a/src/Framework/LoadInSeparateAppDomainAttribute.cs +++ b/src/Framework/LoadInSeparateAppDomainAttribute.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/LoggerException.cs b/src/Framework/LoggerException.cs index f99fab5d903..ba423ceba87 100644 --- a/src/Framework/LoggerException.cs +++ b/src/Framework/LoggerException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -96,7 +96,7 @@ protected LoggerException(SerializationInfo info, StreamingContext context) #if FEATURE_SECURITY_PERMISSIONS [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] #endif - override public void GetObjectData(SerializationInfo info, StreamingContext context) + public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); diff --git a/src/Framework/MSBuildEventSource.cs b/src/Framework/MSBuildEventSource.cs index 89b8370c392..dbf6df5b071 100644 --- a/src/Framework/MSBuildEventSource.cs +++ b/src/Framework/MSBuildEventSource.cs @@ -1,4 +1,7 @@ -using System.Diagnostics.Tracing; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics.Tracing; #nullable disable @@ -646,7 +649,7 @@ public void LoadAssemblyAndFindTypeStop(string assemblyPath, int numberOfPublicT { WriteEvent(88, assemblyPath, numberOfPublicTypesSearched); } - + [Event(89, Keywords = Keywords.All)] public void MSBuildServerBuildStart(string commandLine) { diff --git a/src/Framework/MetaProjectGeneratedEventArgs.cs b/src/Framework/MetaProjectGeneratedEventArgs.cs index fa03336cf0b..c18111d9459 100644 --- a/src/Framework/MetaProjectGeneratedEventArgs.cs +++ b/src/Framework/MetaProjectGeneratedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/NativeMethods.cs b/src/Framework/NativeMethods.cs index dfbe41864a8..b5bdead5c07 100644 --- a/src/Framework/NativeMethods.cs +++ b/src/Framework/NativeMethods.cs @@ -23,7 +23,7 @@ namespace Microsoft.Build.Framework; internal static class NativeMethods { -#region Constants + #region Constants internal const uint ERROR_INSUFFICIENT_BUFFER = 0x8007007A; internal const uint STARTUP_LOADER_SAFEMODE = 0x10; @@ -72,9 +72,9 @@ internal static class NativeMethods internal const uint WAIT_OBJECT_0 = 0x00000000; internal const uint WAIT_TIMEOUT = 0x00000102; -#endregion + #endregion -#region Enums + #region Enums private enum PROCESSINFOCLASS : int { @@ -534,7 +534,7 @@ public static int GetLogicalCoreCount() /// https://github.com/dotnet/runtime/blob/221ad5b728f93489655df290c1ea52956ad8f51c/src/libraries/System.Runtime.Extensions/src/System/Environment.Windows.cs#L171-L210 /// [SupportedOSPlatform("windows")] - private unsafe static int GetLogicalCoreCountOnWindows() + private static unsafe int GetLogicalCoreCountOnWindows() { uint len = 0; const int ERROR_INSUFFICIENT_BUFFER = 122; @@ -573,9 +573,9 @@ private unsafe static int GetLogicalCoreCountOnWindows() return -1; } -#endregion + #endregion -#region Member data + #region Member data internal static bool HasMaxPath => MaxPath == MAX_PATH; @@ -658,7 +658,7 @@ internal static bool IsUnixLike internal static bool IsLinux { #if CLR2COMPATIBILITY - get { return false; } + get { return false; } #else get { return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); } #endif @@ -670,7 +670,7 @@ internal static bool IsLinux internal static bool IsBSD { #if CLR2COMPATIBILITY - get { return false; } + get { return false; } #else get { @@ -692,7 +692,10 @@ internal static bool IsMono { get { - if (_isMono != null) return _isMono.Value; + if (_isMono != null) + { + return _isMono.Value; + } lock (IsMonoLock) { @@ -719,7 +722,7 @@ internal static bool IsMono internal static bool IsWindows { #if CLR2COMPATIBILITY - get { return true; } + get { return true; } #else get { @@ -739,7 +742,7 @@ internal static bool IsWindows internal static bool IsOSX { #if CLR2COMPATIBILITY - get { return false; } + get { return false; } #else get { @@ -882,9 +885,9 @@ private static SystemInformationData SystemInformation /// internal static ProcessorArchitectures ProcessorArchitectureNative => SystemInformation.ProcessorArchitectureTypeNative; -#endregion + #endregion -#region Wrapper methods + #region Wrapper methods [DllImport("kernel32.dll", SetLastError = true)] @@ -1429,7 +1432,7 @@ internal static List> GetChildProcessIds(in /// Internal, optimized GetCurrentDirectory implementation that simply delegates to the native method /// /// - internal unsafe static string GetCurrentDirectory() + internal static unsafe string GetCurrentDirectory() { #if FEATURE_LEGACY_GETCURRENTDIRECTORY if (IsWindows) @@ -1444,7 +1447,7 @@ internal unsafe static string GetCurrentDirectory() } [SupportedOSPlatform("windows")] - private unsafe static int GetCurrentDirectoryWin32(int nBufferLength, char* lpBuffer) + private static unsafe int GetCurrentDirectoryWin32(int nBufferLength, char* lpBuffer) { int pathLength = GetCurrentDirectory(nBufferLength, lpBuffer); VerifyThrowWin32Result(pathLength); @@ -1452,7 +1455,7 @@ private unsafe static int GetCurrentDirectoryWin32(int nBufferLength, char* lpBu } [SupportedOSPlatform("windows")] - internal unsafe static string GetFullPath(string path) + internal static unsafe string GetFullPath(string path) { int bufferSize = GetFullPathWin32(path, 0, null, IntPtr.Zero); char* buffer = stackalloc char[bufferSize]; @@ -1462,7 +1465,7 @@ internal unsafe static string GetFullPath(string path) } [SupportedOSPlatform("windows")] - private unsafe static int GetFullPathWin32(string target, int bufferLength, char* buffer, IntPtr mustBeZero) + private static unsafe int GetFullPathWin32(string target, int bufferLength, char* buffer, IntPtr mustBeZero) { int pathLength = GetFullPathName(target, bufferLength, buffer, mustBeZero); VerifyThrowWin32Result(pathLength); @@ -1476,7 +1479,7 @@ private unsafe static int GetFullPathWin32(string target, int bufferLength, char /// The length of the buffer. /// The string. /// True only if the contents of and the first characters in are identical. - private unsafe static bool AreStringsEqual(char* buffer, int len, string s) + private static unsafe bool AreStringsEqual(char* buffer, int len, string s) { if (len != s.Length) { @@ -1560,7 +1563,7 @@ internal static void VerifyThrowWin32Result(int result) [DllImport("kernel32.dll")] [SupportedOSPlatform("windows")] internal static extern uint GetFileType(IntPtr hFile); - + [DllImport("kernel32.dll")] internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode); @@ -1570,7 +1573,7 @@ internal static void VerifyThrowWin32Result(int result) [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Justification = "Using unmanaged equivalent for performance reasons")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [SupportedOSPlatform("windows")] - internal unsafe static extern int GetCurrentDirectory(int nBufferLength, char* lpBuffer); + internal static extern unsafe int GetCurrentDirectory(int nBufferLength, char* lpBuffer); [SuppressMessage("Microsoft.Usage", "CA2205:UseManagedEquivalentsOfWin32Api", Justification = "Using unmanaged equivalent for performance reasons")] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "SetCurrentDirectory")] @@ -1598,7 +1601,7 @@ internal static bool SetCurrentDirectory(string path) [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] [SupportedOSPlatform("windows")] - internal static unsafe extern int GetFullPathName(string target, int bufferLength, char* buffer, IntPtr mustBeZero); + internal static extern unsafe int GetFullPathName(string target, int bufferLength, char* buffer, IntPtr mustBeZero); [DllImport("KERNEL32.DLL")] [SupportedOSPlatform("windows")] @@ -1654,8 +1657,7 @@ internal static extern SafeFileHandle CreateFile( IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, - IntPtr hTemplateFile - ); + IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] [SupportedOSPlatform("windows")] @@ -1663,8 +1665,7 @@ internal static extern bool GetFileTime( SafeFileHandle hFile, out FILETIME lpCreationTime, out FILETIME lpLastAccessTime, - out FILETIME lpLastWriteTime - ); + out FILETIME lpLastWriteTime); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] @@ -1731,6 +1732,6 @@ internal static bool FileOrDirectoryExistsWindows(string path) return GetFileAttributesEx(path, 0, ref data); } -#endregion + #endregion } diff --git a/src/Framework/NullableAttributes.cs b/src/Framework/NullableAttributes.cs index 86145426936..4e46baa38f0 100644 --- a/src/Framework/NullableAttributes.cs +++ b/src/Framework/NullableAttributes.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // This was copied from https://github.com/dotnet/runtime/blob/39b9607807f29e48cae4652cd74735182b31182e/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs // and updated to have the scope of the attributes be internal. diff --git a/src/Framework/OutputAttribute.cs b/src/Framework/OutputAttribute.cs index 0a1166b8654..b29cb816377 100644 --- a/src/Framework/OutputAttribute.cs +++ b/src/Framework/OutputAttribute.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/Profiler/EvaluationIdProvider.cs b/src/Framework/Profiler/EvaluationIdProvider.cs index 0b0f8f491a2..e81cc016beb 100644 --- a/src/Framework/Profiler/EvaluationIdProvider.cs +++ b/src/Framework/Profiler/EvaluationIdProvider.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.Threading; diff --git a/src/Framework/Profiler/EvaluationLocation.cs b/src/Framework/Profiler/EvaluationLocation.cs index f37093e78a0..43dc75bf28d 100644 --- a/src/Framework/Profiler/EvaluationLocation.cs +++ b/src/Framework/Profiler/EvaluationLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -143,7 +143,7 @@ public EvaluationLocation(long id, long? parentId, EvaluationPass evaluationPass int? line, string elementName, string elementDescription, EvaluationLocationKind kind) { Id = id; - ParentId = parentId == EmptyLocation.Id? null : parentId; // The empty location doesn't count as a parent id, since it's just a dummy starting point + ParentId = parentId == EmptyLocation.Id ? null : parentId; // The empty location doesn't count as a parent id, since it's just a dummy starting point EvaluationPass = evaluationPass; EvaluationPassDescription = evaluationPassDescription; File = file; @@ -181,7 +181,7 @@ public EvaluationLocation(EvaluationPass evaluationPass, string evaluationPassDe /// An empty location, used as the starting instance. /// public static EvaluationLocation EmptyLocation { get; } = CreateEmptyLocation(); - + /// public EvaluationLocation WithEvaluationPass(EvaluationPass evaluationPass, string passDescription = null) { @@ -240,7 +240,7 @@ public override bool Equals(object obj) Line == other.Line && ElementName == other.ElementName && ElementDescription == other.ElementDescription && - Kind == other.Kind; + Kind == other.Kind; } return false; } diff --git a/src/Framework/Profiler/ProfilerResult.cs b/src/Framework/Profiler/ProfilerResult.cs index 70bd4ebed95..9c95f3ae56a 100644 --- a/src/Framework/Profiler/ProfilerResult.cs +++ b/src/Framework/Profiler/ProfilerResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/ProjectEvaluationFinishedEventArgs.cs b/src/Framework/ProjectEvaluationFinishedEventArgs.cs index e38b8cde8a1..328e2fb7570 100644 --- a/src/Framework/ProjectEvaluationFinishedEventArgs.cs +++ b/src/Framework/ProjectEvaluationFinishedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Framework/ProjectEvaluationStartedEventArgs.cs b/src/Framework/ProjectEvaluationStartedEventArgs.cs index 41c0f8154ff..6d231fe1428 100644 --- a/src/Framework/ProjectEvaluationStartedEventArgs.cs +++ b/src/Framework/ProjectEvaluationStartedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/ProjectFinishedEventArgs.cs b/src/Framework/ProjectFinishedEventArgs.cs index 04017a0f2d1..75e3fda981e 100644 --- a/src/Framework/ProjectFinishedEventArgs.cs +++ b/src/Framework/ProjectFinishedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -36,13 +36,11 @@ protected ProjectFinishedEventArgs() /// help keyword /// name of the project /// true indicates project built successfully - public ProjectFinishedEventArgs - ( + public ProjectFinishedEventArgs( string? message, string? helpKeyword, string? projectFile, - bool succeeded - ) + bool succeeded) : this(message, helpKeyword, projectFile, succeeded, DateTime.UtcNow) { } @@ -56,14 +54,12 @@ bool succeeded /// name of the project /// true indicates project built successfully /// Timestamp when the event was created - public ProjectFinishedEventArgs - ( + public ProjectFinishedEventArgs( string? message, string? helpKeyword, string? projectFile, bool succeeded, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.projectFile = projectFile; diff --git a/src/Framework/ProjectImportedEventArgs.cs b/src/Framework/ProjectImportedEventArgs.cs index a77e1344052..b51b4711e70 100644 --- a/src/Framework/ProjectImportedEventArgs.cs +++ b/src/Framework/ProjectImportedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -25,13 +25,11 @@ public ProjectImportedEventArgs() /// /// Initializes a new instance of the ProjectImportedEventArgs class. /// - public ProjectImportedEventArgs - ( + public ProjectImportedEventArgs( int lineNumber, int columnNumber, string message, - params object[] messageArgs - ) + params object[] messageArgs) : base( subcategory: null, code: null, diff --git a/src/Framework/ProjectStartedEventArgs.cs b/src/Framework/ProjectStartedEventArgs.cs index 2a005edc4c9..55f523a2dc1 100644 --- a/src/Framework/ProjectStartedEventArgs.cs +++ b/src/Framework/ProjectStartedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -49,15 +49,13 @@ protected ProjectStartedEventArgs() /// targets we are going to build (empty indicates default targets) /// list of properties /// list of items - public ProjectStartedEventArgs - ( + public ProjectStartedEventArgs( string message, string helpKeyword, string projectFile, string targetNames, IEnumerable properties, - IEnumerable items - ) + IEnumerable items) : this(message, helpKeyword, projectFile, targetNames, properties, items, DateTime.UtcNow) { } @@ -74,8 +72,7 @@ IEnumerable items /// list of properties /// list of items /// event context info for the parent project - public ProjectStartedEventArgs - ( + public ProjectStartedEventArgs( int projectId, string message, string helpKeyword, @@ -83,8 +80,7 @@ public ProjectStartedEventArgs string targetNames, IEnumerable properties, IEnumerable items, - BuildEventContext parentBuildEventContext - ) + BuildEventContext parentBuildEventContext) : this(projectId, message, helpKeyword, projectFile, targetNames, properties, items, parentBuildEventContext, DateTime.UtcNow) { } @@ -103,8 +99,7 @@ BuildEventContext parentBuildEventContext /// event context info for the parent project /// An containing global properties. /// The tools version. - public ProjectStartedEventArgs - ( + public ProjectStartedEventArgs( int projectId, string message, string helpKeyword, @@ -114,8 +109,7 @@ public ProjectStartedEventArgs IEnumerable items, BuildEventContext parentBuildEventContext, IDictionary globalProperties, - string toolsVersion - ) + string toolsVersion) : this(projectId, message, helpKeyword, projectFile, targetNames, properties, items, parentBuildEventContext) { this.GlobalProperties = globalProperties; @@ -133,16 +127,14 @@ string toolsVersion /// list of properties /// list of items /// The of the event. - public ProjectStartedEventArgs - ( + public ProjectStartedEventArgs( string message, string helpKeyword, string projectFile, string targetNames, IEnumerable properties, IEnumerable items, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.projectFile = projectFile; @@ -164,8 +156,7 @@ DateTime eventTimestamp /// list of items /// event context info for the parent project /// The of the event. - public ProjectStartedEventArgs - ( + public ProjectStartedEventArgs( int projectId, string message, string helpKeyword, @@ -174,8 +165,7 @@ public ProjectStartedEventArgs IEnumerable properties, IEnumerable items, BuildEventContext parentBuildEventContext, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : this(message, helpKeyword, projectFile, targetNames, properties, items, eventTimestamp) { parentProjectBuildEventContext = parentBuildEventContext; diff --git a/src/Framework/Properties/AssemblyInfo.cs b/src/Framework/Properties/AssemblyInfo.cs index c4ac04d7e43..2ed1a2a539d 100644 --- a/src/Framework/Properties/AssemblyInfo.cs +++ b/src/Framework/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Resources; diff --git a/src/Framework/PropertyInitialValueSetEventArgs.cs b/src/Framework/PropertyInitialValueSetEventArgs.cs index 050d0c80272..2f623ad6648 100644 --- a/src/Framework/PropertyInitialValueSetEventArgs.cs +++ b/src/Framework/PropertyInitialValueSetEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/PropertyReassignmentEventArgs.cs b/src/Framework/PropertyReassignmentEventArgs.cs index fa709c7789c..7c3c81f92e2 100644 --- a/src/Framework/PropertyReassignmentEventArgs.cs +++ b/src/Framework/PropertyReassignmentEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/RequiredAttribute.cs b/src/Framework/RequiredAttribute.cs index 91e4a6afa36..3c10b97c0c0 100644 --- a/src/Framework/RequiredAttribute.cs +++ b/src/Framework/RequiredAttribute.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/RequiredRuntimeAttribute.cs b/src/Framework/RequiredRuntimeAttribute.cs index 3848003a021..ba6b8000437 100644 --- a/src/Framework/RequiredRuntimeAttribute.cs +++ b/src/Framework/RequiredRuntimeAttribute.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/ResponseFileUsedEventArgs.cs b/src/Framework/ResponseFileUsedEventArgs.cs index 28e4200402f..bc027518a67 100644 --- a/src/Framework/ResponseFileUsedEventArgs.cs +++ b/src/Framework/ResponseFileUsedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/ReuseableStringBuilder.cs b/src/Framework/ReuseableStringBuilder.cs index 924fb0e0071..264daffacd0 100644 --- a/src/Framework/ReuseableStringBuilder.cs +++ b/src/Framework/ReuseableStringBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; @@ -358,11 +358,15 @@ private static int SelectBracketedCapacity(int requiredCapacity) const int minimumCapacity = 0x100; // 256 characters, 512 bytes if (requiredCapacity <= minimumCapacity) + { return minimumCapacity; + } // If user wants bigger capacity than maximum respect it as it could be used as buffer in P/Invoke. if (requiredCapacity >= MaxBuilderSizeCapacity) + { return requiredCapacity; + } // Find next power of two http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 int v = requiredCapacity; diff --git a/src/Framework/RunInMTAAttribute.cs b/src/Framework/RunInMTAAttribute.cs index 293694f7365..6ab24a5c027 100644 --- a/src/Framework/RunInMTAAttribute.cs +++ b/src/Framework/RunInMTAAttribute.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics.CodeAnalysis; diff --git a/src/Framework/RunInSTAAttribute.cs b/src/Framework/RunInSTAAttribute.cs index ad0653e8248..259bc5f968c 100644 --- a/src/Framework/RunInSTAAttribute.cs +++ b/src/Framework/RunInSTAAttribute.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics.CodeAnalysis; diff --git a/src/Framework/Sdk/SdkLogger.cs b/src/Framework/Sdk/SdkLogger.cs index cbf47f81245..9478bc6c583 100644 --- a/src/Framework/Sdk/SdkLogger.cs +++ b/src/Framework/Sdk/SdkLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/Sdk/SdkReference.cs b/src/Framework/Sdk/SdkReference.cs index 6b64974f348..86fe3310ed4 100644 --- a/src/Framework/Sdk/SdkReference.cs +++ b/src/Framework/Sdk/SdkReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -53,8 +53,16 @@ public SdkReference(string name, string version, string minimumVersion) /// public bool Equals(SdkReference other) { - if (other is null) return false; - if (ReferenceEquals(this, other)) return true; + if (other is null) + { + return false; + } + + if (ReferenceEquals(this, other)) + { + return true; + } + return string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(Version, other.Version, StringComparison.OrdinalIgnoreCase) && string.Equals(MinimumVersion, other.MinimumVersion, StringComparison.OrdinalIgnoreCase); @@ -71,12 +79,22 @@ public bool Equals(SdkReference other) public static bool TryParse(string sdk, out SdkReference sdkReference) { sdkReference = null; - if (string.IsNullOrWhiteSpace(sdk)) return false; + if (string.IsNullOrWhiteSpace(sdk)) + { + return false; + } var parts = sdk.Split(MSBuildConstants.ForwardSlash).Select(i => i.Trim()).ToArray(); - if (parts.Length < 1 || parts.Length > 2) return false; - if (string.IsNullOrWhiteSpace(parts[0])) return false; + if (parts.Length < 1 || parts.Length > 2) + { + return false; + } + + if (string.IsNullOrWhiteSpace(parts[0])) + { + return false; + } if (parts.Length == 1 || string.IsNullOrWhiteSpace(parts[1])) { @@ -97,9 +115,17 @@ public static bool TryParse(string sdk, out SdkReference sdkReference) /// public override bool Equals(object obj) { - if (obj is null) return false; - if (ReferenceEquals(this, obj)) return true; - return obj is SdkReference && Equals((SdkReference) obj); + if (obj is null) + { + return false; + } + + if (ReferenceEquals(this, obj)) + { + return true; + } + + return obj is SdkReference && Equals((SdkReference)obj); } /// diff --git a/src/Framework/Sdk/SdkResolver.cs b/src/Framework/Sdk/SdkResolver.cs index 753cc5a0116..7c0a662b2fc 100644 --- a/src/Framework/Sdk/SdkResolver.cs +++ b/src/Framework/Sdk/SdkResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/Sdk/SdkResolverContext.cs b/src/Framework/Sdk/SdkResolverContext.cs index 5a1e58e0942..17d39ee584b 100644 --- a/src/Framework/Sdk/SdkResolverContext.cs +++ b/src/Framework/Sdk/SdkResolverContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/Sdk/SdkResult.cs b/src/Framework/Sdk/SdkResult.cs index 52f4157b6fe..a3b354827a5 100644 --- a/src/Framework/Sdk/SdkResult.cs +++ b/src/Framework/Sdk/SdkResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Framework/Sdk/SdkResultFactory.cs b/src/Framework/Sdk/SdkResultFactory.cs index aac55e6833f..2a40692476c 100644 --- a/src/Framework/Sdk/SdkResultFactory.cs +++ b/src/Framework/Sdk/SdkResultFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/Sdk/SdkResultItem.cs b/src/Framework/Sdk/SdkResultItem.cs index 7feba81b7e6..47de1f3711b 100644 --- a/src/Framework/Sdk/SdkResultItem.cs +++ b/src/Framework/Sdk/SdkResultItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -8,8 +8,8 @@ namespace Microsoft.Build.Framework { - #nullable enable - +#nullable enable + /// /// The value of an item and any associated metadata to be added by an SDK resolver. See /// diff --git a/src/Framework/StringBuilderCache.cs b/src/Framework/StringBuilderCache.cs index 5b21061d9ae..5fd67790e9d 100644 --- a/src/Framework/StringBuilderCache.cs +++ b/src/Framework/StringBuilderCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -93,7 +93,7 @@ public static void Release(StringBuilder sb) StringBuilderCache.t_cachedInstance = sb; } #if DEBUG && !CLR2COMPATIBILITY && !MICROSOFT_BUILD_ENGINE_OM_UNITTESTS - MSBuildEventSource.Log.ReusableStringBuilderFactoryStop(hash: sb.GetHashCode(), returningCapacity: sb.Capacity, returningLength: sb.Length, type: sb.Capacity <= MAX_BUILDER_SIZE ? "sbc-return" : "sbc-discard"); + MSBuildEventSource.Log.ReusableStringBuilderFactoryStop(hash: sb.GetHashCode(), returningCapacity: sb.Capacity, returningLength: sb.Length, type: sb.Capacity <= MAX_BUILDER_SIZE ? "sbc-return" : "sbc-discard"); #endif } diff --git a/src/Framework/SupportedOSPlatform.cs b/src/Framework/SupportedOSPlatform.cs index 8a50d7c82f0..f532d4569e6 100644 --- a/src/Framework/SupportedOSPlatform.cs +++ b/src/Framework/SupportedOSPlatform.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if !NET6_0_OR_GREATER namespace System.Runtime.Versioning diff --git a/src/Framework/TargetBuiltReason.cs b/src/Framework/TargetBuiltReason.cs index 5f271125003..b00d1eff6c7 100644 --- a/src/Framework/TargetBuiltReason.cs +++ b/src/Framework/TargetBuiltReason.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/TargetFinishedEventArgs.cs b/src/Framework/TargetFinishedEventArgs.cs index 5398fd557a3..7dd9e1ad1d7 100644 --- a/src/Framework/TargetFinishedEventArgs.cs +++ b/src/Framework/TargetFinishedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -41,15 +41,13 @@ protected TargetFinishedEventArgs() /// project file /// file in which the target is defined /// true if target built successfully - public TargetFinishedEventArgs - ( + public TargetFinishedEventArgs( string message, string helpKeyword, string targetName, string projectFile, string targetFile, - bool succeeded - ) + bool succeeded) : this(message, helpKeyword, targetName, projectFile, targetFile, succeeded, DateTime.UtcNow, null) { } @@ -65,16 +63,14 @@ bool succeeded /// file in which the target is defined /// true if target built successfully /// Target output items for the target. If batching will be null for everything except for the last target in the batch - public TargetFinishedEventArgs - ( + public TargetFinishedEventArgs( string message, string helpKeyword, string targetName, string projectFile, string targetFile, bool succeeded, - IEnumerable targetOutputs - ) + IEnumerable targetOutputs) : this(message, helpKeyword, targetName, projectFile, targetFile, succeeded, DateTime.UtcNow, targetOutputs) { } @@ -91,8 +87,7 @@ IEnumerable targetOutputs /// true if target built successfully /// Timestamp when the event was created /// An containing the outputs of the target. - public TargetFinishedEventArgs - ( + public TargetFinishedEventArgs( string message, string helpKeyword, string targetName, @@ -100,8 +95,7 @@ public TargetFinishedEventArgs string targetFile, bool succeeded, DateTime eventTimestamp, - IEnumerable targetOutputs - ) + IEnumerable targetOutputs) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.targetName = targetName; diff --git a/src/Framework/TargetSkippedEventArgs.cs b/src/Framework/TargetSkippedEventArgs.cs index 05177c0c594..22b2a4a1a0e 100644 --- a/src/Framework/TargetSkippedEventArgs.cs +++ b/src/Framework/TargetSkippedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -56,11 +56,9 @@ public TargetSkippedEventArgs() /// /// Initializes a new instance of the TargetSkippedEventArgs class. /// - public TargetSkippedEventArgs - ( + public TargetSkippedEventArgs( string message, - params object[] messageArgs - ) + params object[] messageArgs) : base( subcategory: null, code: null, diff --git a/src/Framework/TargetStartedEventArgs.cs b/src/Framework/TargetStartedEventArgs.cs index 2a51fddd380..27275a91205 100644 --- a/src/Framework/TargetStartedEventArgs.cs +++ b/src/Framework/TargetStartedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -39,14 +39,12 @@ protected TargetStartedEventArgs() /// target name /// project file /// file in which the target is defined - public TargetStartedEventArgs - ( + public TargetStartedEventArgs( string message, string helpKeyword, string targetName, string projectFile, - string targetFile - ) + string targetFile) : this(message, helpKeyword, targetName, projectFile, targetFile, String.Empty, TargetBuiltReason.None, DateTime.UtcNow) { } @@ -61,16 +59,14 @@ string targetFile /// file in which the target is defined /// The part of the target. /// Timestamp when the event was created - public TargetStartedEventArgs - ( + public TargetStartedEventArgs( string message, string helpKeyword, string targetName, string projectFile, string targetFile, string parentTarget, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.targetName = targetName; @@ -90,8 +86,7 @@ DateTime eventTimestamp /// The part of the target. /// The reason the parent built this target. /// Timestamp when the event was created - public TargetStartedEventArgs - ( + public TargetStartedEventArgs( string message, string helpKeyword, string targetName, @@ -99,8 +94,7 @@ public TargetStartedEventArgs string targetFile, string parentTarget, TargetBuiltReason buildReason, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.targetName = targetName; @@ -148,7 +142,7 @@ internal override void CreateFromStream(BinaryReader reader, int version) if (version > 20) { parentTarget = reader.ReadByte() == 0 ? null : reader.ReadString(); - buildReason = (TargetBuiltReason) reader.ReadInt32(); + buildReason = (TargetBuiltReason)reader.ReadInt32(); } } #endregion diff --git a/src/Framework/TaskCommandLineEventArgs.cs b/src/Framework/TaskCommandLineEventArgs.cs index 2e80c7ddc0e..526be83791e 100644 --- a/src/Framework/TaskCommandLineEventArgs.cs +++ b/src/Framework/TaskCommandLineEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -41,12 +41,10 @@ protected TaskCommandLineEventArgs() /// The name of the task raising this event. /// Importance of command line -- controls whether /// the command line will be displayed by less verbose loggers. - public TaskCommandLineEventArgs - ( + public TaskCommandLineEventArgs( string commandLine, string taskName, - MessageImportance importance - ) + MessageImportance importance) : this(commandLine, taskName, importance, DateTime.UtcNow) { // do nothing @@ -62,13 +60,11 @@ MessageImportance importance /// Importance of command line -- controls whether /// the command line will be displayed by less verbose loggers. /// Timestamp when the event was created - public TaskCommandLineEventArgs - ( + public TaskCommandLineEventArgs( string commandLine, string taskName, MessageImportance importance, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(commandLine, helpKeyword: null, taskName, importance, eventTimestamp) { // do nothing diff --git a/src/Framework/TaskFinishedEventArgs.cs b/src/Framework/TaskFinishedEventArgs.cs index 3b282a9afac..f1d88eb301e 100644 --- a/src/Framework/TaskFinishedEventArgs.cs +++ b/src/Framework/TaskFinishedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -40,15 +40,13 @@ protected TaskFinishedEventArgs() /// file in which the task is defined /// task name /// true indicates task succeed - public TaskFinishedEventArgs - ( + public TaskFinishedEventArgs( string message, string helpKeyword, string projectFile, string taskFile, string taskName, - bool succeeded - ) + bool succeeded) : this(message, helpKeyword, projectFile, taskFile, taskName, succeeded, DateTime.UtcNow) { } @@ -64,16 +62,14 @@ bool succeeded /// task name /// true indicates task succeed /// Timestamp when event was created - public TaskFinishedEventArgs - ( + public TaskFinishedEventArgs( string message, string helpKeyword, string projectFile, string taskFile, string taskName, bool succeeded, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.taskName = taskName; diff --git a/src/Framework/TaskItemData.cs b/src/Framework/TaskItemData.cs index 6f35859a355..560daa03662 100644 --- a/src/Framework/TaskItemData.cs +++ b/src/Framework/TaskItemData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Framework/TaskParameterEventArgs.cs b/src/Framework/TaskParameterEventArgs.cs index c4ae14f03ca..7aa294f828c 100644 --- a/src/Framework/TaskParameterEventArgs.cs +++ b/src/Framework/TaskParameterEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -32,14 +32,12 @@ public class TaskParameterEventArgs : BuildMessageEventArgs /// /// Creates an instance of this class for the given task parameter. /// - public TaskParameterEventArgs - ( + public TaskParameterEventArgs( TaskParameterMessageKind kind, string itemType, IList items, bool logItemMetadata, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(null, null, null, MessageImportance.Low, eventTimestamp) { Kind = kind; diff --git a/src/Framework/TaskPropertyInfo.cs b/src/Framework/TaskPropertyInfo.cs index 3d06ce4d747..73e1f817e22 100644 --- a/src/Framework/TaskPropertyInfo.cs +++ b/src/Framework/TaskPropertyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; diff --git a/src/Framework/TaskStartedEventArgs.cs b/src/Framework/TaskStartedEventArgs.cs index eafeb579b5d..d8d17ed4534 100644 --- a/src/Framework/TaskStartedEventArgs.cs +++ b/src/Framework/TaskStartedEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -39,14 +39,12 @@ protected TaskStartedEventArgs() /// project file /// file in which the task is defined /// task name - public TaskStartedEventArgs - ( + public TaskStartedEventArgs( string message, string helpKeyword, string projectFile, string taskFile, - string taskName - ) + string taskName) : this(message, helpKeyword, projectFile, taskFile, taskName, DateTime.UtcNow) { } @@ -61,15 +59,13 @@ string taskName /// file in which the task is defined /// task name /// Timestamp when event was created - public TaskStartedEventArgs - ( + public TaskStartedEventArgs( string message, string helpKeyword, string projectFile, string taskFile, string taskName, - DateTime eventTimestamp - ) + DateTime eventTimestamp) : base(message, helpKeyword, "MSBuild", eventTimestamp) { this.taskName = taskName; diff --git a/src/Framework/Telemetry/BuildTelemetry.cs b/src/Framework/Telemetry/BuildTelemetry.cs index 45e7537ff7c..9515a2e185e 100644 --- a/src/Framework/Telemetry/BuildTelemetry.cs +++ b/src/Framework/Telemetry/BuildTelemetry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Framework/Telemetry/KnownTelemetry.cs b/src/Framework/Telemetry/KnownTelemetry.cs index 5f32304d7e6..bbfb62666e7 100644 --- a/src/Framework/Telemetry/KnownTelemetry.cs +++ b/src/Framework/Telemetry/KnownTelemetry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.Build.Framework.Telemetry; diff --git a/src/Framework/Telemetry/TelemetryBase.cs b/src/Framework/Telemetry/TelemetryBase.cs index 26348f1ea4f..d2475146c5b 100644 --- a/src/Framework/Telemetry/TelemetryBase.cs +++ b/src/Framework/Telemetry/TelemetryBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Framework/TelemetryEventArgs.cs b/src/Framework/TelemetryEventArgs.cs index 4edc7d0a626..276ec0a1fa3 100644 --- a/src/Framework/TelemetryEventArgs.cs +++ b/src/Framework/TelemetryEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/TestInfo.cs b/src/Framework/TestInfo.cs index 45efb41040b..a35ff48fdce 100644 --- a/src/Framework/TestInfo.cs +++ b/src/Framework/TestInfo.cs @@ -1,4 +1,7 @@ -#nullable disable +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable disable namespace Microsoft.Build.Framework { diff --git a/src/Framework/Traits.cs b/src/Framework/Traits.cs index 222c739542f..8b7fce908e4 100644 --- a/src/Framework/Traits.cs +++ b/src/Framework/Traits.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/UninitializedPropertyReadEventArgs.cs b/src/Framework/UninitializedPropertyReadEventArgs.cs index 954cc5e43ca..ef638c5e101 100644 --- a/src/Framework/UninitializedPropertyReadEventArgs.cs +++ b/src/Framework/UninitializedPropertyReadEventArgs.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Framework/VisualStudioLocationHelper.cs b/src/Framework/VisualStudioLocationHelper.cs index be2ec623f5b..a747ea8bd1a 100644 --- a/src/Framework/VisualStudioLocationHelper.cs +++ b/src/Framework/VisualStudioLocationHelper.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; #if FEATURE_VISUALSTUDIOSETUP using System.Runtime.InteropServices; @@ -17,7 +20,7 @@ namespace Microsoft.Build.Shared internal class VisualStudioLocationHelper { #if FEATURE_VISUALSTUDIOSETUP - private const int REGDB_E_CLASSNOTREG = unchecked((int) 0x80040154); + private const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154); #endif // FEATURE_VISUALSTUDIOSETUP /// @@ -33,7 +36,7 @@ internal static IList GetInstances() try { // This code is not obvious. See the sample (link above) for reference. - var query = (ISetupConfiguration2) GetQuery(); + var query = (ISetupConfiguration2)GetQuery(); var e = query.EnumAllInstances(); int fetched; @@ -42,10 +45,13 @@ internal static IList GetInstances() { // Call e.Next to query for the next instance (single item or nothing returned). e.Next(1, instances, out fetched); - if (fetched <= 0) continue; + if (fetched <= 0) + { + continue; + } var instance = instances[0]; - var state = ((ISetupInstance2) instance).GetState(); + var state = ((ISetupInstance2)instance).GetState(); Version version; try @@ -70,7 +76,7 @@ internal static IList GetInstances() catch (COMException) { } catch (DllNotFoundException) - { + { // This is OK, VS "15" or greater likely not installed. } #endif diff --git a/src/Framework/XamlTypes/Argument.cs b/src/Framework/XamlTypes/Argument.cs index bc69f83a709..d223f4287f7 100644 --- a/src/Framework/XamlTypes/Argument.cs +++ b/src/Framework/XamlTypes/Argument.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; diff --git a/src/Framework/XamlTypes/BaseProperty.cs b/src/Framework/XamlTypes/BaseProperty.cs index 4587cd8ab93..258a30747bf 100644 --- a/src/Framework/XamlTypes/BaseProperty.cs +++ b/src/Framework/XamlTypes/BaseProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/BoolProperty.cs b/src/Framework/XamlTypes/BoolProperty.cs index d1db3eac06b..3476db9732a 100644 --- a/src/Framework/XamlTypes/BoolProperty.cs +++ b/src/Framework/XamlTypes/BoolProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/XamlTypes/Category.cs b/src/Framework/XamlTypes/Category.cs index 5756483902e..7538572c08e 100644 --- a/src/Framework/XamlTypes/Category.cs +++ b/src/Framework/XamlTypes/Category.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; diff --git a/src/Framework/XamlTypes/CategorySchema.cs b/src/Framework/XamlTypes/CategorySchema.cs index 72b2fe6bf46..a646cc7eb98 100644 --- a/src/Framework/XamlTypes/CategorySchema.cs +++ b/src/Framework/XamlTypes/CategorySchema.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/XamlTypes/ContentType.cs b/src/Framework/XamlTypes/ContentType.cs index 93d6298362c..d8e3f8bb7ee 100644 --- a/src/Framework/XamlTypes/ContentType.cs +++ b/src/Framework/XamlTypes/ContentType.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/DataSource.cs b/src/Framework/XamlTypes/DataSource.cs index bd1e559d682..49833064068 100644 --- a/src/Framework/XamlTypes/DataSource.cs +++ b/src/Framework/XamlTypes/DataSource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; diff --git a/src/Framework/XamlTypes/DynamicEnumProperty.cs b/src/Framework/XamlTypes/DynamicEnumProperty.cs index f4e1655abb2..cb4e230b993 100644 --- a/src/Framework/XamlTypes/DynamicEnumProperty.cs +++ b/src/Framework/XamlTypes/DynamicEnumProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/src/Framework/XamlTypes/EnumProperty.cs b/src/Framework/XamlTypes/EnumProperty.cs index d07d9eba886..749a26394b6 100644 --- a/src/Framework/XamlTypes/EnumProperty.cs +++ b/src/Framework/XamlTypes/EnumProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/src/Framework/XamlTypes/EnumValue.cs b/src/Framework/XamlTypes/EnumValue.cs index 014262e8bf0..4c90e0b947d 100644 --- a/src/Framework/XamlTypes/EnumValue.cs +++ b/src/Framework/XamlTypes/EnumValue.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/FileExtension.cs b/src/Framework/XamlTypes/FileExtension.cs index a1368b9abf4..43c421f90de 100644 --- a/src/Framework/XamlTypes/FileExtension.cs +++ b/src/Framework/XamlTypes/FileExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/IProjectSchemaNode.cs b/src/Framework/XamlTypes/IProjectSchemaNode.cs index 879e9bc3cd1..119357ececa 100644 --- a/src/Framework/XamlTypes/IProjectSchemaNode.cs +++ b/src/Framework/XamlTypes/IProjectSchemaNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/IntProperty.cs b/src/Framework/XamlTypes/IntProperty.cs index eb8d77a669a..a3bcf704968 100644 --- a/src/Framework/XamlTypes/IntProperty.cs +++ b/src/Framework/XamlTypes/IntProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/XamlTypes/ItemType.cs b/src/Framework/XamlTypes/ItemType.cs index e6696f3b2d6..14a8d89c880 100644 --- a/src/Framework/XamlTypes/ItemType.cs +++ b/src/Framework/XamlTypes/ItemType.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/NameValuePair.cs b/src/Framework/XamlTypes/NameValuePair.cs index f180244d508..7de604d79f6 100644 --- a/src/Framework/XamlTypes/NameValuePair.cs +++ b/src/Framework/XamlTypes/NameValuePair.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; diff --git a/src/Framework/XamlTypes/ProjectSchemaDefinitions.cs b/src/Framework/XamlTypes/ProjectSchemaDefinitions.cs index 353136c50e8..818795fbe20 100644 --- a/src/Framework/XamlTypes/ProjectSchemaDefinitions.cs +++ b/src/Framework/XamlTypes/ProjectSchemaDefinitions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/Rule.cs b/src/Framework/XamlTypes/Rule.cs index 7c07bbfcd0a..b833e7b888e 100644 --- a/src/Framework/XamlTypes/Rule.cs +++ b/src/Framework/XamlTypes/Rule.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/RuleBag.cs b/src/Framework/XamlTypes/RuleBag.cs index 1831443deeb..2263e46d90e 100644 --- a/src/Framework/XamlTypes/RuleBag.cs +++ b/src/Framework/XamlTypes/RuleBag.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Framework/XamlTypes/RuleSchema.cs b/src/Framework/XamlTypes/RuleSchema.cs index 7ce3572062c..4dc9e23d78c 100644 --- a/src/Framework/XamlTypes/RuleSchema.cs +++ b/src/Framework/XamlTypes/RuleSchema.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/XamlTypes/StringListProperty.cs b/src/Framework/XamlTypes/StringListProperty.cs index 91298c04a18..7aea73e76f8 100644 --- a/src/Framework/XamlTypes/StringListProperty.cs +++ b/src/Framework/XamlTypes/StringListProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/XamlTypes/StringProperty.cs b/src/Framework/XamlTypes/StringProperty.cs index e2b61544f1b..6010ab78a68 100644 --- a/src/Framework/XamlTypes/StringProperty.cs +++ b/src/Framework/XamlTypes/StringProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Framework/XamlTypes/ValueEditor.cs b/src/Framework/XamlTypes/ValueEditor.cs index e58c6e236a4..f8aa2923bd7 100644 --- a/src/Framework/XamlTypes/ValueEditor.cs +++ b/src/Framework/XamlTypes/ValueEditor.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/MSBuild.UnitTests/AssemblyInfo.cs b/src/MSBuild.UnitTests/AssemblyInfo.cs index 7f6f30fcef9..3b5d7bbb185 100644 --- a/src/MSBuild.UnitTests/AssemblyInfo.cs +++ b/src/MSBuild.UnitTests/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs b/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs index 3597bc3fa3d..e3233cff927 100644 --- a/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs +++ b/src/MSBuild.UnitTests/CommandLineSwitches_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -564,9 +564,9 @@ public void GraphBuildSwitchCanHaveParameters() { CommandLineSwitches switches = new CommandLineSwitches(); - MSBuildApp.GatherCommandLineSwitches(new List { "/graph", "/graph:true; NoBuild ;; ;", "/graph:foo"}, switches); + MSBuildApp.GatherCommandLineSwitches(new List { "/graph", "/graph:true; NoBuild ;; ;", "/graph:foo" }, switches); - switches[CommandLineSwitches.ParameterizedSwitch.GraphBuild].ShouldBe(new[] {"true", " NoBuild ", " ", "foo"}); + switches[CommandLineSwitches.ParameterizedSwitch.GraphBuild].ShouldBe(new[] { "true", " NoBuild ", " ", "foo" }); switches.HaveErrors().ShouldBeFalse(); } @@ -588,9 +588,9 @@ public void InputResultsCachesSupportsMultipleOccurrence() { CommandLineSwitches switches = new CommandLineSwitches(); - MSBuildApp.GatherCommandLineSwitches(new List(){"/irc", "/irc:a;b", "/irc:c;d"}, switches); + MSBuildApp.GatherCommandLineSwitches(new List() { "/irc", "/irc:a;b", "/irc:c;d" }, switches); - switches[CommandLineSwitches.ParameterizedSwitch.InputResultsCaches].ShouldBe(new []{null, "a", "b", "c", "d"}); + switches[CommandLineSwitches.ParameterizedSwitch.InputResultsCaches].ShouldBe(new[] { null, "a", "b", "c", "d" }); switches.HaveErrors().ShouldBeFalse(); } @@ -600,9 +600,9 @@ public void OutputResultsCache() { CommandLineSwitches switches = new CommandLineSwitches(); - MSBuildApp.GatherCommandLineSwitches(new List(){"/orc:a"}, switches); + MSBuildApp.GatherCommandLineSwitches(new List() { "/orc:a" }, switches); - switches[CommandLineSwitches.ParameterizedSwitch.OutputResultsCache].ShouldBe(new []{"a"}); + switches[CommandLineSwitches.ParameterizedSwitch.OutputResultsCache].ShouldBe(new[] { "a" }); switches.HaveErrors().ShouldBeFalse(); } @@ -612,7 +612,7 @@ public void OutputResultsCachesDoesNotSupportMultipleOccurrences() { CommandLineSwitches switches = new CommandLineSwitches(); - MSBuildApp.GatherCommandLineSwitches(new List(){"/orc:a", "/orc:b"}, switches); + MSBuildApp.GatherCommandLineSwitches(new List() { "/orc:a", "/orc:b" }, switches); switches.HaveErrors().ShouldBeTrue(); } @@ -1023,15 +1023,16 @@ public void InvalidToolsVersionErrors() lowPriority: false, inputResultsCaches: null, outputResultsCache: null, - commandLine: null - ); + commandLine: null); } finally { - if (File.Exists(filename)) File.Delete(filename); + if (File.Exists(filename)) + { + File.Delete(filename); + } } - } - ); + }); } [Fact] public void TestHaveAnySwitchesBeenSet() @@ -1179,7 +1180,7 @@ public void ProcessWarnAsErrorSwitchEmpty() { CommandLineSwitches commandLineSwitches = new CommandLineSwitches(); - MSBuildApp.GatherCommandLineSwitches(new List(new [] { "/warnaserror" }), commandLineSwitches); + MSBuildApp.GatherCommandLineSwitches(new List(new[] { "/warnaserror" }), commandLineSwitches); ISet actualWarningsAsErrors = MSBuildApp.ProcessWarnAsErrorSwitch(commandLineSwitches); @@ -1272,7 +1273,7 @@ public void ProcessBooleanSwitchTest() MSBuildApp.ProcessBooleanSwitch(Array.Empty(), defaultValue: false, resourceName: null).ShouldBeFalse(); - MSBuildApp.ProcessBooleanSwitch(new [] { "true" }, defaultValue: false, resourceName: null).ShouldBeTrue(); + MSBuildApp.ProcessBooleanSwitch(new[] { "true" }, defaultValue: false, resourceName: null).ShouldBeTrue(); MSBuildApp.ProcessBooleanSwitch(new[] { "false" }, defaultValue: true, resourceName: null).ShouldBeFalse(); @@ -1282,29 +1283,29 @@ public void ProcessBooleanSwitchTest() public static IEnumerable ProcessGraphBuildSwitchData() { var emptyOptions = new GraphBuildOptions(); - var noBuildOptions = new GraphBuildOptions {Build = false}; + var noBuildOptions = new GraphBuildOptions { Build = false }; - yield return new object[] {Array.Empty(), emptyOptions, null}; + yield return new object[] { Array.Empty(), emptyOptions, null }; - yield return new object[] {new[] {"true"}, emptyOptions, null}; + yield return new object[] { new[] { "true" }, emptyOptions, null }; - yield return new object[] {new[] {"false"}, null, null}; + yield return new object[] { new[] { "false" }, null, null }; - yield return new object[] {new[] {" ", " "}, emptyOptions, null}; + yield return new object[] { new[] { " ", " " }, emptyOptions, null }; - yield return new object[] {new[] {"NoBuild"}, noBuildOptions, null}; + yield return new object[] { new[] { "NoBuild" }, noBuildOptions, null }; - yield return new object[] {new[] {"noBUILD"}, noBuildOptions, null}; + yield return new object[] { new[] { "noBUILD" }, noBuildOptions, null }; - yield return new object[] {new[] {"noBUILD "}, noBuildOptions, null}; + yield return new object[] { new[] { "noBUILD " }, noBuildOptions, null }; - yield return new object[] {new[] {"false", "true"}, null, new[] {"false"}}; + yield return new object[] { new[] { "false", "true" }, null, new[] { "false" } }; - yield return new object[] {new[] {"nobuild", "true"}, noBuildOptions, new[] {"true"}}; + yield return new object[] { new[] { "nobuild", "true" }, noBuildOptions, new[] { "true" } }; - yield return new object[] {new[] { "false", "nobuild" }, null, new[] {"false"}}; + yield return new object[] { new[] { "false", "nobuild" }, null, new[] { "false" } }; - yield return new object[] {new[] {"nobuild", "invalid"}, null, new[] {"invalid"}}; + yield return new object[] { new[] { "nobuild", "invalid" }, null, new[] { "invalid" } }; } [Theory] @@ -1350,7 +1351,7 @@ public void ProcessProfileEvaluationInvalidFilename(string filename) { bool enableProfiler = false; Should.Throw( - () => MSBuildApp.ProcessProfileEvaluationSwitch(new[] {filename}, new List(), out enableProfiler), + () => MSBuildApp.ProcessProfileEvaluationSwitch(new[] { filename }, new List(), out enableProfiler), typeof(CommandLineSwitchException)); } diff --git a/src/MSBuild.UnitTests/MSBuildServer_Tests.cs b/src/MSBuild.UnitTests/MSBuildServer_Tests.cs index e211fc36115..2231689abae 100644 --- a/src/MSBuild.UnitTests/MSBuildServer_Tests.cs +++ b/src/MSBuild.UnitTests/MSBuildServer_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/MSBuild.UnitTests/PerfLog_Tests.cs b/src/MSBuild.UnitTests/PerfLog_Tests.cs index a167de8abad..0f747122ec8 100644 --- a/src/MSBuild.UnitTests/PerfLog_Tests.cs +++ b/src/MSBuild.UnitTests/PerfLog_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; diff --git a/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs b/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs index 91839f18a69..49c86fc23a8 100644 --- a/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs +++ b/src/MSBuild.UnitTests/ProjectSchemaValidationHandler_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_XML_SCHEMA_VALIDATION using System; @@ -56,7 +56,11 @@ public void VerifyInvalidProjectSchema() } finally { - if (projectFilename != null) File.Delete(projectFilename); + if (projectFilename != null) + { + File.Delete(projectFilename); + } + CleanupSchemaFiles(msbuildTempXsdFilenames); Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM); Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", oldValueForMSBuildLoadMicrosoftTargetsReadOnly); @@ -95,8 +99,16 @@ public void VerifyInvalidSchemaItself1() } finally { - if (projectFilename != null) File.Delete(projectFilename); - if (invalidSchemaFile != null) File.Delete(invalidSchemaFile); + if (projectFilename != null) + { + File.Delete(projectFilename); + } + + if (invalidSchemaFile != null) + { + File.Delete(invalidSchemaFile); + } + Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM); Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", oldValueForMSBuildLoadMicrosoftTargetsReadOnly); } @@ -147,8 +159,16 @@ public void VerifyInvalidSchemaItself2() } finally { - if (invalidSchemaFile != null) File.Delete(invalidSchemaFile); - if (projectFilename != null) File.Delete(projectFilename); + if (invalidSchemaFile != null) + { + File.Delete(invalidSchemaFile); + } + + if (projectFilename != null) + { + File.Delete(projectFilename); + } + Environment.SetEnvironmentVariable("MSBuildOldOM", oldValueForMSBuildOldOM); Environment.SetEnvironmentVariable("MSBuildLoadMicrosoftTargetsReadOnly", oldValueForMSBuildLoadMicrosoftTargetsReadOnly); } @@ -255,6 +275,7 @@ public void VerifyInvalidImportNotCaughtBySchema() } } +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Helper Functions /// @@ -329,7 +350,7 @@ private void CleanupSchemaFiles(string[] msbuildTempXsdFilenames) /// Stolen from ObjectModelHelpers because we use relatively little /// of the ObjectModelHelpers functionality, so as to avoid having to include in /// this project everything that ObjectModelHelpers depends on - static internal string CreateTempFileOnDisk(string fileContents, params object[] args) + internal static string CreateTempFileOnDisk(string fileContents, params object[] args) { return CreateTempFileOnDiskNoFormat(String.Format(fileContents, args)); } @@ -340,7 +361,7 @@ static internal string CreateTempFileOnDisk(string fileContents, params object[] /// Stolen from ObjectModelHelpers because we use relatively little /// of the ObjectModelHelpers functionality, so as to avoid having to include in /// this project everything that ObjectModelHelpers depends on - static internal string CreateTempFileOnDiskNoFormat(string fileContents) + internal static string CreateTempFileOnDiskNoFormat(string fileContents) { string projectFilePath = FileUtilities.GetTemporaryFileName(); @@ -357,7 +378,7 @@ static internal string CreateTempFileOnDiskNoFormat(string fileContents) /// Stolen from ObjectModelHelpers because we use relatively little /// of the ObjectModelHelpers functionality, so as to avoid having to include in /// this project everything that ObjectModelHelpers depends on - static private string CleanupFileContents(string projectFileContents) + private static string CleanupFileContents(string projectFileContents) { // Replace reverse-single-quotes with double-quotes. projectFileContents = projectFileContents.Replace("`", "\""); @@ -373,6 +394,7 @@ static private string CleanupFileContents(string projectFileContents) private const string msbuildDefaultToolsVersion = "4.0"; #endregion // Helper Functions +#pragma warning restore format } } #endif diff --git a/src/MSBuild.UnitTests/ValidateAssemblyLoadContext.cs b/src/MSBuild.UnitTests/ValidateAssemblyLoadContext.cs index 249571a1802..7a802d191e4 100644 --- a/src/MSBuild.UnitTests/ValidateAssemblyLoadContext.cs +++ b/src/MSBuild.UnitTests/ValidateAssemblyLoadContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_ASSEMBLYLOADCONTEXT diff --git a/src/MSBuild.UnitTests/XMake_Tests.cs b/src/MSBuild.UnitTests/XMake_Tests.cs index 5849fb8f3c8..3dec3a1446c 100644 --- a/src/MSBuild.UnitTests/XMake_Tests.cs +++ b/src/MSBuild.UnitTests/XMake_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -516,11 +516,11 @@ public void Help(string indicator) { MSBuildApp.Execute( #if FEATURE_GET_COMMANDLINE - @$"c:\bin\msbuild.exe {indicator} " + @$"c:\bin\msbuild.exe {indicator} ") #else - new [] {@"c:\bin\msbuild.exe", indicator} + new[] { @"c:\bin\msbuild.exe", indicator }) #endif - ).ShouldBe(MSBuildApp.ExitType.Success); + .ShouldBe(MSBuildApp.ExitType.Success); } [Fact] @@ -564,8 +564,7 @@ public void InvalidVerbosity() Should.Throw(() => { MSBuildApp.ProcessVerbositySwitch("loquacious"); - } - ); + }); } [Fact] public void ValidMaxCPUCountSwitch() @@ -587,8 +586,7 @@ public void InvalidMaxCPUCountSwitch1() Should.Throw(() => { MSBuildApp.ProcessMaxCPUCountSwitch(new[] { "-1" }); - } - ); + }); } [Fact] @@ -597,8 +595,7 @@ public void InvalidMaxCPUCountSwitch2() Should.Throw(() => { MSBuildApp.ProcessMaxCPUCountSwitch(new[] { "0" }); - } - ); + }); } [Fact] @@ -607,8 +604,7 @@ public void InvalidMaxCPUCountSwitch3() Should.Throw(() => { MSBuildApp.ProcessMaxCPUCountSwitch(new[] { "foo" }); - } - ); + }); } [Fact] @@ -618,8 +614,7 @@ public void InvalidMaxCPUCountSwitch4() { // Too big MSBuildApp.ProcessMaxCPUCountSwitch(new[] { "1025" }); - } - ); + }); } /// @@ -1394,8 +1389,7 @@ public void TestProcessProjectSwitchNullInList() string[] extensionsToIgnore = { ".phantomextension", null }; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles).ShouldBe("my.proj", StringCompareShould.IgnoreCase); // "Expected my.proj to be only project found" - } - ); + }); } /// @@ -1410,8 +1404,7 @@ public void TestProcessProjectSwitchEmptyInList() string[] extensionsToIgnore = { ".phantomextension", string.Empty }; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles).ShouldBe("my.proj", StringCompareShould.IgnoreCase); // "Expected my.proj to be only project found" - } - ); + }); } /// /// If only a dot is specified then the extension is invalid @@ -1425,8 +1418,7 @@ public void TestProcessProjectSwitchExtensionWithoutDot() string[] extensionsToIgnore = { "phantomextension" }; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles).ShouldBe("my.proj", StringCompareShould.IgnoreCase); - } - ); + }); } /// /// Put some junk into the extension, in this case there should be an exception @@ -1440,8 +1432,7 @@ public void TestProcessProjectSwitchMalformed() string[] extensionsToIgnore = { ".C:\\boocatmoo.a" }; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles).ShouldBe("my.proj", StringCompareShould.IgnoreCase); // "Expected my.proj to be only project found" - } - ); + }); } /// /// Test what happens if there are no project or solution files in the directory @@ -1455,8 +1446,7 @@ public void TestProcessProjectSwitchWildcards() string[] extensionsToIgnore = { ".proj*", ".nativeproj?" }; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } [Fact] public void TestProcessProjectSwitch() @@ -1536,8 +1526,7 @@ public void TestProcessProjectSwitchRemovedAllprojects() var extensionsToIgnore = new[] { ".nativeproj", ".vcproj" }; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Test the case where there is a solution and a project in the same directory but they have different names @@ -1551,8 +1540,7 @@ public void TestProcessProjectSwitchSlnProjDifferentNames() string[] extensionsToIgnore = null; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Test the case where we have two proj files in the same directory @@ -1566,8 +1554,7 @@ public void TestProcessProjectSwitchTwoProj() string[] extensionsToIgnore = null; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Test the case where we have two native project files in the same directory @@ -1581,8 +1568,7 @@ public void TestProcessProjectSwitchTwoNative() string[] extensionsToIgnore = null; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Test when there are two solutions in the same directory @@ -1596,8 +1582,7 @@ public void TestProcessProjectSwitchTwoSolutions() string[] extensionsToIgnore = null; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Check the case where there are more than two projects in the directory and one is a proj file @@ -1611,8 +1596,7 @@ public void TestProcessProjectSwitchMoreThenTwoProj() string[] extensionsToIgnore = null; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Test what happens if there are no project or solution files in the directory @@ -1626,8 +1610,7 @@ public void TestProcessProjectSwitchNoProjectOrSolution() string[] extensionsToIgnore = null; IgnoreProjectExtensionsHelper projectHelper = new IgnoreProjectExtensionsHelper(projects); MSBuildApp.ProcessProjectSwitch(Array.Empty(), extensionsToIgnore, projectHelper.GetFiles); - } - ); + }); } /// /// Helper class to simulate directory work for ignore project extensions @@ -1741,14 +1724,12 @@ public void TestProcessFileLoggerSwitch1() List distributedLoggerRecords = new List(); var loggers = new List(); - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); distributedLoggerRecords.Count.ShouldBe(0); // "Expected no distributed loggers to be attached" loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" } @@ -1764,14 +1745,12 @@ public void TestProcessFileLoggerSwitch2() List distributedLoggerRecords = new List(); var loggers = new List(); - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); distributedLoggerRecords.Count.ShouldBe(1); // "Expected one distributed loggers to be attached" loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" } @@ -1787,14 +1766,12 @@ public void TestProcessFileLoggerSwitch3() List distributedLoggerRecords = new List(); var loggers = new List(); - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); distributedLoggerRecords.Count.ShouldBe(0); // "Expected no distributed loggers to be attached" loggers.Count.ShouldBe(0); // "Expected a central loggers to be attached" @@ -1803,14 +1780,12 @@ public void TestProcessFileLoggerSwitch3() loggers = new List(); fileLoggerParameters = new[] { "Parameter" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); distributedLoggerRecords.Count.ShouldBe(0); // "Expected no distributed loggers to be attached" loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" @@ -1818,14 +1793,12 @@ public void TestProcessFileLoggerSwitch3() loggers = new List(); fileLoggerParameters = new[] { "Parameter1", "Parameter" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); distributedLoggerRecords.Count.ShouldBe(0); // "Expected no distributed loggers to be attached" loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" } @@ -1841,14 +1814,12 @@ public void TestProcessFileLoggerSwitch4() List distributedLoggerRecords = new List(); var loggers = new List(); - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" distributedLoggerRecords.Count.ShouldBe(1); // "Expected a distributed logger to be attached" distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe($"logFile={Path.Combine(Directory.GetCurrentDirectory(), "MSBuild.log")}", StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" @@ -1858,14 +1829,12 @@ public void TestProcessFileLoggerSwitch4() loggers = new List(); fileLoggerParameters = new[] { "verbosity=Normal;" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" distributedLoggerRecords.Count.ShouldBe(1); // "Expected a distributed logger to be attached" distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe($"{fileLoggerParameters[0]};logFile={Path.Combine(Directory.GetCurrentDirectory(), "MSBuild.log")}", StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" @@ -1875,14 +1844,12 @@ public void TestProcessFileLoggerSwitch4() loggers = new List(); fileLoggerParameters = new[] { "verbosity=Normal", "" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" distributedLoggerRecords.Count.ShouldBe(1); // "Expected a distributed logger to be attached" distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe($"{fileLoggerParameters[0]};logFile={Path.Combine(Directory.GetCurrentDirectory(), "MSBuild.log")}", StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" @@ -1892,14 +1859,12 @@ public void TestProcessFileLoggerSwitch4() loggers = new List(); fileLoggerParameters = new[] { "", "Parameter1" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" distributedLoggerRecords.Count.ShouldBe(1); // "Expected a distributed logger to be attached" distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe($";Parameter1;logFile={Path.Combine(Directory.GetCurrentDirectory(), "MSBuild.log")}", StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" @@ -1909,14 +1874,12 @@ public void TestProcessFileLoggerSwitch4() loggers = new List(); fileLoggerParameters = new[] { "Parameter1", "verbosity=Normal;logfile=" + (NativeMethodsShared.IsWindows ? "c:\\temp\\cat.log" : "/tmp/cat.log") }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" distributedLoggerRecords.Count.ShouldBe(1); // "Expected a distributed logger to be attached" distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe(fileLoggerParameters[0] + ";" + fileLoggerParameters[1], StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" @@ -1924,14 +1887,12 @@ public void TestProcessFileLoggerSwitch4() distributedLoggerRecords = new List(); loggers = new List(); fileLoggerParameters = new[] { "Parameter1", "verbosity=Normal;logfile=" + Path.Combine("..", "cat.log") + ";Parameter1" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" distributedLoggerRecords.Count.ShouldBe(1); // "Expected a distributed logger to be attached" distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe($"Parameter1;verbosity=Normal;logFile={Path.Combine(Directory.GetCurrentDirectory(), "..", "cat.log")};Parameter1", StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" @@ -1939,14 +1900,12 @@ public void TestProcessFileLoggerSwitch4() loggers = new List(); distributedLoggerRecords = new List(); fileLoggerParameters = new[] { "Parameter1", ";Parameter;", "", ";", ";Parameter", "Parameter;" }; - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 2 - ); + 2); distributedLoggerRecords[0].ForwardingLoggerDescription.LoggerSwitchParameters.ShouldBe($"Parameter1;Parameter;;;Parameter;Parameter;logFile={Path.Combine(Directory.GetCurrentDirectory(), "msbuild.log")}", StringCompareShould.IgnoreCase); // "Expected parameter in logger to match parameter passed in" } @@ -1961,14 +1920,12 @@ public void TestProcessFileLoggerSwitch5() List distributedLoggerRecords = new List(); var loggers = new List(); - MSBuildApp.ProcessDistributedFileLogger - ( + MSBuildApp.ProcessDistributedFileLogger( distributedFileLogger, fileLoggerParameters, distributedLoggerRecords, loggers, - 1 - ); + 1); distributedLoggerRecords.Count.ShouldBe(0); // "Expected no distributed loggers to be attached" loggers.Count.ShouldBe(0); // "Expected no central loggers to be attached" } @@ -1983,27 +1940,23 @@ public void ProcessConsoleLoggerSwitches() List distributedLoggerRecords = new List(); string[] consoleLoggerParameters = { "Parameter1", ";Parameter;", "", ";", ";Parameter", "Parameter;" }; - MSBuildApp.ProcessConsoleLoggerSwitch - ( + MSBuildApp.ProcessConsoleLoggerSwitch( true, consoleLoggerParameters, distributedLoggerRecords, verbosity, 1, - loggers - ); + loggers); loggers.ShouldBeEmpty("Expected no central loggers to be attached"); distributedLoggerRecords.ShouldBeEmpty("Expected no distributed loggers to be attached"); - MSBuildApp.ProcessConsoleLoggerSwitch - ( + MSBuildApp.ProcessConsoleLoggerSwitch( false, consoleLoggerParameters, distributedLoggerRecords, verbosity, 1, - loggers - ); + loggers); loggers.ShouldHaveSingleItem("Expected a central logger to be attached"); loggers[0].ShouldBeOfType(); loggers[0].Parameters.ShouldBe( @@ -2011,15 +1964,13 @@ public void ProcessConsoleLoggerSwitches() "Expected parameter in logger to match parameters passed in", StringCompareShould.IgnoreCase); - MSBuildApp.ProcessConsoleLoggerSwitch - ( + MSBuildApp.ProcessConsoleLoggerSwitch( false, consoleLoggerParameters, distributedLoggerRecords, verbosity, 2, - loggers - ); + loggers); loggers.ShouldHaveSingleItem("Expected a central logger to be attached"); distributedLoggerRecords.ShouldHaveSingleItem("Expected a distributed logger to be attached"); DistributedLoggerRecord distributedLogger = distributedLoggerRecords[0]; diff --git a/src/MSBuild/AssemblyInfo.cs b/src/MSBuild/AssemblyInfo.cs index b30ea61e1dc..f93e8a6db00 100644 --- a/src/MSBuild/AssemblyInfo.cs +++ b/src/MSBuild/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/MSBuild/AssemblyResources.cs b/src/MSBuild/AssemblyResources.cs index ed9431764ac..a0eaaa57204 100644 --- a/src/MSBuild/AssemblyResources.cs +++ b/src/MSBuild/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/MSBuild/CommandLineSwitchException.cs b/src/MSBuild/CommandLineSwitchException.cs index d5a4b8bb7a6..50cca72257a 100644 --- a/src/MSBuild/CommandLineSwitchException.cs +++ b/src/MSBuild/CommandLineSwitchException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -23,10 +23,8 @@ internal sealed class CommandLineSwitchException : Exception /// This constructor initializes the exception message. /// /// - private CommandLineSwitchException - ( - string message - ) : + private CommandLineSwitchException( + string message) : base(message) { // do nothing @@ -37,11 +35,9 @@ string message /// /// /// - private CommandLineSwitchException - ( + private CommandLineSwitchException( string message, - string commandLineArg - ) : + string commandLineArg) : this(message) { this.commandLineArg = commandLineArg; @@ -50,11 +46,9 @@ string commandLineArg /// /// Serialization constructor /// - private CommandLineSwitchException - ( + private CommandLineSwitchException( SerializationInfo info, - StreamingContext context - ) : + StreamingContext context) : base(info, context) { ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info)); diff --git a/src/MSBuild/CommandLineSwitches.cs b/src/MSBuild/CommandLineSwitches.cs index 4ec352da9a3..c9785c3b3fe 100644 --- a/src/MSBuild/CommandLineSwitches.cs +++ b/src/MSBuild/CommandLineSwitches.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -122,12 +122,10 @@ private struct ParameterlessSwitchInfo /// /// /// - internal ParameterlessSwitchInfo - ( + internal ParameterlessSwitchInfo( string[] switchNames, ParameterlessSwitch parameterlessSwitch, - string duplicateSwitchErrorMessage - ) + string duplicateSwitchErrorMessage) { this.switchNames = switchNames; this.duplicateSwitchErrorMessage = duplicateSwitchErrorMessage; @@ -158,16 +156,14 @@ private struct ParameterizedSwitchInfo /// /// /// - internal ParameterizedSwitchInfo - ( + internal ParameterizedSwitchInfo( string[] switchNames, ParameterizedSwitch parameterizedSwitch, string duplicateSwitchErrorMessage, bool multipleParametersAllowed, string missingParametersErrorMessage, bool unquoteParameters, - bool emptyParametersAllowed - ) + bool emptyParametersAllowed) { this.switchNames = switchNames; this.duplicateSwitchErrorMessage = duplicateSwitchErrorMessage; @@ -234,47 +230,47 @@ bool emptyParametersAllowed //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ // Switch Names Switch Id Duplicate Switch Error Multi Params? Missing Parameters Error Unquote? Empty? //------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ - new ParameterizedSwitchInfo( new string[] { null }, ParameterizedSwitch.Project, "DuplicateProjectSwitchError", false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "target", "t"}, ParameterizedSwitch.Target, null, true, "MissingTargetError", true, false ), - new ParameterizedSwitchInfo( new string[] { "property", "p" }, ParameterizedSwitch.Property, null, true, "MissingPropertyError", true, false ), - new ParameterizedSwitchInfo( new string[] { "logger", "l" }, ParameterizedSwitch.Logger, null, false, "MissingLoggerError", false, false ), - new ParameterizedSwitchInfo( new string[] { "distributedlogger", "dl" }, ParameterizedSwitch.DistributedLogger, null, false, "MissingLoggerError", false, false ), - new ParameterizedSwitchInfo( new string[] { "verbosity", "v" }, ParameterizedSwitch.Verbosity, null, false, "MissingVerbosityError", true, false ), + new ParameterizedSwitchInfo( new string[] { null }, ParameterizedSwitch.Project, "DuplicateProjectSwitchError", false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "target", "t"}, ParameterizedSwitch.Target, null, true, "MissingTargetError", true, false), + new ParameterizedSwitchInfo( new string[] { "property", "p" }, ParameterizedSwitch.Property, null, true, "MissingPropertyError", true, false), + new ParameterizedSwitchInfo( new string[] { "logger", "l" }, ParameterizedSwitch.Logger, null, false, "MissingLoggerError", false, false), + new ParameterizedSwitchInfo( new string[] { "distributedlogger", "dl" }, ParameterizedSwitch.DistributedLogger, null, false, "MissingLoggerError", false, false), + new ParameterizedSwitchInfo( new string[] { "verbosity", "v" }, ParameterizedSwitch.Verbosity, null, false, "MissingVerbosityError", true, false), #if FEATURE_XML_SCHEMA_VALIDATION - new ParameterizedSwitchInfo( new string[] { "validate", "val" }, ParameterizedSwitch.Validate, null, false, null, true, false ), + new ParameterizedSwitchInfo( new string[] { "validate", "val" }, ParameterizedSwitch.Validate, null, false, null, true, false), #endif - new ParameterizedSwitchInfo( new string[] { "consoleloggerparameters", "clp" }, ParameterizedSwitch.ConsoleLoggerParameters, null, false, "MissingConsoleLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "nodemode", "nmode" }, ParameterizedSwitch.NodeMode, null, false, null, false, false ), - new ParameterizedSwitchInfo( new string[] { "maxcpucount", "m" }, ParameterizedSwitch.MaxCPUCount, null, false, "MissingMaxCPUCountError", true, false ), - new ParameterizedSwitchInfo( new string[] { "ignoreprojectextensions", "ignore" }, ParameterizedSwitch.IgnoreProjectExtensions, null, true, "MissingIgnoreProjectExtensionsError", true, false ), - new ParameterizedSwitchInfo( new string[] { "toolsversion","tv" }, ParameterizedSwitch.ToolsVersion, null, false, "MissingToolsVersionError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters", "flp" }, ParameterizedSwitch.FileLoggerParameters, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters1", "flp1" }, ParameterizedSwitch.FileLoggerParameters1, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters2", "flp2" }, ParameterizedSwitch.FileLoggerParameters2, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters3", "flp3" }, ParameterizedSwitch.FileLoggerParameters3, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters4", "flp4" }, ParameterizedSwitch.FileLoggerParameters4, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters5", "flp5" }, ParameterizedSwitch.FileLoggerParameters5, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters6", "flp6" }, ParameterizedSwitch.FileLoggerParameters6, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters7", "flp7" }, ParameterizedSwitch.FileLoggerParameters7, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters8", "flp8" }, ParameterizedSwitch.FileLoggerParameters8, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "fileloggerparameters9", "flp9" }, ParameterizedSwitch.FileLoggerParameters9, null, false, "MissingFileLoggerParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "nodereuse", "nr" }, ParameterizedSwitch.NodeReuse, null, false, "MissingNodeReuseParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "preprocess", "pp" }, ParameterizedSwitch.Preprocess, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "targets", "ts" }, ParameterizedSwitch.Targets, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "warnaserror", "err" }, ParameterizedSwitch.WarningsAsErrors, null, true, null, true, true ), - new ParameterizedSwitchInfo( new string[] { "warnnotaserror", "noerr" }, ParameterizedSwitch.WarningsNotAsErrors, null, true, "MissingWarnNotAsErrorParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "warnasmessage", "nowarn" }, ParameterizedSwitch.WarningsAsMessages, null, true, "MissingWarnAsMessageParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "binarylogger", "bl" }, ParameterizedSwitch.BinaryLogger, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "restore", "r" }, ParameterizedSwitch.Restore, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "profileevaluation", "prof" }, ParameterizedSwitch.ProfileEvaluation, null, false, "MissingProfileParameterError", true, false ), - new ParameterizedSwitchInfo( new string[] { "restoreproperty", "rp" }, ParameterizedSwitch.RestoreProperty, null, true, "MissingPropertyError", true, false ), - new ParameterizedSwitchInfo( new string[] { "interactive" }, ParameterizedSwitch.Interactive, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "isolateprojects", "isolate" }, ParameterizedSwitch.IsolateProjects, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "graphbuild", "graph" }, ParameterizedSwitch.GraphBuild, null, true, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "inputResultsCaches", "irc" }, ParameterizedSwitch.InputResultsCaches, null, true, null, true, true ), - new ParameterizedSwitchInfo( new string[] { "outputResultsCache", "orc" }, ParameterizedSwitch.OutputResultsCache, "DuplicateOutputResultsCache", false, null, true, true ), - new ParameterizedSwitchInfo( new string[] { "lowpriority", "low" }, ParameterizedSwitch.LowPriority, null, false, null, true, false ), - new ParameterizedSwitchInfo( new string[] { "detailedsummary", "ds" }, ParameterizedSwitch.DetailedSummary, null, false, null, true, false ), + new ParameterizedSwitchInfo( new string[] { "consoleloggerparameters", "clp" }, ParameterizedSwitch.ConsoleLoggerParameters, null, false, "MissingConsoleLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "nodemode", "nmode" }, ParameterizedSwitch.NodeMode, null, false, null, false, false), + new ParameterizedSwitchInfo( new string[] { "maxcpucount", "m" }, ParameterizedSwitch.MaxCPUCount, null, false, "MissingMaxCPUCountError", true, false), + new ParameterizedSwitchInfo( new string[] { "ignoreprojectextensions", "ignore" }, ParameterizedSwitch.IgnoreProjectExtensions, null, true, "MissingIgnoreProjectExtensionsError", true, false), + new ParameterizedSwitchInfo( new string[] { "toolsversion","tv" }, ParameterizedSwitch.ToolsVersion, null, false, "MissingToolsVersionError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters", "flp" }, ParameterizedSwitch.FileLoggerParameters, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters1", "flp1" }, ParameterizedSwitch.FileLoggerParameters1, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters2", "flp2" }, ParameterizedSwitch.FileLoggerParameters2, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters3", "flp3" }, ParameterizedSwitch.FileLoggerParameters3, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters4", "flp4" }, ParameterizedSwitch.FileLoggerParameters4, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters5", "flp5" }, ParameterizedSwitch.FileLoggerParameters5, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters6", "flp6" }, ParameterizedSwitch.FileLoggerParameters6, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters7", "flp7" }, ParameterizedSwitch.FileLoggerParameters7, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters8", "flp8" }, ParameterizedSwitch.FileLoggerParameters8, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "fileloggerparameters9", "flp9" }, ParameterizedSwitch.FileLoggerParameters9, null, false, "MissingFileLoggerParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "nodereuse", "nr" }, ParameterizedSwitch.NodeReuse, null, false, "MissingNodeReuseParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "preprocess", "pp" }, ParameterizedSwitch.Preprocess, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "targets", "ts" }, ParameterizedSwitch.Targets, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "warnaserror", "err" }, ParameterizedSwitch.WarningsAsErrors, null, true, null, true, true), + new ParameterizedSwitchInfo( new string[] { "warnnotaserror", "noerr" }, ParameterizedSwitch.WarningsNotAsErrors, null, true, "MissingWarnNotAsErrorParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "warnasmessage", "nowarn" }, ParameterizedSwitch.WarningsAsMessages, null, true, "MissingWarnAsMessageParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "binarylogger", "bl" }, ParameterizedSwitch.BinaryLogger, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "restore", "r" }, ParameterizedSwitch.Restore, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "profileevaluation", "prof" }, ParameterizedSwitch.ProfileEvaluation, null, false, "MissingProfileParameterError", true, false), + new ParameterizedSwitchInfo( new string[] { "restoreproperty", "rp" }, ParameterizedSwitch.RestoreProperty, null, true, "MissingPropertyError", true, false), + new ParameterizedSwitchInfo( new string[] { "interactive" }, ParameterizedSwitch.Interactive, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "isolateprojects", "isolate" }, ParameterizedSwitch.IsolateProjects, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "graphbuild", "graph" }, ParameterizedSwitch.GraphBuild, null, true, null, true, false), + new ParameterizedSwitchInfo( new string[] { "inputResultsCaches", "irc" }, ParameterizedSwitch.InputResultsCaches, null, true, null, true, true), + new ParameterizedSwitchInfo( new string[] { "outputResultsCache", "orc" }, ParameterizedSwitch.OutputResultsCache, "DuplicateOutputResultsCache", false, null, true, true), + new ParameterizedSwitchInfo( new string[] { "lowpriority", "low" }, ParameterizedSwitch.LowPriority, null, false, null, true, false), + new ParameterizedSwitchInfo( new string[] { "detailedsummary", "ds" }, ParameterizedSwitch.DetailedSummary, null, false, null, true, false), }; /// @@ -284,12 +280,10 @@ bool emptyParametersAllowed /// [out] switch identifier (from ParameterlessSwitch enumeration) /// /// true, if switch is a recognized switch that doesn't take parameters - internal static bool IsParameterlessSwitch - ( + internal static bool IsParameterlessSwitch( string switchName, out ParameterlessSwitch parameterlessSwitch, - out string duplicateSwitchErrorMessage - ) + out string duplicateSwitchErrorMessage) { parameterlessSwitch = ParameterlessSwitch.Invalid; duplicateSwitchErrorMessage = null; @@ -313,10 +307,8 @@ out string duplicateSwitchErrorMessage /// /// Identifies/detects a switch that takes no parameters. /// - internal static bool IsParameterlessSwitch - ( - string switchName - ) + internal static bool IsParameterlessSwitch( + string switchName) { ParameterlessSwitch parameterlessSwitch; string duplicateSwitchErrorMessage; @@ -333,16 +325,14 @@ string switchName /// /// /// true, if switch is a recognized switch that takes parameters - internal static bool IsParameterizedSwitch - ( + internal static bool IsParameterizedSwitch( string switchName, out ParameterizedSwitch parameterizedSwitch, out string duplicateSwitchErrorMessage, out bool multipleParametersAllowed, out string missingParametersErrorMessage, out bool unquoteParameters, - out bool emptyParametersAllowed - ) + out bool emptyParametersAllowed) { parameterizedSwitch = ParameterizedSwitch.Invalid; duplicateSwitchErrorMessage = null; @@ -450,15 +440,13 @@ internal void SetParameterlessSwitch(ParameterlessSwitch parameterlessSwitch, st /// /// /// true, if the given parameters were successfully stored - internal bool SetParameterizedSwitch - ( + internal bool SetParameterizedSwitch( ParameterizedSwitch parameterizedSwitch, string commandLineArg, string switchParameters, bool multipleParametersAllowed, bool unquoteParameters, - bool emptyParametersAllowed - ) + bool emptyParametersAllowed) { bool parametersStored = false; @@ -477,8 +465,7 @@ bool emptyParametersAllowed _parameterizedSwitches[(int)parameterizedSwitch].commandLineArg = string.Concat( _parameterizedSwitches[(int)parameterizedSwitch].commandLineArg, " ", - commandLineArg - ); + commandLineArg); } // check if the switch has multiple parameters @@ -487,7 +474,7 @@ bool emptyParametersAllowed if (String.Empty.Equals(switchParameters) && emptyParametersAllowed) { // Store a null parameter if its allowed - _parameterizedSwitches[(int) parameterizedSwitch].parameters.Add(null); + _parameterizedSwitches[(int)parameterizedSwitch].parameters.Add(null); parametersStored = true; } else diff --git a/src/MSBuild/DistributedLoggerRecord.cs b/src/MSBuild/DistributedLoggerRecord.cs index 695b2834563..b13a5a33a9f 100644 --- a/src/MSBuild/DistributedLoggerRecord.cs +++ b/src/MSBuild/DistributedLoggerRecord.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Logging; diff --git a/src/MSBuild/InitializationException.cs b/src/MSBuild/InitializationException.cs index deb2a93f11c..ff5a5e21ade 100644 --- a/src/MSBuild/InitializationException.cs +++ b/src/MSBuild/InitializationException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; @@ -28,10 +28,8 @@ internal sealed class InitializationException : Exception /// This constructor initializes the exception message. /// /// - private InitializationException - ( - string message - ) : + private InitializationException( + string message) : base(message) { // do nothing @@ -42,11 +40,9 @@ string message /// /// /// Can be null. - private InitializationException - ( + private InitializationException( string message, - string invalidSwitch - ) : + string invalidSwitch) : this(message) { this.invalidSwitch = invalidSwitch; @@ -55,11 +51,9 @@ string invalidSwitch /// /// Serialization constructor /// - private InitializationException - ( + private InitializationException( SerializationInfo info, - StreamingContext context - ) : + StreamingContext context) : base(info, context) { ErrorUtilities.VerifyThrowArgumentNull(info, nameof(info)); diff --git a/src/MSBuild/LogMessagePacket.cs b/src/MSBuild/LogMessagePacket.cs index 2e69e1f1e36..a91d2619447 100644 --- a/src/MSBuild/LogMessagePacket.cs +++ b/src/MSBuild/LogMessagePacket.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -42,7 +42,7 @@ private LogMessagePacket(ITranslator translator) /// /// Factory for serialization /// - static internal INodePacket FactoryForDeserialization(ITranslator translator) + internal static INodePacket FactoryForDeserialization(ITranslator translator) { return new LogMessagePacket(translator); } diff --git a/src/MSBuild/MSBuildClientApp.cs b/src/MSBuild/MSBuildClientApp.cs index 0fd4ea40181..c9ea4f7cd03 100644 --- a/src/MSBuild/MSBuildClientApp.cs +++ b/src/MSBuild/MSBuildClientApp.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; @@ -40,8 +40,7 @@ public static MSBuildApp.ExitType Execute( #else string[] commandLine, #endif - CancellationToken cancellationToken - ) + CancellationToken cancellationToken) { string msbuildLocation = BuildEnvironmentHelper.Instance.CurrentMSBuildExePath; @@ -71,7 +70,7 @@ public static MSBuildApp.ExitType Execute( string msbuildLocation, CancellationToken cancellationToken) { - MSBuildClient msbuildClient = new MSBuildClient(commandLine, msbuildLocation); + MSBuildClient msbuildClient = new MSBuildClient(commandLine, msbuildLocation); MSBuildClientExitResult exitResult = msbuildClient.Execute(cancellationToken); if (exitResult.MSBuildClientExitType == MSBuildClientExitType.ServerBusy || diff --git a/src/MSBuild/NodeEndpointOutOfProcTaskHost.cs b/src/MSBuild/NodeEndpointOutOfProcTaskHost.cs index 36ea494b383..a2f7e5695fc 100644 --- a/src/MSBuild/NodeEndpointOutOfProcTaskHost.cs +++ b/src/MSBuild/NodeEndpointOutOfProcTaskHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; using Microsoft.Build.Internal; diff --git a/src/MSBuild/OutOfProcTaskAppDomainWrapper.cs b/src/MSBuild/OutOfProcTaskAppDomainWrapper.cs index 2812e8b48de..d8520ec4b61 100644 --- a/src/MSBuild/OutOfProcTaskAppDomainWrapper.cs +++ b/src/MSBuild/OutOfProcTaskAppDomainWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/MSBuild/OutOfProcTaskAppDomainWrapperBase.cs b/src/MSBuild/OutOfProcTaskAppDomainWrapperBase.cs index 10655f84b09..49475409d3f 100644 --- a/src/MSBuild/OutOfProcTaskAppDomainWrapperBase.cs +++ b/src/MSBuild/OutOfProcTaskAppDomainWrapperBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -89,8 +89,7 @@ internal bool CancelPending /// The AppDomainSetup that we want to use to launch our AppDomainIsolated tasks /// Parameters that will be passed to the task when created /// Task completion result showing success, failure or if there was a crash - internal OutOfProcTaskHostTaskResult ExecuteTask - ( + internal OutOfProcTaskHostTaskResult ExecuteTask( IBuildEngine oopTaskHostNode, string taskName, string taskLocation, @@ -100,8 +99,7 @@ internal OutOfProcTaskHostTaskResult ExecuteTask #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif - IDictionary taskParams - ) + IDictionary taskParams) { buildEngine = oopTaskHostNode; this.taskName = taskName; @@ -123,13 +121,11 @@ IDictionary taskParams // so just save that instead. Exception exceptionToReturn = e is TargetInvocationException ? e.InnerException : e; - return new OutOfProcTaskHostTaskResult - ( + return new OutOfProcTaskHostTaskResult( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", - new string[] { taskName, taskLocation, String.Empty } - ); + new string[] { taskName, taskLocation, String.Empty }); } OutOfProcTaskHostTaskResult taskResult; @@ -142,13 +138,11 @@ IDictionary taskParams #endif taskParams); #else - return new OutOfProcTaskHostTaskResult - ( + return new OutOfProcTaskHostTaskResult( TaskCompleteType.CrashedDuringInitialization, null, "TaskInstantiationFailureNotSupported", - new string[] { taskName, taskLocation, typeof(RunInSTAAttribute).FullName } - ); + new string[] { taskName, taskLocation, typeof(RunInSTAAttribute).FullName }); #endif } else @@ -189,8 +183,7 @@ internal void CleanupTask() /// STA thread launching code lifted from XMakeBuildEngine\BackEnd\Components\RequestBuilder\TaskBuilder.cs, ExecuteTaskInSTAThread method. /// Any bug fixes made to this code, please ensure that you also fix that code. /// - private OutOfProcTaskHostTaskResult InstantiateAndExecuteTaskInSTAThread - ( + private OutOfProcTaskHostTaskResult InstantiateAndExecuteTaskInSTAThread( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, @@ -201,8 +194,7 @@ private OutOfProcTaskHostTaskResult InstantiateAndExecuteTaskInSTAThread #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif - IDictionary taskParams - ) + IDictionary taskParams) { ManualResetEvent taskRunnerFinished = new ManualResetEvent(false); OutOfProcTaskHostTaskResult taskResult = null; @@ -214,8 +206,7 @@ IDictionary taskParams { try { - taskResult = InstantiateAndExecuteTask - ( + taskResult = InstantiateAndExecuteTask( oopTaskHostNode, taskType, taskName, @@ -226,8 +217,7 @@ IDictionary taskParams #if FEATURE_APPDOMAIN appDomainSetup, #endif - taskParams - ); + taskParams); } catch (Exception e) when (!ExceptionHandling.IsCriticalException(e)) { @@ -238,7 +228,7 @@ IDictionary taskParams taskRunnerFinished.Set(); } }; - + Thread staThread = new Thread(taskRunnerDelegate); staThread.SetApartmentState(ApartmentState.STA); staThread.Name = "MSBuild STA task runner thread"; @@ -272,8 +262,7 @@ IDictionary taskParams /// /// Do the work of actually instantiating and running the task. /// - private OutOfProcTaskHostTaskResult InstantiateAndExecuteTask - ( + private OutOfProcTaskHostTaskResult InstantiateAndExecuteTask( IBuildEngine oopTaskHostNode, LoadedType taskType, string taskName, @@ -284,8 +273,7 @@ private OutOfProcTaskHostTaskResult InstantiateAndExecuteTask #if FEATURE_APPDOMAIN AppDomainSetup appDomainSetup, #endif - IDictionary taskParams - ) + IDictionary taskParams) { #if FEATURE_APPDOMAIN _taskAppDomain = null; @@ -294,7 +282,14 @@ IDictionary taskParams try { - wrappedTask = TaskLoader.CreateTask(taskType, taskName, taskFile, taskLine, taskColumn, new TaskLoader.LogError(LogErrorDelegate), +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + wrappedTask = TaskLoader.CreateTask( + taskType, + taskName, + taskFile, + taskLine, + taskColumn, + new TaskLoader.LogError(LogErrorDelegate), #if FEATURE_APPDOMAIN appDomainSetup, #endif @@ -303,6 +298,7 @@ IDictionary taskParams , out _taskAppDomain #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter wrappedTask.BuildEngine = oopTaskHostNode; } @@ -317,13 +313,11 @@ IDictionary taskParams exceptionToReturn = e.InnerException; } - return new OutOfProcTaskHostTaskResult - ( + return new OutOfProcTaskHostTaskResult( TaskCompleteType.CrashedDuringInitialization, exceptionToReturn, "TaskInstantiationFailureError", - new string[] { taskName, taskLocation, String.Empty } - ); + new string[] { taskName, taskLocation, String.Empty }); } foreach (KeyValuePair param in taskParams) @@ -335,14 +329,12 @@ IDictionary taskParams } catch (Exception e) when (!ExceptionHandling.IsCriticalException(e)) { - return new OutOfProcTaskHostTaskResult - ( + return new OutOfProcTaskHostTaskResult( TaskCompleteType.CrashedDuringInitialization, // If it's a TargetInvocationException, we only care about the contents of the inner exception, so save that instead. e is TargetInvocationException ? e.InnerException : e, "InvalidTaskAttributeError", - new string[] { param.Key, param.Value.ToString(), taskName } - ); + new string[] { param.Key, param.Value.ToString(), taskName }); } } @@ -402,9 +394,7 @@ private void LogErrorDelegate(string taskLocation, int taskLine, int taskColumn, 0, ResourceUtilities.FormatString(AssemblyResources.GetString(message), messageArgs), null, - taskName - ) - ); + taskName)); } } } diff --git a/src/MSBuild/OutOfProcTaskHostNode.cs b/src/MSBuild/OutOfProcTaskHostNode.cs index 629d9141a93..31209200c7b 100644 --- a/src/MSBuild/OutOfProcTaskHostNode.cs +++ b/src/MSBuild/OutOfProcTaskHostNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -901,8 +901,7 @@ private void RunTask(object state) // As a fix, we will create the class directly without wrapping it in a domain _taskWrapper = new OutOfProcTaskAppDomainWrapper(); - taskResult = _taskWrapper.ExecuteTask - ( + taskResult = _taskWrapper.ExecuteTask( this as IBuildEngine, taskName, taskLocation, @@ -912,8 +911,7 @@ private void RunTask(object state) #if FEATURE_APPDOMAIN taskConfiguration.AppDomainSetup, #endif - taskParams - ); + taskParams); } catch (ThreadAbortException) { @@ -937,11 +935,9 @@ private void RunTask(object state) lock (_taskCompleteLock) { - _taskCompletePacket = new TaskHostTaskComplete - ( + _taskCompletePacket = new TaskHostTaskComplete( taskResult, - currentEnvironment - ); + currentEnvironment); } #if FEATURE_APPDOMAIN @@ -1173,13 +1169,11 @@ private void LogMessageFromResource(MessageImportance importance, string message ErrorUtilities.VerifyThrow(_currentConfiguration != null, "We should never have a null configuration when we're trying to log messages!"); // Using the CLR 2 build event because this class is shared between MSBuildTaskHost.exe (CLR2) and MSBuild.exe (CLR4+) - BuildMessageEventArgs message = new BuildMessageEventArgs - ( + BuildMessageEventArgs message = new BuildMessageEventArgs( ResourceUtilities.FormatString(AssemblyResources.GetString(messageResource), messageArgs), null, _currentConfiguration.TaskName, - importance - ); + importance); LogMessageEvent(message); } @@ -1192,8 +1186,7 @@ private void LogWarningFromResource(string messageResource, params object[] mess ErrorUtilities.VerifyThrow(_currentConfiguration != null, "We should never have a null configuration when we're trying to log warnings!"); // Using the CLR 2 build event because this class is shared between MSBuildTaskHost.exe (CLR2) and MSBuild.exe (CLR4+) - BuildWarningEventArgs warning = new BuildWarningEventArgs - ( + BuildWarningEventArgs warning = new BuildWarningEventArgs( null, null, ProjectFileOfTaskNode, @@ -1203,8 +1196,7 @@ private void LogWarningFromResource(string messageResource, params object[] mess 0, ResourceUtilities.FormatString(AssemblyResources.GetString(messageResource), messageArgs), null, - _currentConfiguration.TaskName - ); + _currentConfiguration.TaskName); LogWarningEvent(warning); } @@ -1217,8 +1209,7 @@ private void LogErrorFromResource(string messageResource) ErrorUtilities.VerifyThrow(_currentConfiguration != null, "We should never have a null configuration when we're trying to log errors!"); // Using the CLR 2 build event because this class is shared between MSBuildTaskHost.exe (CLR2) and MSBuild.exe (CLR4+) - BuildErrorEventArgs error = new BuildErrorEventArgs - ( + BuildErrorEventArgs error = new BuildErrorEventArgs( null, null, ProjectFileOfTaskNode, @@ -1228,8 +1219,7 @@ private void LogErrorFromResource(string messageResource) 0, AssemblyResources.GetString(messageResource), null, - _currentConfiguration.TaskName - ); + _currentConfiguration.TaskName); LogErrorEvent(error); } diff --git a/src/MSBuild/PerformanceLogEventListener.cs b/src/MSBuild/PerformanceLogEventListener.cs index 3e08da0d512..4aaa1283384 100644 --- a/src/MSBuild/PerformanceLogEventListener.cs +++ b/src/MSBuild/PerformanceLogEventListener.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/MSBuild/ProjectSchemaValidationHandler.cs b/src/MSBuild/ProjectSchemaValidationHandler.cs index 3f6b1cce5f7..f23360f892b 100644 --- a/src/MSBuild/ProjectSchemaValidationHandler.cs +++ b/src/MSBuild/ProjectSchemaValidationHandler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_XML_SCHEMA_VALIDATION using System; @@ -21,7 +21,7 @@ internal sealed class ProjectSchemaValidationHandler { // Set to true if there was a syntax error in the project file. private bool _syntaxError; - +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Methods /// @@ -33,12 +33,10 @@ internal sealed class ProjectSchemaValidationHandler /// Path to the framework directory where the default schema for /// this ToolsVersion can be found. /// True if the project was successfully validated against the given schema, false otherwise - internal static void VerifyProjectSchema - ( + internal static void VerifyProjectSchema( string projectFile, string schemaFile, - string binPath - ) + string binPath) { ErrorUtilities.VerifyThrowArgumentNull(projectFile, nameof(projectFile)); ErrorUtilities.VerifyThrowArgumentNull(binPath, nameof(binPath)); @@ -57,11 +55,9 @@ string binPath else { // If we've gotten to this point, there is no schema to validate against -- just exit. - InitializationException.Throw - ( + InitializationException.Throw( ResourceUtilities.FormatResourceStringStripCodeAndKeyword("SchemaNotFoundErrorWithFile", schemaFile), - null /* No associated command line switch */ - ); + null); /* No associated command line switch */ } ProjectSchemaValidationHandler validationHandler = new ProjectSchemaValidationHandler(); @@ -72,11 +68,9 @@ string binPath /// /// Validates a project against the given schema. A schema file must be provided. /// - private void VerifyProjectSchema - ( + private void VerifyProjectSchema( string projectFile, - string schemaFile - ) + string schemaFile) { ErrorUtilities.VerifyThrowArgumentNull(schemaFile, nameof(schemaFile)); ErrorUtilities.VerifyThrowArgumentNull(projectFile, nameof(projectFile)); @@ -124,24 +118,21 @@ string schemaFile } } - VerifyThrowInitializationExceptionWithResource - ( + VerifyThrowInitializationExceptionWithResource( !_syntaxError, projectFile, 0 /* line */, 0 /* end line */, 0 /* column */, 0 /* end column */, - "ProjectSchemaErrorHalt" - ); + "ProjectSchemaErrorHalt"); } } } // handle errors in the schema itself catch (XmlException e) { - ThrowInitializationExceptionWithResource - ( + ThrowInitializationExceptionWithResource( (e.SourceUri.Length == 0) ? String.Empty : new Uri(e.SourceUri).LocalPath, e.LineNumber, 0 /* end line */, @@ -149,14 +140,12 @@ string schemaFile 0 /* end column */, "InvalidSchemaFile", schemaFile, - e.Message - ); + e.Message); } // handle errors in the schema itself catch (XmlSchemaException e) { - ThrowInitializationExceptionWithResource - ( + ThrowInitializationExceptionWithResource( (e.SourceUri.Length == 0) ? String.Empty : new Uri(e.SourceUri).LocalPath, e.LineNumber, 0 /* end line */, @@ -164,8 +153,7 @@ string schemaFile 0 /* end column */, "InvalidSchemaFile", schemaFile, - e.Message - ); + e.Message); } } } @@ -174,8 +162,7 @@ string schemaFile /// Given the parameters passed in, if the condition is false, builds an /// error message and throws an InitializationException with that message. /// - private static void VerifyThrowInitializationExceptionWithResource - ( + private static void VerifyThrowInitializationExceptionWithResource( bool condition, string projectFile, int fileLine, @@ -183,21 +170,18 @@ private static void VerifyThrowInitializationExceptionWithResource int fileColumn, int fileEndColumn, string resourceName, - params object[] args - ) + params object[] args) { if (!condition) { - ThrowInitializationExceptionWithResource - ( + ThrowInitializationExceptionWithResource( projectFile, fileLine, fileEndLine, fileColumn, fileEndColumn, resourceName, - args - ); + args); } } @@ -205,54 +189,45 @@ params object[] args /// Given the parameters passed in, builds an error message and throws an /// InitializationException with that message. /// - private static void ThrowInitializationExceptionWithResource - ( + private static void ThrowInitializationExceptionWithResource( string projectFile, int fileLine, int fileEndLine, int fileColumn, int fileEndColumn, string resourceName, - params object[] args - ) + params object[] args) { - InitializationException.Throw - ( - BuildStringFromResource - ( + InitializationException.Throw( + BuildStringFromResource( projectFile, fileLine, fileEndLine, fileColumn, fileEndColumn, resourceName, - args - ), - null /* No associated command line switch */ - ); + args), + null); /* No associated command line switch */ } /// /// Given a resource string and information about a file, builds up a string /// containing the message. /// - private static string BuildStringFromResource - ( + private static string BuildStringFromResource( string projectFile, int fileLine, int fileEndLine, int fileColumn, int fileEndColumn, string resourceName, - params object[] args - ) + params object[] args) { string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword(out errorCode, out helpKeyword, resourceName, args); - return EventArgsFormatting.FormatEventMessage - ( + return EventArgsFormatting.FormatEventMessage( "error", AssemblyResources.GetString("SubCategoryForSchemaValidationErrors"), message, @@ -262,8 +237,7 @@ params object[] args fileEndLine, fileColumn, fileEndColumn, - 0 /* thread id */ - ); + 0); /* thread id */ } #endregion // Methods @@ -287,22 +261,19 @@ private void OnSchemaValidationError(object sender, ValidationEventArgs args) filePath = (new Uri(args.Exception.SourceUri)).LocalPath; } - Console.WriteLine - ( - BuildStringFromResource - ( + Console.WriteLine( + BuildStringFromResource( filePath, args.Exception.LineNumber, 0 /* end line */, args.Exception.LinePosition, 0 /* end column */, "SchemaValidationError", - args.Exception.Message - ) - ); + args.Exception.Message)); } #endregion // Event Handlers +#pragma warning restore format } } #endif diff --git a/src/MSBuild/XMake.cs b/src/MSBuild/XMake.cs index cf6ba40db6a..f2ef7143789 100644 --- a/src/MSBuild/XMake.cs +++ b/src/MSBuild/XMake.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -128,7 +128,7 @@ public enum ExitType private static readonly CancellationTokenSource s_buildCancellationSource = new CancellationTokenSource(); private static readonly char[] s_commaSemicolon = { ',', ';' }; - + /// /// Static constructor /// @@ -213,11 +213,13 @@ private static void HandleConfigurationException(Exception ex) /// /// 0 on success, 1 on failure [MTAThread] +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter public static int Main( #if !FEATURE_GET_COMMANDLINE string[] args #endif ) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { DebuggerLaunchCheck(); @@ -238,15 +240,14 @@ string[] args !Traits.Instance.EscapeHatches.EnsureStdOutForChildNodesIsPrimaryStdout && CanRunServerBasedOnCommandLineSwitches( #if FEATURE_GET_COMMANDLINE - Environment.CommandLine + Environment.CommandLine)) #else - ConstructArrayArg(args) + ConstructArrayArg(args))) #endif - )) { Console.CancelKeyPress += Console_CancelKeyPress; - + // Use the client app to execute build in msbuild server. Opt-in feature. exitCode = ((s_initialized && MSBuildClientApp.Execute( #if FEATURE_GET_COMMANDLINE @@ -254,19 +255,18 @@ string[] args #else ConstructArrayArg(args), #endif - s_buildCancellationSource.Token - ) == ExitType.Success) ? 0 : 1); + s_buildCancellationSource.Token) == ExitType.Success) ? 0 : 1); } else { // return 0 on success, non-zero on failure exitCode = ((s_initialized && Execute( #if FEATURE_GET_COMMANDLINE - Environment.CommandLine + Environment.CommandLine) #else - ConstructArrayArg(args) + ConstructArrayArg(args)) #endif - ) == ExitType.Success) ? 0 : 1); + == ExitType.Success) ? 0 : 1); } if (Environment.GetEnvironmentVariable("MSBUILDDUMPPROCESSCOUNTERS") == "1") @@ -286,11 +286,10 @@ string[] args /// private static bool CanRunServerBasedOnCommandLineSwitches( #if FEATURE_GET_COMMANDLINE - string commandLine + string commandLine) #else - string[] commandLine + string[] commandLine) #endif - ) { bool canRunServer = true; try @@ -624,11 +623,10 @@ private static void DebuggerLaunchCheck() /// or the manner in which it failed. public static ExitType Execute( #if FEATURE_GET_COMMANDLINE - string commandLine + string commandLine) #else - string[] commandLine + string[] commandLine) #endif - ) { DebuggerLaunchCheck(); @@ -656,7 +654,8 @@ string[] commandLine #if FEATURE_GET_COMMANDLINE MSBuildEventSource.Log.MSBuildExeStart(commandLine); #else - if (MSBuildEventSource.Log.IsEnabled()) { + if (MSBuildEventSource.Log.IsEnabled()) + { MSBuildEventSource.Log.MSBuildExeStart(string.Join(" ", commandLine)); } #endif @@ -744,11 +743,10 @@ string[] commandLine ref lowPriority, recursing: false, #if FEATURE_GET_COMMANDLINE - commandLine + commandLine); #else - string.Join(' ', commandLine) + string.Join(' ', commandLine)); #endif - ); CommandLineSwitches.SwitchesFromResponseFiles = null; @@ -813,9 +811,9 @@ string[] commandLine inputResultsCaches, outputResultsCache, commandLine)) - { - exitType = ExitType.BuildError; - } + { + exitType = ExitType.BuildError; + } } // end of build DateTime t2 = DateTime.Now; @@ -966,7 +964,8 @@ string[] commandLine #if FEATURE_GET_COMMANDLINE MSBuildEventSource.Log.MSBuildExeStop(commandLine); #else - if (MSBuildEventSource.Log.IsEnabled()) { + if (MSBuildEventSource.Log.IsEnabled()) + { MSBuildEventSource.Log.MSBuildExeStop(string.Join(" ", commandLine)); } #endif @@ -1009,7 +1008,7 @@ private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs // We're already on a threadpool thread anyway. WaitCallback callback = delegate { - try + try { s_cancelComplete.Reset(); @@ -1094,8 +1093,7 @@ private static void ResetGatheringSwitchesState() /// /// true, if build succeeds [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Not going to refactor it right now")] - internal static bool BuildProject - ( + internal static bool BuildProject( string projectFile, string[] targets, string toolsVersion, @@ -1126,11 +1124,10 @@ internal static bool BuildProject string[] inputResultsCaches, string outputResultsCache, #if FEATURE_GET_COMMANDLINE - string commandLine + string commandLine) #else - string[] commandLine + string[] commandLine) #endif - ) { if (FileUtilities.IsVCProjFilename(projectFile) || FileUtilities.IsDspFilename(projectFile)) { @@ -1186,8 +1183,7 @@ string[] commandLine { if (logger.Parameters != null && (logger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 || - logger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1) - ) + logger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1)) { logTaskInputs = true; break; @@ -1201,8 +1197,7 @@ string[] commandLine { if (logger.CentralLogger?.Parameters != null && (logger.CentralLogger.Parameters.IndexOf("V=DIAG", StringComparison.OrdinalIgnoreCase) != -1 || - logger.CentralLogger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1) - ) + logger.CentralLogger.Parameters.IndexOf("VERBOSITY=DIAG", StringComparison.OrdinalIgnoreCase) != -1)) { logTaskInputs = true; break; @@ -1215,8 +1210,7 @@ string[] commandLine bool preprocessOnly = preprocessWriter != null && !FileUtilities.IsSolutionFilename(projectFile); bool targetsOnly = targetsWriter != null && !FileUtilities.IsSolutionFilename(projectFile); - projectCollection = new ProjectCollection - ( + projectCollection = new ProjectCollection( globalProperties, loggers, null, @@ -1225,8 +1219,7 @@ string[] commandLine onlyLogCriticalEvents, loadProjectsReadOnly: !preprocessOnly, useAsynchronousLogging: true, - reuseProjectRootElementCache: s_isServerNode - ); + reuseProjectRootElementCache: s_isServerNode); if (toolsVersion != null && !projectCollection.ContainsToolset(toolsVersion)) { @@ -1349,8 +1342,7 @@ string[] commandLine new BuildManager.DeferredBuildMessage( String.Format("Included response file: {0}", responseFilePath), MessageImportance.Normal, - responseFilePath - )); + responseFilePath)); } } @@ -1375,7 +1367,7 @@ string[] commandLine { if (graphBuildOptions != null) { - graphBuildRequest = new GraphBuildRequestData(new[]{ new ProjectGraphEntryPoint(projectFile, globalProperties) }, targets, null, BuildRequestDataFlags.None, graphBuildOptions); + graphBuildRequest = new GraphBuildRequestData(new[] { new ProjectGraphEntryPoint(projectFile, globalProperties) }, targets, null, BuildRequestDataFlags.None, graphBuildOptions); } else { @@ -1664,8 +1656,7 @@ internal static void SetConsoleUI() && codepage != thisThread.CurrentUICulture.TextInfo.OEMCodePage && - codepage != thisThread.CurrentUICulture.TextInfo.ANSICodePage - ) + codepage != thisThread.CurrentUICulture.TextInfo.ANSICodePage) { thisThread.CurrentUICulture = new CultureInfo("en-US"); return; @@ -1852,15 +1843,13 @@ internal static void GatherCommandLineSwitches(List commandLineArgs, Com /// /// /// The given switch's parameters (with interesting quoting preserved). - internal static string ExtractSwitchParameters - ( + internal static string ExtractSwitchParameters( string commandLineArg, string unquotedCommandLineArg, int doubleQuotesRemovedFromArg, string switchName, int switchParameterIndicator, - int switchIndicatorsLength - ) + int switchIndicatorsLength) { // find the parameter indicator again using the quoted arg @@ -2017,15 +2006,13 @@ private static void GatherResponseFileSwitch(string unquotedCommandLineArg, Comm /// /// /// - private static void GatherParameterlessCommandLineSwitch - ( + private static void GatherParameterlessCommandLineSwitch( CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterlessSwitch parameterlessSwitch, string switchParameters, string duplicateSwitchErrorMessage, string unquotedCommandLineArg, - string commandLine - ) + string commandLine) { // switch should not have any parameters if (switchParameters.Length == 0) @@ -2059,8 +2046,7 @@ string commandLine /// /// /// - private static void GatherParameterizedCommandLineSwitch - ( + private static void GatherParameterizedCommandLineSwitch( CommandLineSwitches commandLineSwitches, CommandLineSwitches.ParameterizedSwitch parameterizedSwitch, string switchParameters, @@ -2070,8 +2056,7 @@ private static void GatherParameterizedCommandLineSwitch bool unquoteParameters, string unquotedCommandLineArg, bool allowEmptyParameters, - string commandLine - ) + string commandLine) { if (// switch must have parameters (switchParameters.Length > 1) || @@ -2197,8 +2182,7 @@ private static bool GatherAutoResponseFileSwitchesFromFullPath(string autoRespon /// performs deeper error checking on the switches and their parameters. /// /// true, if build can be invoked - private static bool ProcessCommandLineSwitches - ( + private static bool ProcessCommandLineSwitches( CommandLineSwitches switchesFromAutoResponseFile, CommandLineSwitches switchesNotFromAutoResponseFile, ref string projectFile, @@ -2232,8 +2216,7 @@ private static bool ProcessCommandLineSwitches ref string outputResultsCache, ref bool lowPriority, bool recursing, - string commandLine - ) + string commandLine) { bool invokeBuild = false; @@ -2348,8 +2331,7 @@ string commandLine ref outputResultsCache, ref lowPriority, recursing: true, - commandLine - ); + commandLine); } // figure out which targets we are building @@ -2424,7 +2406,7 @@ string commandLine commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.Verbosity], commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.NoConsoleLogger], commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.DistributedFileLogger], - commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.FancyLogger], + commandLineSwitches[CommandLineSwitches.ParameterlessSwitch.FancyLogger], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.FileLoggerParameters], // used by DistributedFileLogger commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.ConsoleLoggerParameters], commandLineSwitches[CommandLineSwitches.ParameterizedSwitch.BinaryLogger], @@ -2435,8 +2417,7 @@ string commandLine out originalVerbosity, cpuCount, out profilerLogger, - out enableProfiler - ); + out enableProfiler); // We're finished with defining individual loggers' verbosity at this point, so we don't need to worry about messing them up. if (Traits.Instance.DebugEngine) @@ -2565,7 +2546,7 @@ internal static GraphBuildOptions ProcessGraphBuildSwitch(string[] parameters) if (parameter.Trim().Equals("NoBuild", StringComparison.OrdinalIgnoreCase)) { - options = options with {Build = false}; + options = options with { Build = false }; } else { @@ -2932,12 +2913,10 @@ internal static int ProcessMaxCPUCountSwitch(string[] parameters) /// /// The project filename/path. /// Internal for testing purposes - internal static string ProcessProjectSwitch - ( + internal static string ProcessProjectSwitch( string[] parameters, string[] projectsExtensionsToIgnore, - DirectoryGetFiles getFiles - ) + DirectoryGetFiles getFiles) { ErrorUtilities.VerifyThrow(parameters.Length <= 1, "It should not be possible to specify more than 1 project at a time."); string projectFile = null; @@ -3052,7 +3031,7 @@ DirectoryGetFiles getFiles } // if there are no project, solution filter, or solution files in the directory, we can't build else if (actualProjectFiles.Count == 0 && - actualSolutionFiles.Count== 0 && + actualSolutionFiles.Count == 0 && solutionFilterFiles.Count == 0) { InitializationException.Throw("MissingProjectError", null, null, false); @@ -3202,14 +3181,13 @@ internal static Dictionary ProcessPropertySwitch(string[] parame /// Instantiates the loggers that are going to listen to events from this build. /// /// List of loggers. - private static ILogger[] ProcessLoggingSwitches - ( + private static ILogger[] ProcessLoggingSwitches( string[] loggerSwitchParameters, string[] distributedLoggerSwitchParameters, string[] verbositySwitchParameters, bool noConsoleLogger, bool distributedFileLogger, - bool fancyLoggerCommandLineOptIn, + bool fancyLoggerCommandLineOptIn, string[] fileLoggerParameters, string[] consoleLoggerParameters, string[] binaryLoggerParameters, @@ -3220,8 +3198,7 @@ private static ILogger[] ProcessLoggingSwitches out LoggerVerbosity originalVerbosity, int cpuCount, out ProfilerLogger profilerLogger, - out bool enableProfiler - ) + out bool enableProfiler) { // if verbosity level is not specified, use the default originalVerbosity = LoggerVerbosity.Normal; @@ -3301,7 +3278,10 @@ private static void ProcessFileLoggers(string[][] groupedFileLoggerParameters, L for (int i = 0; i < groupedFileLoggerParameters.Length; i++) { // If we had no, say, "/fl5" then continue; we may have a "/fl6" and so on - if (groupedFileLoggerParameters[i] == null) continue; + if (groupedFileLoggerParameters[i] == null) + { + continue; + } string fileParameters = "SHOWPROJECTFILE=TRUE;"; // Use a default log file name of "msbuild.log", "msbuild1.log", "msbuild2.log", etc; put this first on the parameter @@ -3357,7 +3337,7 @@ private static void ProcessBinaryLogger(string[] binaryLoggerParameters, List /// Process the noconsole switch and attach or not attach the correct console loggers /// - internal static void ProcessConsoleLoggerSwitch - ( + internal static void ProcessConsoleLoggerSwitch( bool noConsoleLogger, string[] consoleLoggerParameters, List distributedLoggerRecords, LoggerVerbosity verbosity, int cpuCount, - List loggers - ) + List loggers) { // the console logger is always active, unless specifically disabled if (!noConsoleLogger) @@ -3426,19 +3404,16 @@ private static bool DoesEnvironmentSupportFancyLogger() if (Console.IsOutputRedirected) { messagesToLogInBuildLoggers.Add( - new BuildManager.DeferredBuildMessage("FancyLogger was not used because the output is being redirected to a file.", MessageImportance.Low) - ); + new BuildManager.DeferredBuildMessage("FancyLogger was not used because the output is being redirected to a file.", MessageImportance.Low)); return false; } // If terminal is dumb if ( (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.GetEnvironmentVariable("WT_SESSION") == "") - || Environment.GetEnvironmentVariable("TERM") == "dumb" - ) + || Environment.GetEnvironmentVariable("TERM") == "dumb") { messagesToLogInBuildLoggers.Add( - new BuildManager.DeferredBuildMessage("FancyLogger was not used because the output is not supported.", MessageImportance.Low) - ); + new BuildManager.DeferredBuildMessage("FancyLogger was not used because the output is not supported.", MessageImportance.Low)); return false; } return true; @@ -3446,8 +3421,7 @@ private static bool DoesEnvironmentSupportFancyLogger() private static void ProcessFancyLogger( bool noConsoleLogger, - List loggers - ) + List loggers) { // Check for flags and env variables if (!noConsoleLogger) @@ -3492,14 +3466,12 @@ private static DistributedLoggerRecord CreateForwardingLoggerRecord(ILogger logg /// /// Process the file logger switches and attach the correct file loggers. Internal for testing /// - internal static void ProcessDistributedFileLogger - ( + internal static void ProcessDistributedFileLogger( bool distributedFileLogger, string[] fileLoggerParameters, List distributedLoggerRecords, List loggers, - int cpuCount - ) + int cpuCount) { if (distributedFileLogger) { @@ -3798,13 +3770,11 @@ private static LoggerDescription ParseLoggingParameter(string parameter, string /// Loads a logger from its assembly, instantiates it, and handles errors. /// /// Instantiated logger. - private static bool CreateAndConfigureLogger - ( + private static bool CreateAndConfigureLogger( LoggerDescription loggerDescription, LoggerVerbosity verbosity, string unquotedParameter, - out ILogger logger - ) + out ILogger logger) { logger = null; @@ -3869,8 +3839,7 @@ out ILogger logger return true; } - private static void ReplayBinaryLog - ( + private static void ReplayBinaryLog( string binaryLogFilePath, ILogger[] loggers, IEnumerable distributedLoggerRecords, @@ -3963,12 +3932,10 @@ private static void ThrowInvalidToolsVersionInitializationException(IEnumerable< toolsVersionList = toolsVersionList.Substring(0, toolsVersionList.Length - 2); } - string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword - ( + string message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword( "UnrecognizedToolsVersion", toolsVersion, - toolsVersionList - ); + toolsVersionList); message = ResourceUtilities.FormatResourceStringStripCodeAndKeyword("InvalidToolsVersionError", message); InitializationException.Throw(message, toolsVersion); diff --git a/src/MSBuildTaskHost/AssemblyInfo.cs b/src/MSBuildTaskHost/AssemblyInfo.cs index 32460f62989..191d7a3e309 100644 --- a/src/MSBuildTaskHost/AssemblyInfo.cs +++ b/src/MSBuildTaskHost/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/MSBuildTaskHost/AssemblyResources.cs b/src/MSBuildTaskHost/AssemblyResources.cs index a43269ecd9c..d03e3abe886 100644 --- a/src/MSBuildTaskHost/AssemblyResources.cs +++ b/src/MSBuildTaskHost/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/MSBuildTaskHost/Concurrent/ConcurrentDictionary.cs b/src/MSBuildTaskHost/Concurrent/ConcurrentDictionary.cs index a27b5f6dbba..7a334f623b8 100644 --- a/src/MSBuildTaskHost/Concurrent/ConcurrentDictionary.cs +++ b/src/MSBuildTaskHost/Concurrent/ConcurrentDictionary.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Diagnostics; using System.Threading; @@ -170,7 +173,9 @@ private bool TryAddInternal(TKey key, int hashcode, TValue value, bool updateIfE try { if (acquireLock) + { lockTaken = Monitor.TryEnter(tables._locks[lockNo]); + } // If the table just got resized, we may not be holding the right lock, and must retry. // This should be a rare occurrence. @@ -238,7 +243,9 @@ private bool TryAddInternal(TKey key, int hashcode, TValue value, bool updateIfE finally { if (lockTaken) + { Monitor.Exit(tables._locks[lockNo]); + } } // @@ -281,8 +288,15 @@ private static void ThrowKeyNullException() /// if the key was not in the dictionary. public TValue GetOrAdd(TKey key, Func valueFactory) { - if (key == null) ThrowKeyNullException(); - if (valueFactory == null) throw new ArgumentNullException(nameof(valueFactory)); + if (key == null) + { + ThrowKeyNullException(); + } + + if (valueFactory == null) + { + throw new ArgumentNullException(nameof(valueFactory)); + } int hashcode = _comparer.GetHashCode(key); diff --git a/src/MSBuildTaskHost/Concurrent/ConcurrentQueue.cs b/src/MSBuildTaskHost/Concurrent/ConcurrentQueue.cs index ef6cca48ce1..44c553bef6c 100644 --- a/src/MSBuildTaskHost/Concurrent/ConcurrentQueue.cs +++ b/src/MSBuildTaskHost/Concurrent/ConcurrentQueue.cs @@ -1,4 +1,7 @@ -using System; +// 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.Diagnostics; using System.Runtime.InteropServices; using System.Threading; @@ -48,7 +51,7 @@ internal class ConcurrentQueue /// The current head segment. private volatile Segment _head; - static internal object VolatileReader(ref object o) => Thread.VolatileRead(ref o); + internal static object VolatileReader(ref object o) => Thread.VolatileRead(ref o); /// /// Initializes a new instance of the class. /// diff --git a/src/MSBuildTaskHost/FileSystem/MSBuildTaskHostFileSystem.cs b/src/MSBuildTaskHost/FileSystem/MSBuildTaskHostFileSystem.cs index 18a19d1c85f..46cb997dc51 100644 --- a/src/MSBuildTaskHost/FileSystem/MSBuildTaskHostFileSystem.cs +++ b/src/MSBuildTaskHost/FileSystem/MSBuildTaskHostFileSystem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/MSBuildTaskHost/Immutable/ImmutableDictionary.cs b/src/MSBuildTaskHost/Immutable/ImmutableDictionary.cs index f3eb19e6dc1..025bb7c5536 100644 --- a/src/MSBuildTaskHost/Immutable/ImmutableDictionary.cs +++ b/src/MSBuildTaskHost/Immutable/ImmutableDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; @@ -8,15 +8,15 @@ namespace System.Collections.Immutable { - static class ImmutableExtensions + internal static class ImmutableExtensions { - public static ImmutableDictionary ToImmutableDictionary(this IDictionary dictionary) + public static ImmutableDictionary ToImmutableDictionary(this IDictionary dictionary) { return new ImmutableDictionary(dictionary); } } - static class ImmutableDictionary + internal static class ImmutableDictionary { internal static ImmutableDictionary Create(IEqualityComparer comparer) { @@ -29,7 +29,7 @@ internal static ImmutableDictionary Create(IEqualityComparer comp /// /// /// - sealed class ImmutableDictionary : IDictionary, IDictionary + internal sealed class ImmutableDictionary : IDictionary, IDictionary { /// /// The underlying dictionary. diff --git a/src/MSBuildTaskHost/OutOfProcTaskAppDomainWrapper.cs b/src/MSBuildTaskHost/OutOfProcTaskAppDomainWrapper.cs index 9cc9e2b7796..442522f743b 100644 --- a/src/MSBuildTaskHost/OutOfProcTaskAppDomainWrapper.cs +++ b/src/MSBuildTaskHost/OutOfProcTaskAppDomainWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/MSBuildTaskHost/OutOfProcTaskHost.cs b/src/MSBuildTaskHost/OutOfProcTaskHost.cs index 4f4b2ab02da..0998734f9ce 100644 --- a/src/MSBuildTaskHost/OutOfProcTaskHost.cs +++ b/src/MSBuildTaskHost/OutOfProcTaskHost.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/MSBuildTaskHost/Properties/AssemblyInfo.cs b/src/MSBuildTaskHost/Properties/AssemblyInfo.cs index 7b572bc6037..2e74dfc6607 100644 --- a/src/MSBuildTaskHost/Properties/AssemblyInfo.cs +++ b/src/MSBuildTaskHost/Properties/AssemblyInfo.cs @@ -1,4 +1,7 @@ -using System; +// 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.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM diff --git a/src/MSBuildTaskHost/TypeLoader.cs b/src/MSBuildTaskHost/TypeLoader.cs index 4c3df1e1d14..08ab44925ed 100644 --- a/src/MSBuildTaskHost/TypeLoader.cs +++ b/src/MSBuildTaskHost/TypeLoader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -129,12 +129,10 @@ internal static bool IsPartialTypeNameMatch(string typeName1, string typeName2) /// found will be returned. /// The unusued bool is to match the signature of the Shared copy of TypeLoader. /// - internal LoadedType Load - ( + internal LoadedType Load( string typeName, AssemblyLoadInfo assembly, - bool _ - ) + bool _) { return GetLoadedType(s_cacheOfLoadedTypesByFilter, typeName, assembly); } @@ -145,11 +143,9 @@ bool _ /// found will be returned. /// /// The loaded type, or null if the type was not found. - internal LoadedType ReflectionOnlyLoad - ( + internal LoadedType ReflectionOnlyLoad( string typeName, - AssemblyLoadInfo assembly - ) + AssemblyLoadInfo assembly) { return GetLoadedType(s_cacheOfReflectionOnlyLoadedTypesByFilter, typeName, assembly); } diff --git a/src/Package/Microsoft.Build.UnGAC/NativeMethods.cs b/src/Package/Microsoft.Build.UnGAC/NativeMethods.cs index 1272101e50c..e549aefaec4 100644 --- a/src/Package/Microsoft.Build.UnGAC/NativeMethods.cs +++ b/src/Package/Microsoft.Build.UnGAC/NativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Package/Microsoft.Build.UnGAC/Program.cs b/src/Package/Microsoft.Build.UnGAC/Program.cs index 3515f1781a2..fb850b26700 100644 --- a/src/Package/Microsoft.Build.UnGAC/Program.cs +++ b/src/Package/Microsoft.Build.UnGAC/Program.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -13,9 +13,9 @@ namespace Microsoft.Build.UnGAC /// It runs at VS install-time as well as repair-time. /// It is intended to run as best effort. Meaning that if it fails, we avoid throwing and instead log it. /// - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { try { diff --git a/src/Samples/Dependency/Alpha.cs b/src/Samples/Dependency/Alpha.cs index 409caee5360..2c732570756 100644 --- a/src/Samples/Dependency/Alpha.cs +++ b/src/Samples/Dependency/Alpha.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Samples/Dependency/Properties/AssemblyInfo.cs b/src/Samples/Dependency/Properties/AssemblyInfo.cs index 1b7d6870cf6..4219e2cae88 100644 --- a/src/Samples/Dependency/Properties/AssemblyInfo.cs +++ b/src/Samples/Dependency/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/Samples/PortableTask/Properties/AssemblyInfo.cs b/src/Samples/PortableTask/Properties/AssemblyInfo.cs index acc604b168d..098449693bb 100644 --- a/src/Samples/PortableTask/Properties/AssemblyInfo.cs +++ b/src/Samples/PortableTask/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/Samples/PortableTask/ShowItems.cs b/src/Samples/PortableTask/ShowItems.cs index 10e53fa21fa..15937c7a645 100644 --- a/src/Samples/PortableTask/ShowItems.cs +++ b/src/Samples/PortableTask/ShowItems.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using System.Reflection; diff --git a/src/Samples/PortableTask/Sleep.cs b/src/Samples/PortableTask/Sleep.cs index ea11d4d1685..e5021e2851b 100644 --- a/src/Samples/PortableTask/Sleep.cs +++ b/src/Samples/PortableTask/Sleep.cs @@ -1,4 +1,7 @@ -using System; +// 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.Threading.Tasks; #nullable disable diff --git a/src/Samples/ProjectCachePlugin/AssemblyMockCache.cs b/src/Samples/ProjectCachePlugin/AssemblyMockCache.cs index 4d9b3f345b1..fb90a830653 100644 --- a/src/Samples/ProjectCachePlugin/AssemblyMockCache.cs +++ b/src/Samples/ProjectCachePlugin/AssemblyMockCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Linq; diff --git a/src/Samples/TaskUsageLogger/Properties/AssemblyInfo.cs b/src/Samples/TaskUsageLogger/Properties/AssemblyInfo.cs index fd24e6b516b..c4f85f1ed07 100644 --- a/src/Samples/TaskUsageLogger/Properties/AssemblyInfo.cs +++ b/src/Samples/TaskUsageLogger/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Runtime.InteropServices; diff --git a/src/Samples/TaskUsageLogger/TaskUsageLogger.cs b/src/Samples/TaskUsageLogger/TaskUsageLogger.cs index 001357401f6..207ed556262 100644 --- a/src/Samples/TaskUsageLogger/TaskUsageLogger.cs +++ b/src/Samples/TaskUsageLogger/TaskUsageLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Samples/TaskWithDependency/LogStringFromDependency.cs b/src/Samples/TaskWithDependency/LogStringFromDependency.cs index 8bd5ab1b1e4..d0de0410ded 100644 --- a/src/Samples/TaskWithDependency/LogStringFromDependency.cs +++ b/src/Samples/TaskWithDependency/LogStringFromDependency.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Dependency; diff --git a/src/Samples/TaskWithDependency/Properties/AssemblyInfo.cs b/src/Samples/TaskWithDependency/Properties/AssemblyInfo.cs index 518b51cd063..ac44e52b0c3 100644 --- a/src/Samples/TaskWithDependency/Properties/AssemblyInfo.cs +++ b/src/Samples/TaskWithDependency/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/Samples/XmlFileLogger/ILogNode.cs b/src/Samples/XmlFileLogger/ILogNode.cs index bedae997a3f..daaf93c1d9f 100644 --- a/src/Samples/XmlFileLogger/ILogNode.cs +++ b/src/Samples/XmlFileLogger/ILogNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml.Linq; diff --git a/src/Samples/XmlFileLogger/ItemGroupParser.cs b/src/Samples/XmlFileLogger/ItemGroupParser.cs index c17ab8bfac4..5dbd98cd92a 100644 --- a/src/Samples/XmlFileLogger/ItemGroupParser.cs +++ b/src/Samples/XmlFileLogger/ItemGroupParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Samples/XmlFileLogger/LogProcessNode.cs b/src/Samples/XmlFileLogger/LogProcessNode.cs index 086c98a1534..b561addd604 100644 --- a/src/Samples/XmlFileLogger/LogProcessNode.cs +++ b/src/Samples/XmlFileLogger/LogProcessNode.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Samples/XmlFileLogger/ObjectModel/Build.cs b/src/Samples/XmlFileLogger/ObjectModel/Build.cs index 80b274e93c4..5bcdc8135ce 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/Build.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/Build.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Samples/XmlFileLogger/ObjectModel/InputParameter.cs b/src/Samples/XmlFileLogger/ObjectModel/InputParameter.cs index 6787d9381c8..354fea86729 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/InputParameter.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/InputParameter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Samples/XmlFileLogger/ObjectModel/Item.cs b/src/Samples/XmlFileLogger/ObjectModel/Item.cs index 2a8620187c3..c25ca8c5eea 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/Item.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/Item.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Samples/XmlFileLogger/ObjectModel/ItemGroup.cs b/src/Samples/XmlFileLogger/ObjectModel/ItemGroup.cs index 568c56e3635..0d5150ec47c 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/ItemGroup.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/ItemGroup.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Samples/XmlFileLogger/ObjectModel/Message.cs b/src/Samples/XmlFileLogger/ObjectModel/Message.cs index b893987b08c..378708d8ca9 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/Message.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/Message.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml.Linq; diff --git a/src/Samples/XmlFileLogger/ObjectModel/OutputItem.cs b/src/Samples/XmlFileLogger/ObjectModel/OutputItem.cs index 159226a674f..5f51bf46ef8 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/OutputItem.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/OutputItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Samples/XmlFileLogger/ObjectModel/OutputProperty.cs b/src/Samples/XmlFileLogger/ObjectModel/OutputProperty.cs index 0654cd4b583..3792dedb95e 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/OutputProperty.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/OutputProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Samples/XmlFileLogger/ObjectModel/Project.cs b/src/Samples/XmlFileLogger/ObjectModel/Project.cs index 1ce36edaf9a..8fcee5fe6d7 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/Project.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/Project.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -153,7 +153,7 @@ public override string ToString() /// Target node private Target GetOrAddTargetByName(string targetName, TargetStartedEventArgs e = null) { - Target result = _targetNameToTargetMap.GetOrAdd(targetName, key=> new Target(key, e)); + Target result = _targetNameToTargetMap.GetOrAdd(targetName, key => new Target(key, e)); if (e != null) { diff --git a/src/Samples/XmlFileLogger/ObjectModel/Target.cs b/src/Samples/XmlFileLogger/ObjectModel/Target.cs index a92d2013f16..41d4a4a1d33 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/Target.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/Target.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using System.Xml.Linq; diff --git a/src/Samples/XmlFileLogger/ObjectModel/Task.cs b/src/Samples/XmlFileLogger/ObjectModel/Task.cs index 3d276a28cb8..dcc6982c577 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/Task.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/Task.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml.Linq; using Microsoft.Build.Framework; diff --git a/src/Samples/XmlFileLogger/ObjectModel/TaskParameter.cs b/src/Samples/XmlFileLogger/ObjectModel/TaskParameter.cs index 464d10c5d19..1ae3ed59aec 100644 --- a/src/Samples/XmlFileLogger/ObjectModel/TaskParameter.cs +++ b/src/Samples/XmlFileLogger/ObjectModel/TaskParameter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; diff --git a/src/Samples/XmlFileLogger/Properties/AssemblyInfo.cs b/src/Samples/XmlFileLogger/Properties/AssemblyInfo.cs index 051d53af8b3..72ac1de6314 100644 --- a/src/Samples/XmlFileLogger/Properties/AssemblyInfo.cs +++ b/src/Samples/XmlFileLogger/Properties/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Runtime.InteropServices; diff --git a/src/Samples/XmlFileLogger/PropertyBag.cs b/src/Samples/XmlFileLogger/PropertyBag.cs index 9f5b6f00fde..d702f1edd11 100644 --- a/src/Samples/XmlFileLogger/PropertyBag.cs +++ b/src/Samples/XmlFileLogger/PropertyBag.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Samples/XmlFileLogger/UnknownTaskParameterPrefixException.cs b/src/Samples/XmlFileLogger/UnknownTaskParameterPrefixException.cs index b2aec3d718a..a5569056a82 100644 --- a/src/Samples/XmlFileLogger/UnknownTaskParameterPrefixException.cs +++ b/src/Samples/XmlFileLogger/UnknownTaskParameterPrefixException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Samples/XmlFileLogger/XmlFileLogger.cs b/src/Samples/XmlFileLogger/XmlFileLogger.cs index e5ab9109723..408f8938ff3 100644 --- a/src/Samples/XmlFileLogger/XmlFileLogger.cs +++ b/src/Samples/XmlFileLogger/XmlFileLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text.RegularExpressions; @@ -42,16 +42,16 @@ public class XmlFileLogger : Logger public override void Initialize(IEventSource eventSource) { ProcessParameters(); - - eventSource.BuildStarted += (s, args) => _build = new Build(args); - eventSource.BuildFinished += (o, args) => _build.CompleteBuild(args, _logFile, _errors, _warings); - eventSource.ProjectStarted += (o, args) => TryProcessEvent(() => _build.AddProject(args)); + eventSource.BuildStarted += (s, args) => _build = new Build(args); + eventSource.BuildFinished += (o, args) => _build.CompleteBuild(args, _logFile, _errors, _warings); + + eventSource.ProjectStarted += (o, args) => TryProcessEvent(() => _build.AddProject(args)); eventSource.ProjectFinished += (o, args) => TryProcessEvent(() => _build.CompleteProject(args)); - eventSource.TargetStarted += (o, args) => TryProcessEvent(() => _build.AddTarget(args)); - eventSource.TargetFinished += (o, args) => TryProcessEvent(() => _build.CompleteTarget(args)); - eventSource.TaskStarted += (o, args) => TryProcessEvent(() => _build.AddTask(args)); - eventSource.TaskFinished += (o, args) => TryProcessEvent(() => _build.CompleteTask(args)); + eventSource.TargetStarted += (o, args) => TryProcessEvent(() => _build.AddTarget(args)); + eventSource.TargetFinished += (o, args) => TryProcessEvent(() => _build.CompleteTarget(args)); + eventSource.TaskStarted += (o, args) => TryProcessEvent(() => _build.AddTask(args)); + eventSource.TaskFinished += (o, args) => TryProcessEvent(() => _build.CompleteTask(args)); eventSource.TaskFinished += (o, args) => TryProcessEvent(() => _build.CompleteTask(args)); diff --git a/src/Shared/AssemblyFolders/AssemblyFoldersEx.cs b/src/Shared/AssemblyFolders/AssemblyFoldersEx.cs index 6df2b6a307f..11e6f4bef30 100644 --- a/src/Shared/AssemblyFolders/AssemblyFoldersEx.cs +++ b/src/Shared/AssemblyFolders/AssemblyFoldersEx.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -65,8 +65,7 @@ internal class AssemblyFoldersEx : IEnumerable /// Used to find registry key default values. /// Architecture to seek. /// Key object to open. - internal AssemblyFoldersEx - ( + internal AssemblyFoldersEx( string registryKeyRoot, string targetRuntimeVersion, string registryKeySuffix, @@ -75,8 +74,7 @@ internal AssemblyFoldersEx GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, ProcessorArchitecture targetProcessorArchitecture, - OpenBaseKey openBaseKey - ) + OpenBaseKey openBaseKey) { // No extensions are supported, except on Windows if (!NativeMethodsShared.IsWindows) @@ -139,8 +137,7 @@ OpenBaseKey openBaseKey /// Used to find registry subkey names. /// Used to find registry key default values. /// Key object to open. - private void FindDirectories - ( + private void FindDirectories( RegistryView view, RegistryHive hive, string registryKeyRoot, @@ -150,8 +147,7 @@ private void FindDirectories string platform, GetRegistrySubKeyNames getRegistrySubKeyNames, GetRegistrySubKeyDefaultValue getRegistrySubKeyDefaultValue, - OpenBaseKey openBaseKey - ) + OpenBaseKey openBaseKey) { // Open the hive for a given view using (RegistryKey baseKey = openBaseKey(hive, view)) diff --git a/src/Shared/AssemblyFolders/AssemblyFoldersFromConfig.cs b/src/Shared/AssemblyFolders/AssemblyFoldersFromConfig.cs index bb50bfa5800..b9e55b44190 100644 --- a/src/Shared/AssemblyFolders/AssemblyFoldersFromConfig.cs +++ b/src/Shared/AssemblyFolders/AssemblyFoldersFromConfig.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -31,7 +31,7 @@ internal AssemblyFoldersFromConfig(string configFile, string targetRuntimeVersio { ErrorUtilities.VerifyThrowArgumentNull(configFile, nameof(configFile)); ErrorUtilities.VerifyThrowArgumentNull(targetRuntimeVersion, nameof(targetRuntimeVersion)); - + var collection = AssemblyFolderCollection.Load(configFile); var assemblyTargets = GatherVersionStrings(targetRuntimeVersion, collection); @@ -76,12 +76,12 @@ private void FindDirectories(List assemblyTargets, Func GatherVersionStrings(string targetRuntimeVersion, AssemblyFolderCollection collection) { - return + return (from folder in collection.AssemblyFolders let targetVersion = VersionUtilities.ConvertToVersion(targetRuntimeVersion) let replacementVersion = GetFrameworkVersion(folder.FrameworkVersion) where targetVersion != null && targetVersion >= replacementVersion - orderby folder.FrameworkVersion descending + orderby folder.FrameworkVersion descending select folder).ToList(); } diff --git a/src/Shared/AssemblyFolders/Serialization/AssemblyFolderCollection.cs b/src/Shared/AssemblyFolders/Serialization/AssemblyFolderCollection.cs index 30583b8abbe..1ee801c71bf 100644 --- a/src/Shared/AssemblyFolders/Serialization/AssemblyFolderCollection.cs +++ b/src/Shared/AssemblyFolders/Serialization/AssemblyFolderCollection.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Xml; diff --git a/src/Shared/AssemblyFolders/Serialization/AssemblyFolderItem.cs b/src/Shared/AssemblyFolders/Serialization/AssemblyFolderItem.cs index 5151c1ff447..eebc67d37c7 100644 --- a/src/Shared/AssemblyFolders/Serialization/AssemblyFolderItem.cs +++ b/src/Shared/AssemblyFolders/Serialization/AssemblyFolderItem.cs @@ -1,11 +1,14 @@ -using System.Diagnostics; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; using System.Runtime.Serialization; #nullable disable namespace Microsoft.Build.Shared.AssemblyFoldersFromConfig { - [DataContract(Name="AssemblyFolder", Namespace = "")] + [DataContract(Name = "AssemblyFolder", Namespace = "")] [DebuggerDisplay("{Name}: FrameworkVersion = {FrameworkVersion}, Platform = {Platform}, Path= {Path}")] internal class AssemblyFolderItem { diff --git a/src/Shared/AssemblyLoadInfo.cs b/src/Shared/AssemblyLoadInfo.cs index 271a077efaa..d4b3413772c 100644 --- a/src/Shared/AssemblyLoadInfo.cs +++ b/src/Shared/AssemblyLoadInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -106,7 +106,7 @@ public void Translate(ITranslator translator) translator.Translate(ref assemblyFile); } - static public AssemblyLoadInfo FactoryForTranslation(ITranslator translator) + public static AssemblyLoadInfo FactoryForTranslation(ITranslator translator) { string assemblyName = null; string assemblyFile = null; diff --git a/src/Shared/AssemblyNameComparer.cs b/src/Shared/AssemblyNameComparer.cs index 1855a039164..f9a30fab128 100644 --- a/src/Shared/AssemblyNameComparer.cs +++ b/src/Shared/AssemblyNameComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Shared/AssemblyNameExtension.cs b/src/Shared/AssemblyNameExtension.cs index a2a6120ec55..aed07dfebdd 100644 --- a/src/Shared/AssemblyNameExtension.cs +++ b/src/Shared/AssemblyNameExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -130,11 +130,11 @@ private AssemblyNameExtension(SerializationInfo info, StreamingContext context) if (hasAssemblyName) { var name = info.GetString("name"); - var publicKey = (byte[]) info.GetValue("pk", typeof(byte[])); - var publicKeyToken = (byte[]) info.GetValue("pkt", typeof(byte[])); + var publicKey = (byte[])info.GetValue("pk", typeof(byte[])); + var publicKeyToken = (byte[])info.GetValue("pkt", typeof(byte[])); var version = (Version)info.GetValue("ver", typeof(Version)); - var flags = (AssemblyNameFlags) info.GetInt32("flags"); - var processorArchitecture = (ProcessorArchitecture) info.GetInt32("cpuarch"); + var flags = (AssemblyNameFlags)info.GetInt32("flags"); + var processorArchitecture = (ProcessorArchitecture)info.GetInt32("cpuarch"); CultureInfo cultureInfo = null; var hasCultureInfo = info.GetBoolean("hasCI"); @@ -143,8 +143,8 @@ private AssemblyNameExtension(SerializationInfo info, StreamingContext context) cultureInfo = new CultureInfo(info.GetInt32("ci")); } - var hashAlgorithm = (System.Configuration.Assemblies.AssemblyHashAlgorithm) info.GetInt32("hashAlg"); - var versionCompatibility = (AssemblyVersionCompatibility) info.GetInt32("verCompat"); + var hashAlgorithm = (System.Configuration.Assemblies.AssemblyHashAlgorithm)info.GetInt32("hashAlg"); + var versionCompatibility = (AssemblyVersionCompatibility)info.GetInt32("verCompat"); var codeBase = info.GetString("codebase"); asAssemblyName = new AssemblyName @@ -167,7 +167,7 @@ private AssemblyNameExtension(SerializationInfo info, StreamingContext context) isSimpleName = info.GetBoolean("isSName"); hasProcessorArchitectureInFusionName = info.GetBoolean("hasCpuArch"); immutable = info.GetBoolean("immutable"); - remappedFrom = (HashSet) info.GetValue("remapped", typeof(HashSet)); + remappedFrom = (HashSet)info.GetValue("remapped", typeof(HashSet)); } /// @@ -952,8 +952,8 @@ public void GetObjectData(SerializationInfo info, StreamingContext context) info.AddValue("pk", asAssemblyName.GetPublicKey()); info.AddValue("pkt", asAssemblyName.GetPublicKeyToken()); info.AddValue("ver", asAssemblyName.Version); - info.AddValue("flags", (int) asAssemblyName.Flags); - info.AddValue("cpuarch", (int) asAssemblyName.ProcessorArchitecture); + info.AddValue("flags", (int)asAssemblyName.Flags); + info.AddValue("cpuarch", (int)asAssemblyName.ProcessorArchitecture); info.AddValue("hasCI", asAssemblyName.CultureInfo != null); if (asAssemblyName.CultureInfo != null) @@ -984,7 +984,7 @@ public void Translate(ITranslator translator) translator.Translate(ref isSimpleName); translator.Translate(ref hasProcessorArchitectureInFusionName); translator.Translate(ref immutable); - + // TODO: consider some kind of protection against infinite loop during serialization, hint: pre serialize check for cycle in graph translator.TranslateHashSet(ref remappedFrom, (ITranslator t) => new AssemblyNameExtension(t), diff --git a/src/Shared/AssemblyNameReverseVersionComparer.cs b/src/Shared/AssemblyNameReverseVersionComparer.cs index 6e8eb62be81..4d4ad07c589 100644 --- a/src/Shared/AssemblyNameReverseVersionComparer.cs +++ b/src/Shared/AssemblyNameReverseVersionComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; @@ -10,12 +10,12 @@ namespace Microsoft.Build.Shared /// /// Compare the version numbers only for an AssemblyNameExtension and make sure they are in reverse order. This assumes the names are the same. /// - sealed internal class AssemblyNameReverseVersionComparer : IComparer + internal sealed class AssemblyNameReverseVersionComparer : IComparer { /// /// A static instance of the comparer for use in a sort method /// - internal readonly static IComparer GenericComparer = new AssemblyNameReverseVersionComparer(); + internal static readonly IComparer GenericComparer = new AssemblyNameReverseVersionComparer(); /// /// Compare x and y by version only. diff --git a/src/Shared/AwaitExtensions.cs b/src/Shared/AwaitExtensions.cs index 3767e5f8c63..c6280524b0a 100644 --- a/src/Shared/AwaitExtensions.cs +++ b/src/Shared/AwaitExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Shared/BinaryReaderExtensions.cs b/src/Shared/BinaryReaderExtensions.cs index dbaad654b30..cd95cc40864 100644 --- a/src/Shared/BinaryReaderExtensions.cs +++ b/src/Shared/BinaryReaderExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Shared/BinaryTranslator.cs b/src/Shared/BinaryTranslator.cs index 05abbdbab95..e7bf01731cc 100644 --- a/src/Shared/BinaryTranslator.cs +++ b/src/Shared/BinaryTranslator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -20,13 +20,13 @@ namespace Microsoft.Build.BackEnd /// Each class implements a Translate method on INodePacket which takes this class /// as a parameter, and uses it to store and retrieve fields to the stream. /// - static internal class BinaryTranslator + internal static class BinaryTranslator { /// /// Returns a read-only serializer. /// /// The serializer. - static internal ITranslator GetReadTranslator(Stream stream, SharedReadBuffer buffer) + internal static ITranslator GetReadTranslator(Stream stream, SharedReadBuffer buffer) { return new BinaryReadTranslator(stream, buffer); } @@ -36,7 +36,7 @@ static internal ITranslator GetReadTranslator(Stream stream, SharedReadBuffer bu /// /// The stream containing data to serialize. /// The serializer. - static internal ITranslator GetWriteTranslator(Stream stream) + internal static ITranslator GetWriteTranslator(Stream stream) { return new BinaryWriteTranslator(stream); } @@ -229,7 +229,7 @@ public void Translate(ref byte[] byteArray) /// /// The array to be translated. /// The length of array which will be used in translation. This parameter is not used when reading - public void Translate(ref byte[] byteArray, ref int length) + public void Translate(ref byte[] byteArray, ref int length) { Translate(ref byteArray); length = byteArray.Length; @@ -302,7 +302,7 @@ public void Translate(ref List list, ObjectTranslator objectTranslator) { IList listAsInterface = list; Translate(ref listAsInterface, objectTranslator, count => new List(count)); - list = (List) listAsInterface; + list = (List)listAsInterface; } public void Translate(ref IList list, ObjectTranslator objectTranslator, NodePacketCollectionCreator collectionFactory) where L : IList @@ -387,16 +387,14 @@ public void Translate(ref TimeSpan value) /// The context to be translated. public void Translate(ref BuildEventContext value) { - value = new BuildEventContext - ( + value = new BuildEventContext( _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), _reader.ReadInt32(), - _reader.ReadInt32() - ); + _reader.ReadInt32()); } #endif @@ -558,7 +556,7 @@ public void TranslateDictionary(ref Dictionary dictionary, IEqua ref copy, count => new Dictionary(count, comparer)); - dictionary = (Dictionary) copy; + dictionary = (Dictionary)copy; } public void TranslateDictionary(ref IDictionary dictionary, NodePacketCollectionCreator> dictionaryCreator) @@ -711,12 +709,12 @@ public void TranslateDictionary(ref Dictionary dictionary, Str } } - /// - /// Reads in the boolean which says if this object is null or not. - /// - /// The type of object to test. - /// True if the object should be read, false otherwise. - public bool TranslateNullable(T value) + /// + /// Reads in the boolean which says if this object is null or not. + /// + /// The type of object to test. + /// True if the object should be read, false otherwise. + public bool TranslateNullable(T value) { bool haveRef = _reader.ReadBoolean(); return haveRef; @@ -1136,7 +1134,7 @@ public void Translate(ref byte[] byteArray) /// /// The array to be translated. /// The length of array which will be used in translation - public void Translate(ref byte[] byteArray, ref int length) + public void Translate(ref byte[] byteArray, ref int length) { if (!TranslateNullable(byteArray)) { diff --git a/src/Shared/BinaryWriterExtensions.cs b/src/Shared/BinaryWriterExtensions.cs index ffc019dacba..41636982688 100644 --- a/src/Shared/BinaryWriterExtensions.cs +++ b/src/Shared/BinaryWriterExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Shared/BufferedReadStream.cs b/src/Shared/BufferedReadStream.cs index 6aaf31e792b..783a9dde80f 100644 --- a/src/Shared/BufferedReadStream.cs +++ b/src/Shared/BufferedReadStream.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -10,15 +10,13 @@ namespace Microsoft.Build.BackEnd { internal class BufferedReadStream : Stream { - const int BUFFER_SIZE = 1024; - - Stream _innerStream; - byte[] _buffer; + private const int BUFFER_SIZE = 1024; + private Stream _innerStream; + private byte[] _buffer; // The number of bytes in the buffer that have been read from the underlying stream but not read by consumers of this stream - int _currentlyBufferedByteCount; - - int _currentIndexInBuffer; + private int _currentlyBufferedByteCount; + private int _currentIndexInBuffer; public BufferedReadStream(Stream innerStream) { diff --git a/src/Shared/BuildEnvironmentHelper.cs b/src/Shared/BuildEnvironmentHelper.cs index e67cbcbd153..493ab1758b5 100644 --- a/src/Shared/BuildEnvironmentHelper.cs +++ b/src/Shared/BuildEnvironmentHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -28,12 +28,12 @@ internal class BuildEnvironmentHelper /// Name of the Visual Studio (and Blend) process. /// VS ASP intellisense server fails without Microsoft.VisualStudio.Web.Host. Remove when issue fixed: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/574986 /// - private static readonly string[] s_visualStudioProcess = {"DEVENV", "BLEND", "Microsoft.VisualStudio.Web.Host"}; + private static readonly string[] s_visualStudioProcess = { "DEVENV", "BLEND", "Microsoft.VisualStudio.Web.Host" }; /// /// Name of the MSBuild process(es) /// - private static readonly string[] s_msBuildProcess = {"MSBUILD", "MSBUILDTASKHOST"}; + private static readonly string[] s_msBuildProcess = { "MSBUILD", "MSBUILDTASKHOST" }; /// /// Name of MSBuild executable files. @@ -93,7 +93,9 @@ private static BuildEnvironment Initialize() { var env = location(); if (env != null) + { return env; + } } // If we can't find a suitable environment, continue in the 'None' mode. If not running tests, @@ -135,10 +137,15 @@ private static BuildEnvironment TryFromEnvironmentVariable() private static BuildEnvironment TryFromVisualStudioProcess() { if (!NativeMethodsShared.IsWindows) + { return null; + } var vsProcess = s_getProcessFromRunningProcess(); - if (!IsProcessInList(vsProcess, s_visualStudioProcess)) return null; + if (!IsProcessInList(vsProcess, s_visualStudioProcess)) + { + return null; + } var vsRoot = FileUtilities.GetFolderAbove(vsProcess, 3); string msBuildExe = GetMSBuildExeFromVsRoot(vsRoot); @@ -154,7 +161,10 @@ private static BuildEnvironment TryFromVisualStudioProcess() private static BuildEnvironment TryFromMSBuildProcess() { var msBuildExe = s_getProcessFromRunningProcess(); - if (!IsProcessInList(msBuildExe, s_msBuildProcess)) return null; + if (!IsProcessInList(msBuildExe, s_msBuildProcess)) + { + return null; + } // First check if we're in a VS installation if (NativeMethodsShared.IsWindows && @@ -180,7 +190,10 @@ private static BuildEnvironment TryFromMSBuildProcess() private static BuildEnvironment TryFromMSBuildAssembly() { var buildAssembly = s_getExecutingAssemblyPath(); - if (buildAssembly == null) return null; + if (buildAssembly == null) + { + return null; + } // Check for MSBuild.[exe|dll] next to the current assembly var msBuildExe = Path.Combine(FileUtilities.GetFolderAbove(buildAssembly), "MSBuild.exe"); @@ -195,8 +208,14 @@ private static BuildEnvironment TryFromMSBuildAssembly() // We're not in VS, check for MSBuild.exe / dll to consider this a standalone environment. string msBuildPath = null; - if (FileSystems.Default.FileExists(msBuildExe)) msBuildPath = msBuildExe; - else if (FileSystems.Default.FileExists(msBuildDll)) msBuildPath = msBuildDll; + if (FileSystems.Default.FileExists(msBuildExe)) + { + msBuildPath = msBuildExe; + } + else if (FileSystems.Default.FileExists(msBuildDll)) + { + msBuildPath = msBuildDll; + } if (!string.IsNullOrEmpty(msBuildPath)) { @@ -247,7 +266,10 @@ private static BuildEnvironment TryFromDevConsole() var vsVersion = s_getEnvironmentVariable("VisualStudioVersion"); if (string.IsNullOrEmpty(vsInstallDir) || string.IsNullOrEmpty(vsVersion) || - vsVersion != CurrentVisualStudioVersion || !FileSystems.Default.DirectoryExists(vsInstallDir)) return null; + vsVersion != CurrentVisualStudioVersion || !FileSystems.Default.DirectoryExists(vsInstallDir)) + { + return null; + } return new BuildEnvironment( BuildEnvironmentMode.VisualStudio, @@ -271,7 +293,10 @@ private static BuildEnvironment TryFromSetupApi() .Where(i => i.Version.Major == v.Major && FileSystems.Default.DirectoryExists(i.Path)) .ToList(); - if (instances.Count == 0) return null; + if (instances.Count == 0) + { + return null; + } if (instances.Count > 1) { @@ -294,7 +319,10 @@ private static BuildEnvironment TryFromAppContextBaseDirectory() // but the toolset files are copied to the app's directory via "contentFiles". var appContextBaseDirectory = s_getAppContextBaseDirectory(); - if (string.IsNullOrEmpty(appContextBaseDirectory)) return null; + if (string.IsNullOrEmpty(appContextBaseDirectory)) + { + return null; + } // Look for possible MSBuild exe names in the AppContextBaseDirectory return s_msBuildExeNames @@ -530,7 +558,9 @@ public BuildEnvironment(BuildEnvironmentMode mode, string currentMSBuildExePath, // We can't detect an environment, don't try to set other paths. if (mode == BuildEnvironmentMode.None || currentMSBuildExeFile == null || currentToolsDirectory == null) + { return; + } var msBuildExeName = currentMSBuildExeFile.Name; diff --git a/src/Shared/BuildEventFileInfo.cs b/src/Shared/BuildEventFileInfo.cs index ab15bb7a088..33cb0d694cc 100644 --- a/src/Shared/BuildEventFileInfo.cs +++ b/src/Shared/BuildEventFileInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Shared/CanonicalError.cs b/src/Shared/CanonicalError.cs index 406784dfeab..011818c3f1c 100644 --- a/src/Shared/CanonicalError.cs +++ b/src/Shared/CanonicalError.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -53,38 +53,33 @@ internal static class CanonicalError { // Defines the main pattern for matching messages. private static readonly Lazy s_originCategoryCodeTextExpression = new Lazy( - () => new Regex - ( + () => new Regex( // Beginning of line and any amount of whitespace. @"^\s*" - // Match a [optional project number prefix 'ddd>'], single letter + colon + remaining filename, or - // string with no colon followed by a colon. + // Match a [optional project number prefix 'ddd>'], single letter + colon + remaining filename, or + // string with no colon followed by a colon. + @"(((?(((\d+>)?[a-zA-Z]?:[^:]*)|([^:]*))):)" - // Origin may also be empty. In this case there's no trailing colon. + // Origin may also be empty. In this case there's no trailing colon. + "|())" - // Match the empty string or a string without a colon that ends with a space + // Match the empty string or a string without a colon that ends with a space + "(?(()|([^:]*? )))" - // Match 'error' or 'warning'. + // Match 'error' or 'warning'. + @"(?(error|warning))" - // Match anything starting with a space that's not a colon/space, followed by a colon. - // Error code is optional in which case "error"/"warning" can be followed immediately by a colon. + // Match anything starting with a space that's not a colon/space, followed by a colon. + // Error code is optional in which case "error"/"warning" can be followed immediately by a colon. + @"( \s*(?[^: ]*))?\s*:" - // Whatever's left on this line, including colons. + // Whatever's left on this line, including colons. + "(?.*)$", - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); - private static readonly Lazy s_originCategoryCodeTextExpression2 = new Lazy( - () => new Regex - ( + private static readonly Lazy s_originCategoryCodeTextExpression2 = new Lazy( + () => new Regex( @"^\s*(?(?.*):(?(?[0-9]*):(?[0-9]*))):(? error| warning):(?.*)", - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); // Matches and extracts filename and location from an 'origin' element. private static readonly Lazy s_filenameLocationFromOrigin = new Lazy( - () => new Regex - ( + () => new Regex( "^" // Beginning of line + @"(\d+>)?" // Optional ddd> project number prefix + "(?.*)" // Match anything. @@ -92,47 +87,39 @@ internal static class CanonicalError + @"(?[\,,0-9,-]*)" // Match any combination of numbers and ',' and '-' + @"\)\s*" // Find the closing paren then any amount of spaces. + "$", // End-of-line - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); // Matches location that is a simple number. private static readonly Lazy s_lineFromLocation = new Lazy( - () => new Regex // Example: line - ( + () => new Regex( // Example: line "^" // Beginning of line + "(?[0-9]*)" // Match any number. + "$", // End-of-line - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); // Matches location that is a range of lines. private static readonly Lazy s_lineLineFromLocation = new Lazy( - () => new Regex // Example: line-line - ( + () => new Regex( // Example: line-line "^" // Beginning of line + "(?[0-9]*)" // Match any number. + "-" // Dash + "(?[0-9]*)" // Match any number. + "$", // End-of-line - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); // Matches location that is a line and column private static readonly Lazy s_lineColFromLocation = new Lazy( - () => new Regex // Example: line,col - ( + () => new Regex( // Example: line,col "^" // Beginning of line + "(?[0-9]*)" // Match any number. + "," // Comma + "(?[0-9]*)" // Match any number. + "$", // End-of-line - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); // Matches location that is a line and column-range private static readonly Lazy s_lineColColFromLocation = new Lazy( - () => new Regex // Example: line,col-col - ( + () => new Regex( // Example: line,col-col "^" // Beginning of line + "(?[0-9]*)" // Match any number. + "," // Comma @@ -140,13 +127,11 @@ internal static class CanonicalError + "-" // Dash + "(?[0-9]*)" // Match any number. + "$", // End-of-line - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); // Matches location that is line,col,line,col private static readonly Lazy s_lineColLineColFromLocation = new Lazy( - () => new Regex // Example: line,col,line,col - ( + () => new Regex( // Example: line,col,line,col "^" // Beginning of line + "(?[0-9]*)" // Match any number. + "," // Comma @@ -156,8 +141,7 @@ internal static class CanonicalError + "," // Dash + "(?[0-9]*)" // Match any number. + "$", // End-of-line - RegexOptions.IgnoreCase | RegexOptions.Compiled - )); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); /// /// Represents the parts of a decomposed canonical message. diff --git a/src/Shared/CollectionHelpers.cs b/src/Shared/CollectionHelpers.cs index 18d052ed39e..e88ef106fc6 100644 --- a/src/Shared/CollectionHelpers.cs +++ b/src/Shared/CollectionHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/CommunicationsUtilities.cs b/src/Shared/CommunicationsUtilities.cs index e21e214cb78..fa13e50f7d1 100644 --- a/src/Shared/CommunicationsUtilities.cs +++ b/src/Shared/CommunicationsUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -89,7 +89,7 @@ internal class Handshake protected readonly int fileVersionPrivate; private readonly int sessionId; - internal protected Handshake(HandshakeOptions nodeType) + protected internal Handshake(HandshakeOptions nodeType) { const int handshakeVersion = (int)CommunicationsUtilities.handshakeVersion; @@ -190,7 +190,7 @@ public string ComputeHash() /// /// This class contains utility methods for the MSBuild engine. /// - static internal class CommunicationsUtilities + internal static class CommunicationsUtilities { /// /// Indicates to the NodeEndpoint that all the various parts of the Handshake have been sent. @@ -235,7 +235,7 @@ static internal class CommunicationsUtilities /// /// Gets or sets the node connection timeout. /// - static internal int NodeConnectionTimeout + internal static int NodeConnectionTimeout { get { return GetIntegerVariableOrDefault("MSBUILDNODECONNECTIONTIMEOUT", DefaultNodeConnectionTimeout); } } @@ -244,13 +244,13 @@ static internal int NodeConnectionTimeout /// Get environment block /// [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static unsafe extern char* GetEnvironmentStrings(); + internal static extern unsafe char* GetEnvironmentStrings(); /// /// Free environment block /// [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings); + internal static extern unsafe bool FreeEnvironmentStrings(char* pStrings); /// /// Copied from the BCL implementation to eliminate some expensive security asserts. @@ -363,7 +363,7 @@ internal static Dictionary GetEnvironmentVariables() var vars = Environment.GetEnvironmentVariables(); foreach (var key in vars.Keys) { - table[(string) key] = (string) vars[key]; + table[(string)key] = (string)vars[key]; } } @@ -422,18 +422,25 @@ internal static void WriteIntForHandshake(this PipeStream stream, int value) stream.Write(bytes, 0, bytes.Length); } - internal static void ReadEndOfHandshakeSignal(this PipeStream stream, bool isProvider +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + internal static void ReadEndOfHandshakeSignal( + this PipeStream stream, + bool isProvider #if NETCOREAPP2_1_OR_GREATER || MONO , int timeout #endif ) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { // Accept only the first byte of the EndOfHandshakeSignal - int valueRead = stream.ReadIntForHandshake(null +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + int valueRead = stream.ReadIntForHandshake( + byteToAccept: null #if NETCOREAPP2_1_OR_GREATER || MONO , timeout #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter if (valueRead != EndOfHandshakeSignal) { @@ -449,6 +456,7 @@ internal static void ReadEndOfHandshakeSignal(this PipeStream stream, bool isPro } } +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter /// /// Extension method to read a series of bytes from a stream. /// If specified, leading byte matches one in the supplied array if any, returns rejection byte and throws IOException. @@ -458,6 +466,7 @@ internal static int ReadIntForHandshake(this PipeStream stream, byte? byteToAcce , int timeout #endif ) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { byte[] bytes = new byte[4]; @@ -608,7 +617,7 @@ internal static HandshakeOptions GetHandshakeOptions(bool taskHost, string archi switch (clrVersion) { case 0: - // Not a taskhost, runtime must match + // Not a taskhost, runtime must match case 4: // Default for MSBuild running on .NET Framework 4, // not represented in handshake diff --git a/src/Shared/Constants.cs b/src/Shared/Constants.cs index 4a59448c172..76d42a328f6 100644 --- a/src/Shared/Constants.cs +++ b/src/Shared/Constants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -78,7 +78,7 @@ internal static class MSBuildConstants /// Current version of this MSBuild Engine assembly in the form, e.g, "12.0" /// internal const string CurrentProductVersion = "17.0"; - + /// /// Symbol used in ProjectReferenceTarget items to represent default targets /// @@ -99,7 +99,7 @@ internal static class MSBuildConstants /// with fallback to default targets if the ProjectReference item has no targets specified. /// internal const string ProjectReferenceTargetsOrDefaultTargetsMarker = ".projectReferenceTargetsOrDefaultTargets"; - + // One-time allocations to avoid implicit allocations for Split(), Trim(). internal static readonly char[] SemicolonChar = { ';' }; internal static readonly char[] SpaceChar = { ' ' }; diff --git a/src/Shared/ConversionUtilities.cs b/src/Shared/ConversionUtilities.cs index af794b51281..73d009c2f01 100644 --- a/src/Shared/ConversionUtilities.cs +++ b/src/Shared/ConversionUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Shared/CopyOnWriteDictionary.cs b/src/Shared/CopyOnWriteDictionary.cs index ec869150afb..b48401b964f 100644 --- a/src/Shared/CopyOnWriteDictionary.cs +++ b/src/Shared/CopyOnWriteDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -34,14 +34,14 @@ internal class CopyOnWriteDictionary : IDictionary, IDictionary, I /// used as the basis of new dictionaries with that comparer to avoid /// allocating new comparers objects. /// - private readonly static ImmutableDictionary NameComparerDictionaryPrototype = ImmutableDictionary.Create(MSBuildNameIgnoreCaseComparer.Default); + private static readonly ImmutableDictionary NameComparerDictionaryPrototype = ImmutableDictionary.Create(MSBuildNameIgnoreCaseComparer.Default); /// /// Empty dictionary with , /// used as the basis of new dictionaries with that comparer to avoid /// allocating new comparers objects. /// - private readonly static ImmutableDictionary OrdinalIgnoreCaseComparerDictionaryPrototype = ImmutableDictionary.Create(StringComparer.OrdinalIgnoreCase); + private static readonly ImmutableDictionary OrdinalIgnoreCaseComparerDictionaryPrototype = ImmutableDictionary.Create(StringComparer.OrdinalIgnoreCase); #endif @@ -192,7 +192,7 @@ public V this[string key] { get { - TryGetValue((string) key, out V? val); + TryGetValue((string)key, out V? val); return val; } #nullable disable diff --git a/src/Shared/CoreCLRAssemblyLoader.cs b/src/Shared/CoreCLRAssemblyLoader.cs index 74afacbce8a..f1bd9b9fca4 100644 --- a/src/Shared/CoreCLRAssemblyLoader.cs +++ b/src/Shared/CoreCLRAssemblyLoader.cs @@ -1,4 +1,5 @@ -// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared.FileSystem; diff --git a/src/Shared/Debugging/DebugUtils.cs b/src/Shared/Debugging/DebugUtils.cs index 3ebdad82043..3dbb923f690 100644 --- a/src/Shared/Debugging/DebugUtils.cs +++ b/src/Shared/Debugging/DebugUtils.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using System; diff --git a/src/Shared/Debugging/PrintLineDebugger.cs b/src/Shared/Debugging/PrintLineDebugger.cs index 62110039952..e0aeb5eab73 100644 --- a/src/Shared/Debugging/PrintLineDebugger.cs +++ b/src/Shared/Debugging/PrintLineDebugger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -63,7 +63,7 @@ public void Dispose() public static CommonWriterType GetStaticWriter() { - return (CommonWriterType) CommonWriterProperty.Value.GetValue(null, null); + return (CommonWriterType)CommonWriterProperty.Value.GetValue(null, null); } // this setter is not thread safe because the assumption is that a writer is set once for the duration of the process (or multiple times from different tests which do not run in parallel). @@ -78,7 +78,7 @@ public static void SetWriter(CommonWriterType writer) } // wrap with a lock so multi threaded logging does not break messages apart - CommonWriterProperty.Value.SetValue(null, (CommonWriterType) LockWrappedWriter); + CommonWriterProperty.Value.SetValue(null, (CommonWriterType)LockWrappedWriter); void LockWrappedWriter(string id, string callsite, IEnumerable message) { @@ -128,7 +128,7 @@ public void Log( #if DEBUG var writer = GetWriter(); - writer?.Invoke(_id, CallsiteString(sourceFilePath, memberName, sourceLineNumber), new[] {message}); + writer?.Invoke(_id, CallsiteString(sourceFilePath, memberName, sourceLineNumber), new[] { message }); #endif } diff --git a/src/Shared/Debugging/PrintLineDebuggerWriters.cs b/src/Shared/Debugging/PrintLineDebuggerWriters.cs index c95ad539ff2..ce90f8a074d 100644 --- a/src/Shared/Debugging/PrintLineDebuggerWriters.cs +++ b/src/Shared/Debugging/PrintLineDebuggerWriters.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/EncodingStringWriter.cs b/src/Shared/EncodingStringWriter.cs index fcbcb254b7d..3955798c458 100644 --- a/src/Shared/EncodingStringWriter.cs +++ b/src/Shared/EncodingStringWriter.cs @@ -1,4 +1,7 @@ -using System.Globalization; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Globalization; using System.IO; using System.Text; diff --git a/src/Shared/EncodingUtilities.cs b/src/Shared/EncodingUtilities.cs index 40ae3a34e5b..b7d1813f368 100644 --- a/src/Shared/EncodingUtilities.cs +++ b/src/Shared/EncodingUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -35,7 +35,9 @@ internal static Encoding CurrentSystemOemEncoding { // if we already have it, no need to do it again if (s_currentOemEncoding != null) + { return s_currentOemEncoding; + } // fall back to default ANSI encoding if we have problems #if FEATURE_ENCODING_DEFAULT @@ -82,13 +84,19 @@ internal static Encoding CurrentSystemOemEncoding internal static bool SimilarToEncoding(this Encoding encoding1, Encoding encoding2) { if (encoding1 == null) + { return encoding2 == null; + } if (encoding2 == null) + { return false; + } if (Equals(encoding1, encoding2)) + { return true; + } return encoding1.EncodingName == encoding2.EncodingName; } @@ -121,7 +129,10 @@ internal static bool StartsWithPreamble(this Stream stream) /// True when the first 3 bytes of the Stream are equal to the preamble. internal static bool StartsWithPreamble(this Stream stream, byte[] preamble) { - if (preamble == null) return false; + if (preamble == null) + { + return false; + } int bytesRead; var buffer = new byte[preamble.Length]; diff --git a/src/Shared/EnvironmentUtilities.cs b/src/Shared/EnvironmentUtilities.cs index 7cb21b1abe2..71e7b576389 100644 --- a/src/Shared/EnvironmentUtilities.cs +++ b/src/Shared/EnvironmentUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Shared/ErrorUtilities.cs b/src/Shared/ErrorUtilities.cs index 7b9017f4701..1dc5a2b9c8a 100644 --- a/src/Shared/ErrorUtilities.cs +++ b/src/Shared/ErrorUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -206,11 +206,9 @@ internal static void VerifyThrowInternalRooted(string value) /// /// /// - internal static void VerifyThrow - ( + internal static void VerifyThrow( bool condition, - string unformattedMessage - ) + string unformattedMessage) { if (!condition) { @@ -226,12 +224,10 @@ string unformattedMessage /// /// /// - internal static void VerifyThrow - ( + internal static void VerifyThrow( bool condition, string unformattedMessage, - object arg0 - ) + object arg0) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInternalError() method, because that method always @@ -249,13 +245,11 @@ object arg0 /// /// /// - internal static void VerifyThrow - ( + internal static void VerifyThrow( bool condition, string unformattedMessage, object arg0, - object arg1 - ) + object arg1) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInternalError() method, because that method always @@ -274,14 +268,12 @@ object arg1 /// /// /// - internal static void VerifyThrow - ( + internal static void VerifyThrow( bool condition, string unformattedMessage, object arg0, object arg1, - object arg2 - ) + object arg2) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInternalError() method, because that method always @@ -301,15 +293,13 @@ object arg2 /// /// /// - internal static void VerifyThrow - ( + internal static void VerifyThrow( bool condition, string unformattedMessage, object arg0, object arg1, object arg2, - object arg3 - ) + object arg3) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInternalError() method, because that method always @@ -345,11 +335,9 @@ internal static void ThrowInvalidOperation(string resourceName, params object[] /// /// /// - internal static void VerifyThrowInvalidOperation - ( + internal static void VerifyThrowInvalidOperation( bool condition, - string resourceName - ) + string resourceName) { if (!condition) { @@ -365,12 +353,10 @@ string resourceName /// /// /// - internal static void VerifyThrowInvalidOperation - ( + internal static void VerifyThrowInvalidOperation( bool condition, string resourceName, - object arg0 - ) + object arg0) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidOperation() method, because that method always @@ -388,13 +374,11 @@ object arg0 /// /// /// - internal static void VerifyThrowInvalidOperation - ( + internal static void VerifyThrowInvalidOperation( bool condition, string resourceName, object arg0, - object arg1 - ) + object arg1) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidOperation() method, because that method always @@ -413,14 +397,12 @@ object arg1 /// /// /// - internal static void VerifyThrowInvalidOperation - ( + internal static void VerifyThrowInvalidOperation( bool condition, string resourceName, object arg0, object arg1, - object arg2 - ) + object arg2) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidOperation() method, because that method always @@ -440,15 +422,13 @@ object arg2 /// /// /// - internal static void VerifyThrowInvalidOperation - ( + internal static void VerifyThrowInvalidOperation( bool condition, string resourceName, object arg0, object arg1, object arg2, - object arg3 - ) + object arg3) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidOperation() method, because that method always @@ -470,11 +450,9 @@ object arg3 /// is expensive, because memory is allocated for the array of arguments -- do /// not call this method repeatedly in performance-critical scenarios /// - internal static void ThrowArgument - ( + internal static void ThrowArgument( string resourceName, - params object[] args - ) + params object[] args) { ThrowArgument(null, resourceName, args); } @@ -492,12 +470,10 @@ params object[] args /// Can be null. /// /// - internal static void ThrowArgument - ( + internal static void ThrowArgument( Exception innerException, string resourceName, - params object[] args - ) + params object[] args) { #if DEBUG ResourceUtilities.VerifyResourceStringExists(resourceName); @@ -514,11 +490,9 @@ params object[] args /// This method is thread-safe. /// /// - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, - string resourceName - ) + string resourceName) { VerifyThrowArgument(condition, null, resourceName); } @@ -530,12 +504,10 @@ string resourceName /// /// /// - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, string resourceName, - object arg0 - ) + object arg0) { VerifyThrowArgument(condition, null, resourceName, arg0); } @@ -548,13 +520,11 @@ object arg0 /// /// /// - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, string resourceName, object arg0, - object arg1 - ) + object arg1) { VerifyThrowArgument(condition, null, resourceName, arg0, arg1); } @@ -563,14 +533,12 @@ object arg1 /// Overload for three string format arguments. /// /// This method is thread-safe. - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, string resourceName, object arg0, object arg1, - object arg2 - ) + object arg2) { VerifyThrowArgument(condition, null, resourceName, arg0, arg1, arg2); } @@ -579,15 +547,13 @@ object arg2 /// Overload for four string format arguments. /// /// This method is thread-safe. - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, string resourceName, object arg0, object arg1, object arg2, - object arg3 - ) + object arg3) { VerifyThrowArgument(condition, null, resourceName, arg0, arg1, arg2, arg3); } @@ -600,12 +566,10 @@ object arg3 /// /// Can be null. /// - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, Exception innerException, - string resourceName - ) + string resourceName) { if (!condition) { @@ -623,13 +587,11 @@ string resourceName /// /// /// - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, Exception innerException, string resourceName, - object arg0 - ) + object arg0) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowArgument() method, because that method always allocates @@ -649,14 +611,12 @@ object arg0 /// /// /// - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, Exception innerException, string resourceName, object arg0, - object arg1 - ) + object arg1) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowArgument() method, because that method always allocates @@ -671,15 +631,13 @@ object arg1 /// Overload for three string format arguments. /// /// This method is thread-safe. - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, Exception innerException, string resourceName, object arg0, object arg1, - object arg2 - ) + object arg2) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowArgument() method, because that method always allocates @@ -694,16 +652,14 @@ object arg2 /// Overload for four string format arguments. /// /// This method is thread-safe. - internal static void VerifyThrowArgument - ( + internal static void VerifyThrowArgument( bool condition, Exception innerException, string resourceName, object arg0, object arg1, object arg2, - object arg3 - ) + object arg3) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowArgument() method, because that method always allocates diff --git a/src/Shared/EscapingUtilities.cs b/src/Shared/EscapingUtilities.cs index 905e705fcf9..f84ddf86632 100644 --- a/src/Shared/EscapingUtilities.cs +++ b/src/Shared/EscapingUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -20,7 +20,7 @@ namespace Microsoft.Build.Shared /// PERF: since we escape and unescape relatively frequently, it may be worth caching /// the last N strings that were (un)escaped /// - static internal class EscapingUtilities + internal static class EscapingUtilities { /// /// Optional cache of escaped strings for use when needing to escape in performance-critical scenarios with significant @@ -102,8 +102,7 @@ internal static string UnescapeAll(string escapedString, bool trim = false) if ( (indexOfPercent <= (escapedStringLength - 3)) && TryDecodeHexDigit(escapedString[indexOfPercent + 1], out int digit1) && - TryDecodeHexDigit(escapedString[indexOfPercent + 2], out int digit2) - ) + TryDecodeHexDigit(escapedString[indexOfPercent + 2], out int digit2)) { // First copy all the characters up to the current percent sign into // the destination. @@ -215,10 +214,8 @@ private static string EscapeWithOptionalCaching(string unescapedString, bool cac /// /// /// - private static bool ContainsReservedCharacters - ( - string unescapedString - ) + private static bool ContainsReservedCharacters( + string unescapedString) { return -1 != unescapedString.IndexOfAny(s_charsToEscape); } diff --git a/src/Shared/EventArgsFormatting.cs b/src/Shared/EventArgsFormatting.cs index ace6e1e8159..643b3761c86 100644 --- a/src/Shared/EventArgsFormatting.cs +++ b/src/Shared/EventArgsFormatting.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -170,8 +170,7 @@ internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProj /// end column number (0 if n/a) /// thread id /// The formatted message string. - internal static string FormatEventMessage - ( + internal static string FormatEventMessage( string category, string subcategory, string message, @@ -181,8 +180,7 @@ internal static string FormatEventMessage int endLineNumber, int columnNumber, int endColumnNumber, - int threadId - ) + int threadId) { return FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId, null); } @@ -204,8 +202,7 @@ int threadId /// thread id /// log output properties /// The formatted message string. - internal static string FormatEventMessage - ( + internal static string FormatEventMessage( string category, string subcategory, string message, @@ -217,8 +214,7 @@ internal static string FormatEventMessage int columnNumber, int endColumnNumber, int threadId, - string logOutputProperties - ) + string logOutputProperties) { // capacity is the longest possible path through the below // to avoid reallocating while constructing the string diff --git a/src/Shared/ExceptionHandling.cs b/src/Shared/ExceptionHandling.cs index 8752511e6b8..a7ef74e8737 100644 --- a/src/Shared/ExceptionHandling.cs +++ b/src/Shared/ExceptionHandling.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -43,9 +43,28 @@ internal static class ExceptionHandling private static string GetDebugDumpPath() { string debugPath = -// Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + + /* Unmerged change from project 'Microsoft.Build.Engine.OM.UnitTests (net7.0)' + Before: + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + After: + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + */ + /* Unmerged change from project 'Microsoft.Build.Engine.OM.UnitTests (net472)' + Before: + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + After: + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + */ + /* Unmerged change from project 'MSBuildTaskHost' + Before: + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + After: + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) + */ + // Cannot access change wave logic from these assemblies (https://github.com/dotnet/msbuild/issues/6707) #if CLR2COMPATIBILITY || MICROSOFT_BUILD_ENGINE_OM_UNITTESTS - Environment.GetEnvironmentVariable("MSBUILDDEBUGPATH"); + Environment.GetEnvironmentVariable("MSBUILDDEBUGPATH"); #else DebugUtils.DebugPath; #endif @@ -197,8 +216,7 @@ internal static bool NotExpectedIoOrXmlException(Exception e) if ( IsXmlException(e) - || !NotExpectedException(e) - ) + || !NotExpectedException(e)) { return false; } @@ -232,9 +250,7 @@ internal static bool NotExpectedReflectionException(Exception e) || e is TargetException // thrown when an attempt is made to invoke a non-static method on a null object. This may occur because the caller does not // have access to the member, or because the target does not define the member, and so on. || e is MissingFieldException // thrown when code in a dependent assembly attempts to access a missing field in an assembly that was modified. - || !NotExpectedException(e) // Reflection can throw IO exceptions if the assembly cannot be opened - - ) + || !NotExpectedException(e)) // Reflection can throw IO exceptions if the assembly cannot be opened { return false; } @@ -252,8 +268,7 @@ internal static bool NotExpectedSerializationException(Exception e) if ( e is SerializationException || - !NotExpectedReflectionException(e) - ) + !NotExpectedReflectionException(e)) { return false; } diff --git a/src/Shared/ExtensionFoldersRegistryKey.cs b/src/Shared/ExtensionFoldersRegistryKey.cs index a4eab36a425..c264311ce11 100644 --- a/src/Shared/ExtensionFoldersRegistryKey.cs +++ b/src/Shared/ExtensionFoldersRegistryKey.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Shared/FileDelegates.cs b/src/Shared/FileDelegates.cs index f4f972ec636..906dfcf9964 100644 --- a/src/Shared/FileDelegates.cs +++ b/src/Shared/FileDelegates.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; diff --git a/src/Shared/FileMatcher.cs b/src/Shared/FileMatcher.cs index 89f0375ee55..660dbd5327d 100644 --- a/src/Shared/FileMatcher.cs +++ b/src/Shared/FileMatcher.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Buffers; @@ -251,8 +251,8 @@ private static IReadOnlyList GetAccessibleFilesAndDirectories(IFileSyste return (ShouldEnforceMatching(pattern) ? fileSystem.EnumerateFileSystemEntries(path, pattern) .Where(o => IsFileNameMatch(o, pattern)) - : fileSystem.EnumerateFileSystemEntries(path, pattern) - ).ToArray(); + : fileSystem.EnumerateFileSystemEntries(path, pattern)) + .ToArray(); } // for OS security catch (UnauthorizedAccessException) @@ -291,8 +291,7 @@ private static bool ShouldEnforceMatching(string searchPattern) return searchPattern.IndexOf("?.", StringComparison.Ordinal) != -1 || ( Path.GetExtension(searchPattern).Length == (3 + 1 /* +1 for the period */) && - searchPattern.IndexOf('*') != -1 - ) || + searchPattern.IndexOf('*') != -1) || searchPattern.EndsWith("?", StringComparison.Ordinal); } @@ -308,14 +307,12 @@ private static bool ShouldEnforceMatching(string searchPattern) /// /// The file system abstraction to use that implements file system operations /// Files that can be accessed. - private static IReadOnlyList GetAccessibleFiles - ( + private static IReadOnlyList GetAccessibleFiles( IFileSystem fileSystem, string path, string filespec, // can be null string projectDirectory, - bool stripProjectDirectory - ) + bool stripProjectDirectory) { try { @@ -376,12 +373,10 @@ bool stripProjectDirectory /// Pattern to match /// The file system abstraction to use that implements file system operations /// Accessible directories. - private static IReadOnlyList GetAccessibleDirectories - ( + private static IReadOnlyList GetAccessibleDirectories( IFileSystem fileSystem, string path, - string pattern - ) + string pattern) { try { @@ -429,10 +424,8 @@ string pattern /// /// The short path. /// The long path. - internal string GetLongPathName - ( - string path - ) + internal string GetLongPathName( + string path) { return GetLongPathName(path, _getFileSystemEntries); } @@ -443,11 +436,9 @@ string path /// The short path. /// Delegate. /// The long path. - internal static string GetLongPathName - ( + internal static string GetLongPathName( string path, - GetFileSystemEntries getFileSystemEntries - ) + GetFileSystemEntries getFileSystemEntries) { if (path.IndexOf("~", StringComparison.Ordinal) == -1) { @@ -555,13 +546,11 @@ internal void SplitFileSpec( out string wildcardDirectoryPart, out string filenamePart) { - PreprocessFileSpecForSplitting - ( + PreprocessFileSpecForSplitting( filespec, out fixedDirectoryPart, out wildcardDirectoryPart, - out filenamePart - ); + out filenamePart); /* * Handle the special case in which filenamePart is '**'. @@ -590,13 +579,11 @@ out filenamePart /// Receives the fixed directory part. /// The wildcard directory part. /// The filename part. - private static void PreprocessFileSpecForSplitting - ( + private static void PreprocessFileSpecForSplitting( string filespec, out string fixedDirectoryPart, out string wildcardDirectoryPart, - out string filenamePart - ) + out string filenamePart) { filespec = FileUtilities.FixFilePath(filespec); int indexOfLastDirectorySeparator = filespec.LastIndexOfAny(directorySeparatorCharacters); @@ -622,8 +609,7 @@ out string filenamePart if ( -1 == indexOfFirstWildcard - || indexOfFirstWildcard > indexOfLastDirectorySeparator - ) + || indexOfFirstWildcard > indexOfLastDirectorySeparator) { /* * There is at least one dir separator, but either there is no wild card or the @@ -682,10 +668,8 @@ out string filenamePart /// Removes the leading ".\" from all of the paths in the array. /// /// Paths to remove .\ from. - private static IEnumerable RemoveInitialDotSlash - ( - IEnumerable paths - ) + private static IEnumerable RemoveInitialDotSlash( + IEnumerable paths) { foreach (string path in paths) { @@ -714,11 +698,9 @@ internal static bool IsDirectorySeparator(char c) /// /// Paths to remove current directory from. /// - internal static IEnumerable RemoveProjectDirectory - ( + internal static IEnumerable RemoveProjectDirectory( IEnumerable paths, - string projectDirectory - ) + string projectDirectory) { bool directoryLastCharIsSeparator = IsDirectorySeparator(projectDirectory[projectDirectory.Length - 1]); foreach (string path in paths) @@ -748,7 +730,7 @@ string projectDirectory } } - struct RecursiveStepResult + private struct RecursiveStepResult { public string RemainingWildcardDirectory; public bool ConsiderFiles; @@ -757,14 +739,13 @@ struct RecursiveStepResult public bool NeedsDirectoryRecursion; } - class FilesSearchData + private class FilesSearchData { public FilesSearchData( string filespec, // can be null string directoryPattern, // can be null Regex regexFileMatch, // can be null - bool needsRecursion - ) + bool needsRecursion) { Filespec = filespec; DirectoryPattern = directoryPattern; @@ -793,7 +774,7 @@ bool needsRecursion public bool NeedsRecursion { get; } } - struct RecursionState + private struct RecursionState { /// /// The directory to search in @@ -1105,10 +1086,8 @@ private static bool MatchFileRecursionStep(RecursionState recursionState, string return recursionState.SearchData.RegexFileMatch.IsMatch(file); } - private static RecursiveStepResult GetFilesRecursiveStep - ( - RecursionState recursionState - ) + private static RecursiveStepResult GetFilesRecursiveStep( + RecursionState recursionState) { RecursiveStepResult ret = new RecursiveStepResult(); @@ -1198,12 +1177,10 @@ RecursionState recursionState /// The wildcard directory part. /// The filename part. /// The regular expression string. - internal static string RegularExpressionFromFileSpec - ( + internal static string RegularExpressionFromFileSpec( string fixedDirectoryPart, string wildcardDirectoryPart, - string filenamePart - ) + string filenamePart) { #if DEBUG ErrorUtilities.VerifyThrow( @@ -1212,8 +1189,7 @@ string filenamePart + FileSpecRegexParts.FilenameGroupStart.Length + (FileSpecRegexParts.GroupEnd.Length * 2) + FileSpecRegexParts.EndOfLine.Length, - "Checked-in length of known regex components differs from computed length. Update checked-in constant." - ); + "Checked-in length of known regex components differs from computed length. Update checked-in constant."); #endif using (var matchFileExpression = new ReuseableStringBuilder(FileSpecRegexMinLength + NativeMethodsShared.MAX_PATH)) { @@ -1636,8 +1612,7 @@ internal static bool RawFileSpecIsValid(string filespec) if ( -1 != rightmostColon - && 1 != rightmostColon - ) + && 1 != rightmostColon) { return false; } @@ -1858,24 +1833,20 @@ bool CompareIgnoreCase(ref ReadOnlySpan input, int iIndex, int pIndex) /// The filespec. /// The candidate to match against. /// The result class. - internal Result FileMatch - ( + internal Result FileMatch( string filespec, - string fileToMatch - ) + string fileToMatch) { Result matchResult = new Result(); fileToMatch = GetLongPathName(fileToMatch, _getFileSystemEntries); Regex regexFileMatch; - GetFileSpecInfoWithRegexObject - ( + GetFileSpecInfoWithRegexObject( filespec, out regexFileMatch, out matchResult.isFileSpecRecursive, - out matchResult.isLegalFileSpec - ); + out matchResult.isLegalFileSpec); if (matchResult.isLegalFileSpec) { @@ -1910,7 +1881,7 @@ internal static void GetRegexMatchInfo( } } - class TaskOptions + private class TaskOptions { public TaskOptions(int maxTasks) { @@ -1940,12 +1911,10 @@ public TaskOptions(int maxTasks) /// Get files that match the given file spec. /// Exclude files that match this file spec. /// The search action, array of files, and Exclude file spec (if applicable). - internal (string[] FileList, SearchAction Action, string ExcludeFileSpec) GetFiles - ( + internal (string[] FileList, SearchAction Action, string ExcludeFileSpec) GetFiles( string projectDirectoryUnescaped, string filespecUnescaped, - List excludeSpecsUnescaped = null - ) + List excludeSpecsUnescaped = null) { // For performance. Short-circuit iff there is no wildcard. if (!HasWildcards(filespecUnescaped)) @@ -2090,15 +2059,13 @@ private SearchAction GetFileSearchData( stripProjectDirectory = false; result = new RecursionState(); - GetFileSpecInfo - ( + GetFileSpecInfo( filespecUnescaped, out string fixedDirectoryPart, out string wildcardDirectoryPart, out string filenamePart, out bool needsRecursion, - out bool isLegalFileSpec - ); + out bool isLegalFileSpec); /* * If the filespec is invalid, then just return now. @@ -2675,7 +2642,7 @@ private static bool IsSubdirectoryOf(string possibleChild, string possibleParent // Ensure that the prefix match wasn't to a distinct directory, so that // x\y\prefix doesn't falsely match x\y\prefixmatch. - if (directorySeparatorCharacters.Contains(possibleParent[possibleParent.Length-1])) + if (directorySeparatorCharacters.Contains(possibleParent[possibleParent.Length - 1])) { return true; } diff --git a/src/Shared/FileSystem/CachingFileSystemWrapper.cs b/src/Shared/FileSystem/CachingFileSystemWrapper.cs index 7dc859b7a61..9f43fe26b65 100644 --- a/src/Shared/FileSystem/CachingFileSystemWrapper.cs +++ b/src/Shared/FileSystem/CachingFileSystemWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -33,7 +33,7 @@ public FileAttributes GetAttributes(string path) public DateTime GetLastWriteTimeUtc(string path) { - return _lastWriteTimeCache.GetOrAdd(path, p =>_fileSystem.GetLastWriteTimeUtc(p)); + return _lastWriteTimeCache.GetOrAdd(path, p => _fileSystem.GetLastWriteTimeUtc(p)); } public bool DirectoryExists(string path) diff --git a/src/Shared/FileSystem/FileSystems.cs b/src/Shared/FileSystem/FileSystems.cs index 8a072f89e62..c876af6bc77 100644 --- a/src/Shared/FileSystem/FileSystems.cs +++ b/src/Shared/FileSystem/FileSystems.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/FileSystem/IFileSystem.cs b/src/Shared/FileSystem/IFileSystem.cs index 52d37af1d08..191e348ee2d 100644 --- a/src/Shared/FileSystem/IFileSystem.cs +++ b/src/Shared/FileSystem/IFileSystem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/FileSystem/MSBuildOnWindowsFileSystem.cs b/src/Shared/FileSystem/MSBuildOnWindowsFileSystem.cs index 8ba84cebe03..b6028669729 100644 --- a/src/Shared/FileSystem/MSBuildOnWindowsFileSystem.cs +++ b/src/Shared/FileSystem/MSBuildOnWindowsFileSystem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/FileSystem/ManagedFileSystem.cs b/src/Shared/FileSystem/ManagedFileSystem.cs index c36cc5dee1b..f2223635f80 100644 --- a/src/Shared/FileSystem/ManagedFileSystem.cs +++ b/src/Shared/FileSystem/ManagedFileSystem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -59,8 +59,7 @@ private static IEnumerable HandleFileLoadException( Func> enumerateFunctionDelegate, string path, string searchPattern, - Microsoft.IO.SearchOption searchOption - ) + Microsoft.IO.SearchOption searchOption) { try { @@ -89,8 +88,7 @@ public virtual IEnumerable EnumerateFiles(string path, string searchPatt (path, searchPattern, searchOption) => Microsoft.IO.Directory.EnumerateFiles(path, searchPattern, searchOption), path, searchPattern, - (Microsoft.IO.SearchOption)searchOption - ) + (Microsoft.IO.SearchOption)searchOption) : Directory.EnumerateFiles(path, searchPattern, searchOption); #else return Directory.EnumerateFiles(path, searchPattern, searchOption); @@ -105,8 +103,7 @@ public virtual IEnumerable EnumerateDirectories(string path, string sear (path, searchPattern, searchOption) => Microsoft.IO.Directory.EnumerateDirectories(path, searchPattern, searchOption), path, searchPattern, - (Microsoft.IO.SearchOption)searchOption - ) + (Microsoft.IO.SearchOption)searchOption) : Directory.EnumerateDirectories(path, searchPattern, searchOption); #else return Directory.EnumerateDirectories(path, searchPattern, searchOption); @@ -120,8 +117,7 @@ public virtual IEnumerable EnumerateFileSystemEntries(string path, strin ? HandleFileLoadException( (path, searchPattern, searchOption) => Microsoft.IO.Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption), path, - searchPattern, (Microsoft.IO.SearchOption)searchOption - ) + searchPattern, (Microsoft.IO.SearchOption)searchOption) : Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption); #else return Directory.EnumerateFileSystemEntries(path, searchPattern, searchOption); diff --git a/src/Shared/FileSystem/NativeWin32Exception.cs b/src/Shared/FileSystem/NativeWin32Exception.cs index e013be4f15d..6bb447d4e90 100644 --- a/src/Shared/FileSystem/NativeWin32Exception.cs +++ b/src/Shared/FileSystem/NativeWin32Exception.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; diff --git a/src/Shared/FileSystem/SafeFileHandle.cs b/src/Shared/FileSystem/SafeFileHandle.cs index e24195c838a..b449293797f 100644 --- a/src/Shared/FileSystem/SafeFileHandle.cs +++ b/src/Shared/FileSystem/SafeFileHandle.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32.SafeHandles; diff --git a/src/Shared/FileSystem/WindowsFileSystem.cs b/src/Shared/FileSystem/WindowsFileSystem.cs index 60867009993..6185124d4f1 100644 --- a/src/Shared/FileSystem/WindowsFileSystem.cs +++ b/src/Shared/FileSystem/WindowsFileSystem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -34,9 +34,9 @@ internal class WindowsFileSystem : ManagedFileSystem { private static readonly WindowsFileSystem Instance = new(); - public new static WindowsFileSystem Singleton() => WindowsFileSystem.Instance; + public static new WindowsFileSystem Singleton() => WindowsFileSystem.Instance; - private WindowsFileSystem(){ } + private WindowsFileSystem() { } public override IEnumerable EnumerateFiles(string path, string searchPattern, SearchOption searchOption) { diff --git a/src/Shared/FileSystem/WindowsNative.cs b/src/Shared/FileSystem/WindowsNative.cs index 6ff01bc882c..63640a185be 100644 --- a/src/Shared/FileSystem/WindowsNative.cs +++ b/src/Shared/FileSystem/WindowsNative.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Shared/FileUtilities.cs b/src/Shared/FileUtilities.cs index 63025199472..b1cee220d8b 100644 --- a/src/Shared/FileUtilities.cs +++ b/src/Shared/FileUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; #if !CLR2COMPATIBILITY @@ -376,7 +376,11 @@ internal static String GetDirectoryNameOfFullPath(String fullPath) if (fullPath != null) { int i = fullPath.Length; - while (i > 0 && fullPath[--i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar); + while (i > 0 && fullPath[--i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar) + { + ; + } + return FixFilePath(fullPath.Substring(0, i)); } return null; @@ -1098,7 +1102,9 @@ internal static bool IsBinaryLogFilename(string filename) private static bool HasExtension(string filename, string extension) { if (String.IsNullOrEmpty(filename)) + { return false; + } return filename.EndsWith(extension, PathComparison); } @@ -1231,7 +1237,9 @@ private static bool IsRootedNoThrow(string path) internal static string GetFolderAbove(string path, int count = 1) { if (count < 1) + { return path; + } var parent = Directory.GetParent(path); @@ -1358,8 +1366,15 @@ internal static bool PathsEqual(string path1, string path2) } // uppercase both chars - notice that we need just one compare per char - if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; - if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; + if ((uint)(charA - 'a') <= (uint)('z' - 'a')) + { + charA -= 0x20; + } + + if ((uint)(charB - 'a') <= (uint)('z' - 'a')) + { + charB -= 0x20; + } // Set path delimiters the same if (charA == '\\') diff --git a/src/Shared/FileUtilitiesRegex.cs b/src/Shared/FileUtilitiesRegex.cs index de492cc69ac..650942be1e5 100644 --- a/src/Shared/FileUtilitiesRegex.cs +++ b/src/Shared/FileUtilitiesRegex.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; @@ -162,6 +162,6 @@ internal static bool MeetsUncPatternMinimumRequirements(string pattern) pattern[0] == _forwardSlash) && (pattern[1] == _backSlash || pattern[1] == _forwardSlash); - } + } } } diff --git a/src/Shared/FrameworkLocationHelper.cs b/src/Shared/FrameworkLocationHelper.cs index 28f8a292848..3ff6eb90662 100644 --- a/src/Shared/FrameworkLocationHelper.cs +++ b/src/Shared/FrameworkLocationHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -126,9 +126,9 @@ internal static class FrameworkLocationHelper private const string ToolsVersionsRegistryPath = @"SOFTWARE\Microsoft\MSBuild\ToolsVersions"; #endif // FEATURE_WIN32_REGISTRY -#endregion // Constants + #endregion // Constants -#region Static member variables + #region Static member variables /// /// By default when a root path is not specified we would like to use the program files directory \ reference assemblies\framework as the root location @@ -398,9 +398,9 @@ private static readonly (Version, Version)[,] s_explicitFallbackRulesForPathToDo private static readonly Lazy> DotNetFrameworkSpecDict = new(() => DotNetFrameworkSpecs().ToDictionary(spec => spec.Version)); private static readonly Lazy> VisualStudioSpecDict = new(() => VisualStudioSpecs.Value.ToDictionary(spec => spec.Version)); -#endregion // Static member variables + #endregion // Static member variables -#region Static properties + #region Static properties internal static string PathToDotNetFrameworkV11 { @@ -622,9 +622,9 @@ private static string PathToV4ToolsInFallbackDotNetFrameworkSdk } } -#endregion // Static properties + #endregion // Static properties -#region Internal methods + #region Internal methods internal static string GetDotNetFrameworkSdkRootRegistryKey(Version dotNetFrameworkVersion, Version visualStudioVersion) { @@ -764,14 +764,12 @@ private static bool CheckForFrameworkInstallation(string registryEntryToCheckIns /// Delegate to method that can return filesystem entries. /// .NET framework architecture /// Will return 'null' if there is no target frameworks on this machine. - internal static string FindDotNetFrameworkPath - ( + internal static string FindDotNetFrameworkPath( string currentRuntimePath, string prefix, DirectoryExists directoryExists, GetDirectories getDirectories, - DotNetFrameworkArchitecture architecture - ) + DotNetFrameworkArchitecture architecture) { if (!NativeMethodsShared.IsWindows) { @@ -1090,9 +1088,9 @@ private static string GetPathToBuildToolsFromRegistry(string toolsVersion, DotNe } #endif -#endregion // Internal methods + #endregion // Internal methods -#region Private methods + #region Private methods /// /// Will return the path to the dot net framework reference assemblies if they exist under the program files\reference assembies\microsoft\framework directory @@ -1115,8 +1113,7 @@ private static string GenerateReferenceAssemblyDirectory(string versionPrefix) /// /// Look for the given registry value under the given key. /// - private static string FindRegistryValueUnderKey - ( + private static string FindRegistryValueUnderKey( string registryBaseKeyName, string registryKeyName, RegistryView registryView = RegistryView.Default) @@ -1179,7 +1176,7 @@ private static void RedirectVersionsIfNecessary(ref Version dotNetFrameworkVersi } } -#endregion + #endregion private class VisualStudioSpec { @@ -1387,8 +1384,7 @@ public virtual string GetPathToDotNetFramework(DotNetFrameworkArchitecture archi // variables to null when that's what they are already. if (NativeMethodsShared.IsWindows && !CheckForFrameworkInstallation( this._dotNetFrameworkRegistryKey, - this._dotNetFrameworkSetupRegistryInstalledName - )) + this._dotNetFrameworkSetupRegistryInstalledName)) { return null; } @@ -1409,8 +1405,7 @@ public virtual string GetPathToDotNetFramework(DotNetFrameworkArchitecture archi if (this._hasMsBuild && generatedPathToDotNetFramework != null && (!FileSystems.Default.FileExists(Path.Combine(generatedPathToDotNetFramework, NativeMethodsShared.IsWindows ? "MSBuild.exe" : "mcs.exe")) && - !FileSystems.Default.FileExists(Path.Combine(generatedPathToDotNetFramework, "Microsoft.Build.dll"))) - ) + !FileSystems.Default.FileExists(Path.Combine(generatedPathToDotNetFramework, "Microsoft.Build.dll")))) { return null; } @@ -1728,7 +1723,7 @@ public override string GetPathToDotNetFrameworkSdk(VisualStudioSpec visualStudio /// public override string GetPathToDotNetFrameworkReferenceAssemblies() { - if (this._pathToDotNetFrameworkReferenceAssemblies== null) + if (this._pathToDotNetFrameworkReferenceAssemblies == null) { #if FEATURE_WIN32_REGISTRY this._pathToDotNetFrameworkReferenceAssemblies = FindRegistryValueUnderKey( diff --git a/src/Shared/IConstrainedEqualityComparer.cs b/src/Shared/IConstrainedEqualityComparer.cs index bedd0146be9..c66dc8925f1 100644 --- a/src/Shared/IConstrainedEqualityComparer.cs +++ b/src/Shared/IConstrainedEqualityComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Shared/IElementLocation.cs b/src/Shared/IElementLocation.cs index fb1d1d25849..6353e3d17fb 100644 --- a/src/Shared/IElementLocation.cs +++ b/src/Shared/IElementLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.BackEnd; diff --git a/src/Shared/IKeyed.cs b/src/Shared/IKeyed.cs index c3798db36f4..2c27ca9dc5d 100644 --- a/src/Shared/IKeyed.cs +++ b/src/Shared/IKeyed.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/INodeEndpoint.cs b/src/Shared/INodeEndpoint.cs index ef2f319f023..024dee437dc 100644 --- a/src/Shared/INodeEndpoint.cs +++ b/src/Shared/INodeEndpoint.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/INodePacket.cs b/src/Shared/INodePacket.cs index 0ddbf49a0d7..cb89889c3ac 100644 --- a/src/Shared/INodePacket.cs +++ b/src/Shared/INodePacket.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/INodePacketFactory.cs b/src/Shared/INodePacketFactory.cs index 9449c2aa021..c972e0408b5 100644 --- a/src/Shared/INodePacketFactory.cs +++ b/src/Shared/INodePacketFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/INodePacketHandler.cs b/src/Shared/INodePacketHandler.cs index c8e3a6c77c4..8d72f9dd053 100644 --- a/src/Shared/INodePacketHandler.cs +++ b/src/Shared/INodePacketHandler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/ITranslatable.cs b/src/Shared/ITranslatable.cs index 7492f801260..fdddd566135 100644 --- a/src/Shared/ITranslatable.cs +++ b/src/Shared/ITranslatable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/ITranslator.cs b/src/Shared/ITranslator.cs index 3a507470744..abe32f8d96f 100644 --- a/src/Shared/ITranslator.cs +++ b/src/Shared/ITranslator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -277,7 +277,7 @@ void Translate(ref T value) /// /// The array to be translated. void Translate(ref byte[] byteArray); - + /// /// Translates a byte array /// diff --git a/src/Shared/InprocTrackingNativeMethods.cs b/src/Shared/InprocTrackingNativeMethods.cs index bd0bae9633a..493c4f68490 100644 --- a/src/Shared/InprocTrackingNativeMethods.cs +++ b/src/Shared/InprocTrackingNativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -31,6 +31,7 @@ namespace Microsoft.Build.Shared /// internal static class InprocTrackingNativeMethods { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Delegates for the tracking functions [UnmanagedFunctionPointer(CallingConvention.StdCall)] @@ -146,15 +147,15 @@ internal static void SetThreadCount(int threadCount) } #endregion // Public API - +#pragma warning restore format private static class FileTrackerDllStub { - private readonly static Lazy fileTrackerDllName = new Lazy(() => RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? "FileTrackerA4.dll" : (IntPtr.Size == sizeof(Int32)) ? "FileTracker32.dll" : "FileTracker64.dll"); + private static readonly Lazy fileTrackerDllName = new Lazy(() => RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? "FileTrackerA4.dll" : (IntPtr.Size == sizeof(Int32)) ? "FileTracker32.dll" : "FileTracker64.dll"); // Handle for FileTracker.dll itself [SecurityCritical] private static SafeHandle s_fileTrackerDllHandle; - +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Function pointers to native functions internal static StartTrackingContextDelegate startTrackingContextDelegate; @@ -235,7 +236,9 @@ private static DT CreateDelegate
(String entryPointName) IntPtr entryPoint = GetProcAddress(s_fileTrackerDllHandle, entryPointName); if (IntPtr.Zero == entryPoint) + { throw new EntryPointNotFoundException(fileTrackerDllName.Value + "!" + entryPointName); + } return (DT)(Object)Marshal.GetDelegateForFunctionPointer(entryPoint, typeof(DT)); } @@ -271,7 +274,7 @@ static FileTrackerDllStub() } #endregion // Initialization code - +#pragma warning restore format // Specialized handle to make sure we free FileTracker.dll [SecurityCritical] private class SafeLibraryHandle : SafeHandle diff --git a/src/Shared/InterningBinaryReader.cs b/src/Shared/InterningBinaryReader.cs index 7f186597527..1fc332a0639 100644 --- a/src/Shared/InterningBinaryReader.cs +++ b/src/Shared/InterningBinaryReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; @@ -75,7 +75,7 @@ private InterningBinaryReader(Stream input, Buffer buffer, bool isPrivateBuffer) /// Read a string while checking the string precursor for intern opportunities. /// Taken from ndp\clr\src\bcl\system\io\binaryreader.cs-ReadString() ///
- override public String ReadString() + public override String ReadString() { char[] resultBuffer = null; try @@ -210,7 +210,7 @@ private static Buffer GetPooledBuffer() return new Buffer(); } -#region IDisposable pattern + #region IDisposable pattern /// /// Returns our buffer to the pool if we were not passed one by the caller. @@ -226,7 +226,7 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } -#endregion + #endregion /// /// Create a BinaryReader. It will either be an interning reader or standard binary reader @@ -286,7 +286,7 @@ internal byte[] ByteBuffer /// /// Opaque holder of shared buffer. /// - abstract internal class SharedReadBuffer + internal abstract class SharedReadBuffer { } } diff --git a/src/Shared/LanguageParser/CSharptokenCharReader.cs b/src/Shared/LanguageParser/CSharptokenCharReader.cs index 7dad4a3c123..9b3d77a6525 100644 --- a/src/Shared/LanguageParser/CSharptokenCharReader.cs +++ b/src/Shared/LanguageParser/CSharptokenCharReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -15,7 +15,7 @@ namespace Microsoft.Build.Shared.LanguageParser * Provides utility functions for dealing with C#-specific tokens. * */ - sealed internal class CSharpTokenCharReader : TokenCharReader + internal sealed class CSharpTokenCharReader : TokenCharReader { /* * Method: CSharpTokenCharReader diff --git a/src/Shared/LanguageParser/CSharptokenEnumerator.cs b/src/Shared/LanguageParser/CSharptokenEnumerator.cs index 6cd1204c112..0dbcda4b003 100644 --- a/src/Shared/LanguageParser/CSharptokenEnumerator.cs +++ b/src/Shared/LanguageParser/CSharptokenEnumerator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -15,7 +15,7 @@ namespace Microsoft.Build.Shared.LanguageParser * Given C# sources, enumerate over all tokens. * */ - sealed internal class CSharpTokenEnumerator : TokenEnumerator + internal sealed class CSharpTokenEnumerator : TokenEnumerator { // Reader over the sources. private CSharpTokenCharReader _reader = null; @@ -35,7 +35,7 @@ internal CSharpTokenEnumerator(Stream binaryStream, bool forceANSI) * * Find the next token. Return 'true' if one was found. False, otherwise. */ - override internal bool FindNextToken() + internal override bool FindNextToken() { int startPosition = _reader.Position; @@ -167,8 +167,7 @@ override internal bool FindNextToken() ( // From 2.4.2 Identifiers: A '@' can be used to prefix an identifier so that a keyword can be used as an identifier. _reader.CurrentCharacter == '@' || - _reader.MatchNextIdentifierStart() - ) + _reader.MatchNextIdentifierStart()) { if (_reader.CurrentCharacter == '@') { @@ -314,7 +313,7 @@ override internal bool FindNextToken() * * Return the token char reader. */ - override internal TokenCharReader Reader + internal override TokenCharReader Reader { get { diff --git a/src/Shared/LanguageParser/CSharptokenizer.cs b/src/Shared/LanguageParser/CSharptokenizer.cs index eedeedd05a8..d609157d3d2 100644 --- a/src/Shared/LanguageParser/CSharptokenizer.cs +++ b/src/Shared/LanguageParser/CSharptokenizer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Collections; @@ -14,7 +14,7 @@ namespace Microsoft.Build.Shared.LanguageParser * Given C# sources, return an enumerator that will provide tokens one at a time. * */ - sealed internal class CSharpTokenizer : IEnumerable + internal sealed class CSharpTokenizer : IEnumerable { /* These are the tokens that are specific to the C# tokenizer. diff --git a/src/Shared/LanguageParser/StreamMappedString.cs b/src/Shared/LanguageParser/StreamMappedString.cs index f8fda805458..c4cfd631df9 100644 --- a/src/Shared/LanguageParser/StreamMappedString.cs +++ b/src/Shared/LanguageParser/StreamMappedString.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -12,7 +12,7 @@ namespace Microsoft.Build.Shared.LanguageParser /// /// A class with string-like semantics mapped over a Stream. /// - sealed internal class StreamMappedString + internal sealed class StreamMappedString { /// /// The raw binary stream that's being read. @@ -107,27 +107,23 @@ private void RestartReader() if (_forceANSI) { - _reader = new StreamReader // HIGHCHAR: Falling back to ANSI for VB source files. - ( + _reader = new StreamReader( // HIGHCHAR: Falling back to ANSI for VB source files. _binaryStream, #if FEATURE_ENCODING_DEFAULT Encoding.Default, // Default means ANSI. #else Encoding.ASCII, #endif - false // If the reader had been able to guess the encoding it would have done so already. - ); + false); // If the reader had been able to guess the encoding it would have done so already. } else { Encoding utf8Encoding = new UTF8Encoding(false, true /* throw on illegal bytes */); - _reader = new StreamReader // HIGHCHAR: VB and C# source files are assumed to be UTF if there are no byte-order marks. - ( + _reader = new StreamReader( // HIGHCHAR: VB and C# source files are assumed to be UTF if there are no byte-order marks. _binaryStream, utf8Encoding, - true // Ask the reader to try to guess the file's encoding. - ); + true); // Ask the reader to try to guess the file's encoding. } } diff --git a/src/Shared/LanguageParser/VisualBasictokenCharReader.cs b/src/Shared/LanguageParser/VisualBasictokenCharReader.cs index 4686976eee1..63d10a29c91 100644 --- a/src/Shared/LanguageParser/VisualBasictokenCharReader.cs +++ b/src/Shared/LanguageParser/VisualBasictokenCharReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -15,7 +15,7 @@ namespace Microsoft.Build.Shared.LanguageParser * Provides utility functions for dealing with VB-specific tokens. * */ - sealed internal class VisualBasicTokenCharReader : TokenCharReader + internal sealed class VisualBasicTokenCharReader : TokenCharReader { /* * Method: VisualBasicTokenCharReader @@ -44,8 +44,7 @@ internal bool SinkSeparatorCharacter() || CurrentCharacter == '.' || CurrentCharacter == ':' || CurrentCharacter == '{' - || CurrentCharacter == '}' - ) + || CurrentCharacter == '}') { Skip(); return true; @@ -63,8 +62,7 @@ internal bool SinkLineContinuationCharacter() { if ( - CurrentCharacter == '_' - ) + CurrentCharacter == '_') { Skip(); return true; diff --git a/src/Shared/LanguageParser/VisualBasictokenEnumerator.cs b/src/Shared/LanguageParser/VisualBasictokenEnumerator.cs index 3fbc3b0ed4b..589f4ae3707 100644 --- a/src/Shared/LanguageParser/VisualBasictokenEnumerator.cs +++ b/src/Shared/LanguageParser/VisualBasictokenEnumerator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -14,7 +14,7 @@ namespace Microsoft.Build.Shared.LanguageParser * Given vb sources, enumerate over all tokens. * */ - sealed internal class VisualBasicTokenEnumerator : TokenEnumerator + internal sealed class VisualBasicTokenEnumerator : TokenEnumerator { // Reader over the sources. private VisualBasicTokenCharReader _reader = null; @@ -34,7 +34,7 @@ internal VisualBasicTokenEnumerator(Stream binaryStream, bool forceANSI) * * Find the next token. Return 'true' if one was found. False, otherwise. */ - override internal bool FindNextToken() + internal override bool FindNextToken() { int startPosition = _reader.Position; @@ -103,8 +103,7 @@ override internal bool FindNextToken() // Date is a keyword but, // [Date] is an identifier. _reader.CurrentCharacter == '[' || - _reader.MatchNextIdentifierStart() - ) + _reader.MatchNextIdentifierStart()) { bool escapedIdentifier = false; if (_reader.CurrentCharacter == '[') @@ -321,7 +320,7 @@ override internal bool FindNextToken() * * Return the token char reader. */ - override internal TokenCharReader Reader + internal override TokenCharReader Reader { get { diff --git a/src/Shared/LanguageParser/VisualBasictokenizer.cs b/src/Shared/LanguageParser/VisualBasictokenizer.cs index 3dfff889a24..fc76012673e 100644 --- a/src/Shared/LanguageParser/VisualBasictokenizer.cs +++ b/src/Shared/LanguageParser/VisualBasictokenizer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Collections; @@ -14,7 +14,7 @@ namespace Microsoft.Build.Shared.LanguageParser * Given vb sources, return an enumerator that will provide tokens one at a time. * */ - sealed internal class VisualBasicTokenizer : IEnumerable + internal sealed class VisualBasicTokenizer : IEnumerable { /* These are the tokens that are specific to the VB tokenizer. diff --git a/src/Shared/LanguageParser/token.cs b/src/Shared/LanguageParser/token.cs index 2322048c796..2ce67719e5c 100644 --- a/src/Shared/LanguageParser/token.cs +++ b/src/Shared/LanguageParser/token.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Shared/LanguageParser/tokenChar.cs b/src/Shared/LanguageParser/tokenChar.cs index fc1c21907e3..9d9e99eb67e 100644 --- a/src/Shared/LanguageParser/tokenChar.cs +++ b/src/Shared/LanguageParser/tokenChar.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; @@ -17,7 +17,7 @@ internal static class TokenChar /// /// /// - static internal bool IsNewLine(char c) + internal static bool IsNewLine(char c) { // From the C# spec and vb specs, newline characters are: return c == 0x000d // Carriage return @@ -32,7 +32,7 @@ static internal bool IsNewLine(char c) /// /// /// - static internal bool IsLetter(char c) + internal static bool IsLetter(char c) { UnicodeCategory cat = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c); @@ -44,8 +44,7 @@ static internal bool IsLetter(char c) || cat == UnicodeCategory.TitlecaseLetter || cat == UnicodeCategory.ModifierLetter || cat == UnicodeCategory.OtherLetter - || cat == UnicodeCategory.LetterNumber - ) + || cat == UnicodeCategory.LetterNumber) { return true; } @@ -57,15 +56,14 @@ static internal bool IsLetter(char c) /// /// /// - static internal bool IsDecimalDigit(char c) + internal static bool IsDecimalDigit(char c) { UnicodeCategory cat = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c); // From 2.4.2 of the C# Language Specification // decimal-digit-character: if ( - cat == UnicodeCategory.DecimalDigitNumber - ) + cat == UnicodeCategory.DecimalDigitNumber) { return true; } @@ -77,7 +75,7 @@ static internal bool IsDecimalDigit(char c) /// /// /// - static internal bool IsConnecting(char c) + internal static bool IsConnecting(char c) { UnicodeCategory cat = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c); @@ -85,8 +83,7 @@ static internal bool IsConnecting(char c) // connecting-character: if ( - cat == UnicodeCategory.ConnectorPunctuation - ) + cat == UnicodeCategory.ConnectorPunctuation) { return true; } @@ -98,7 +95,7 @@ static internal bool IsConnecting(char c) /// /// /// - static internal bool IsCombining(char c) + internal static bool IsCombining(char c) { UnicodeCategory cat = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c); @@ -106,8 +103,7 @@ static internal bool IsCombining(char c) // combining-character: if ( cat == UnicodeCategory.NonSpacingMark // Mn - || cat == UnicodeCategory.SpacingCombiningMark // Mc - ) + || cat == UnicodeCategory.SpacingCombiningMark) // Mc { return true; } @@ -119,15 +115,14 @@ static internal bool IsCombining(char c) /// /// /// - static internal bool IsFormatting(char c) + internal static bool IsFormatting(char c) { UnicodeCategory cat = System.Globalization.CharUnicodeInfo.GetUnicodeCategory(c); // From 2.4.2 of the C# Language Specification // formatting-character: if ( - cat == UnicodeCategory.Format // Cf - ) + cat == UnicodeCategory.Format) // Cf { return true; } @@ -139,7 +134,7 @@ static internal bool IsFormatting(char c) /// /// /// - static internal bool IsHexDigit(char c) + internal static bool IsHexDigit(char c) { // From 2.4.4.2 of the C# Language Specification // hex-digit: @@ -147,8 +142,7 @@ static internal bool IsHexDigit(char c) ( (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') - || (c >= 'a' && c <= 'f') - ) + || (c >= 'a' && c <= 'f')) { return true; } @@ -160,12 +154,11 @@ static internal bool IsHexDigit(char c) /// /// /// - static internal bool IsOctalDigit(char c) + internal static bool IsOctalDigit(char c) { if ( - c >= '0' && c <= '7' - ) + c >= '0' && c <= '7') { return true; } diff --git a/src/Shared/LanguageParser/tokenCharReader.cs b/src/Shared/LanguageParser/tokenCharReader.cs index ddd8b1d91a4..2d23ec90339 100644 --- a/src/Shared/LanguageParser/tokenCharReader.cs +++ b/src/Shared/LanguageParser/tokenCharReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -158,13 +158,10 @@ private bool Sink(string match, bool ignoreCase) if ( - String.Equals - ( + String.Equals( match, compare, - (ignoreCase /* ignore case */) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal - ) - ) + (ignoreCase /* ignore case */) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)) { Skip(match.Length); return true; @@ -243,8 +240,7 @@ internal bool SinkIdentifierPart() || TokenChar.IsDecimalDigit(CurrentCharacter) || TokenChar.IsConnecting(CurrentCharacter) || TokenChar.IsCombining(CurrentCharacter) - || TokenChar.IsFormatting(CurrentCharacter) - ) + || TokenChar.IsFormatting(CurrentCharacter)) { Skip(); return true; diff --git a/src/Shared/LanguageParser/tokenEnumerator.cs b/src/Shared/LanguageParser/tokenEnumerator.cs index 8c691dcb8b8..673b5a8a933 100644 --- a/src/Shared/LanguageParser/tokenEnumerator.cs +++ b/src/Shared/LanguageParser/tokenEnumerator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; @@ -20,10 +20,10 @@ internal abstract class TokenEnumerator : IEnumerator protected Token current = null; // Return the token char reader. - abstract internal TokenCharReader Reader { get; } + internal abstract TokenCharReader Reader { get; } // Implemented by derived class to find the next token. - abstract internal bool FindNextToken(); + internal abstract bool FindNextToken(); /* * Method: MoveNext diff --git a/src/Shared/LoadedType.cs b/src/Shared/LoadedType.cs index 0b2500390a3..1ff1e5b762b 100644 --- a/src/Shared/LoadedType.cs +++ b/src/Shared/LoadedType.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Linq; diff --git a/src/Shared/LogMessagePacketBase.cs b/src/Shared/LogMessagePacketBase.cs index 7d518897aa6..9938e6ac170 100644 --- a/src/Shared/LogMessagePacketBase.cs +++ b/src/Shared/LogMessagePacketBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/MSBuildLoadContext.cs b/src/Shared/MSBuildLoadContext.cs index 8d1e1c38e7a..6bbdaa7983e 100644 --- a/src/Shared/MSBuildLoadContext.cs +++ b/src/Shared/MSBuildLoadContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared.FileSystem; @@ -79,22 +79,22 @@ public MSBuildLoadContext(string assemblyPath) // bare search directory if that fails. : new[] { assemblyName.CultureName, string.Empty }) { - var candidatePath = Path.Combine(_directory, - cultureSubfolder, - $"{assemblyName.Name}.dll"); - - if (!FileSystems.Default.FileExists(candidatePath)) - { - continue; - } - - AssemblyName candidateAssemblyName = AssemblyLoadContext.GetAssemblyName(candidatePath); - if (candidateAssemblyName.Version != assemblyName.Version) - { - continue; - } - - return LoadFromAssemblyPath(candidatePath); + var candidatePath = Path.Combine(_directory, + cultureSubfolder, + $"{assemblyName.Name}.dll"); + + if (!FileSystems.Default.FileExists(candidatePath)) + { + continue; + } + + AssemblyName candidateAssemblyName = AssemblyLoadContext.GetAssemblyName(candidatePath); + if (candidateAssemblyName.Version != assemblyName.Version) + { + continue; + } + + return LoadFromAssemblyPath(candidatePath); } // If the Assembly is provided via a file path, the following rules are used to load the assembly: diff --git a/src/Shared/MSBuildNameIgnoreCaseComparer.cs b/src/Shared/MSBuildNameIgnoreCaseComparer.cs index f02c8c5cada..9517b5f2646 100644 --- a/src/Shared/MSBuildNameIgnoreCaseComparer.cs +++ b/src/Shared/MSBuildNameIgnoreCaseComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/MetadataConversionUtilities.cs b/src/Shared/MetadataConversionUtilities.cs index 5a3a4e02017..a6c121a1f52 100644 --- a/src/Shared/MetadataConversionUtilities.cs +++ b/src/Shared/MetadataConversionUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -24,12 +24,10 @@ internal static class MetadataConversionUtilities /// The name of the metadata. /// Receives true if the metadata was found, false otherwise. /// The resulting boolean value. - internal static bool TryConvertItemMetadataToBool - ( + internal static bool TryConvertItemMetadataToBool( ITaskItem item, string itemMetadataName, - out bool metadataFound - ) + out bool metadataFound) { string metadataValue = item.GetMetadata(itemMetadataName); if (string.IsNullOrEmpty(metadataValue)) @@ -58,11 +56,9 @@ out bool metadataFound /// The item that contains the metadata. /// The name of the metadata. /// The resulting boolean value. - internal static bool TryConvertItemMetadataToBool - ( + internal static bool TryConvertItemMetadataToBool( ITaskItem item, - string itemMetadataName - ) + string itemMetadataName) { bool metadataFound; return TryConvertItemMetadataToBool(item, itemMetadataName, out metadataFound); diff --git a/src/Shared/Modifiers.cs b/src/Shared/Modifiers.cs index 6905d0838a2..24ed8cc9a85 100644 --- a/src/Shared/Modifiers.cs +++ b/src/Shared/Modifiers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -17,12 +17,12 @@ namespace Microsoft.Build.Shared /// /// Partial class in order to reduce the amount of sharing into different assemblies /// - static internal partial class FileUtilities + internal static partial class FileUtilities { /// /// Encapsulates the definitions of the item-spec modifiers a.k.a. reserved item metadata. /// - static internal class ItemSpecModifiers + internal static class ItemSpecModifiers { #if DEBUG /// @@ -563,11 +563,9 @@ internal static string GetItemSpecModifier(string currentDirectory, string itemS if (string.Equals(modifier, FileUtilities.ItemSpecModifiers.DefiningProjectDirectory, StringComparison.OrdinalIgnoreCase)) { // ItemSpecModifiers.Directory does not contain the root directory - modifiedItemSpec = Path.Combine - ( + modifiedItemSpec = Path.Combine( GetItemSpecModifier(currentDirectory, definingProjectEscaped, null, ItemSpecModifiers.RootDir), - GetItemSpecModifier(currentDirectory, definingProjectEscaped, null, ItemSpecModifiers.Directory) - ); + GetItemSpecModifier(currentDirectory, definingProjectEscaped, null, ItemSpecModifiers.Directory)); } else { diff --git a/src/Shared/NGen.cs b/src/Shared/NGen.cs index d8e7750ef1a..f37252e7049 100644 --- a/src/Shared/NGen.cs +++ b/src/Shared/NGen.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/NamedPipeUtil.cs b/src/Shared/NamedPipeUtil.cs index 4927b87103d..5c5290b40c8 100644 --- a/src/Shared/NamedPipeUtil.cs +++ b/src/Shared/NamedPipeUtil.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; using System.IO; diff --git a/src/Shared/NodeBuildComplete.cs b/src/Shared/NodeBuildComplete.cs index f057cac41ef..50c62b7cfd0 100644 --- a/src/Shared/NodeBuildComplete.cs +++ b/src/Shared/NodeBuildComplete.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; diff --git a/src/Shared/NodeEndpointOutOfProcBase.cs b/src/Shared/NodeEndpointOutOfProcBase.cs index aefd4aaebb2..ac7f5509236 100644 --- a/src/Shared/NodeEndpointOutOfProcBase.cs +++ b/src/Shared/NodeEndpointOutOfProcBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; #if CLR2COMPATIBILITY @@ -31,7 +31,7 @@ namespace Microsoft.Build.BackEnd /// internal abstract class NodeEndpointOutOfProcBase : INodeEndpoint { -#region Private Data + #region Private Data #if NETCOREAPP2_1_OR_GREATER || MONO /// @@ -113,18 +113,18 @@ internal abstract class NodeEndpointOutOfProcBase : INodeEndpoint /// private BinaryWriter _binaryWriter; -#endregion + #endregion -#region INodeEndpoint Events + #region INodeEndpoint Events /// /// Raised when the link status has changed. /// public event LinkStatusChangedDelegate OnLinkStatusChanged; -#endregion + #endregion -#region INodeEndpoint Properties + #region INodeEndpoint Properties /// /// Returns the link status of this node. @@ -134,13 +134,13 @@ public LinkStatus LinkStatus get { return _status; } } -#endregion + #endregion -#region Properties + #region Properties -#endregion + #endregion -#region INodeEndpoint Methods + #region INodeEndpoint Methods /// /// Causes this endpoint to wait for the remote endpoint to connect @@ -193,9 +193,9 @@ public void ClientWillDisconnect() _isClientDisconnecting = true; } -#endregion + #endregion -#region Construction + #region Construction /// /// Instantiates an endpoint to act as a client @@ -226,8 +226,7 @@ internal void InternalConstruct(string pipeName = null) security.AddAccessRule(rule); security.SetOwner(identifier); - _pipeServer = new NamedPipeServerStream - ( + _pipeServer = new NamedPipeServerStream( pipeName, PipeDirection.InOut, 1, // Only allow one connection at a time. @@ -240,14 +239,12 @@ internal void InternalConstruct(string pipeName = null) PipeBufferSize, // Default input buffer PipeBufferSize, // Default output buffer security, - HandleInheritability.None - ); + HandleInheritability.None); } else #endif { - _pipeServer = new NamedPipeServerStream - ( + _pipeServer = new NamedPipeServerStream( pipeName, PipeDirection.InOut, 1, // Only allow one connection at a time. @@ -258,12 +255,11 @@ internal void InternalConstruct(string pipeName = null) #endif , PipeBufferSize, // Default input buffer - PipeBufferSize // Default output buffer - ); - } + PipeBufferSize); // Default output buffer + } } -#endregion + #endregion /// /// Returns the host handshake for this node endpoint @@ -291,7 +287,7 @@ private void RaiseLinkStatusChanged(LinkStatus newStatus) OnLinkStatusChanged?.Invoke(this, newStatus); } -#region Private Methods + #region Private Methods /// /// This does the actual work of changing the status and shutting down any threads we may have for @@ -312,7 +308,7 @@ private void InternalDisconnect() ChangeLinkStatus(LinkStatus.Inactive); } -#region Asynchronous Mode Methods + #region Asynchronous Mode Methods /// /// Adds a packet to the packet queue when asynchronous mode is enabled. @@ -403,11 +399,14 @@ private void PacketPumpProc() int[] handshakeComponents = handshake.RetrieveHandshakeComponents(); for (int i = 0; i < handshakeComponents.Length; i++) { - int handshakePart = _pipeServer.ReadIntForHandshake(i == 0 ? (byte?)CommunicationsUtilities.handshakeVersion : null /* this will disconnect a < 16.8 host; it expects leading 00 or F5 or 06. 0x00 is a wildcard */ +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + int handshakePart = _pipeServer.ReadIntForHandshake( + byteToAccept: i == 0 ? (byte?)CommunicationsUtilities.handshakeVersion : null /* this will disconnect a < 16.8 host; it expects leading 00 or F5 or 06. 0x00 is a wildcard */ #if NETCOREAPP2_1_OR_GREATER || MONO , ClientConnectTimeout /* wait a long time for the handshake from this side */ #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter if (handshakePart != handshakeComponents[i]) { @@ -454,7 +453,7 @@ private void PacketPumpProc() // 2. The host is too old sending us bits we automatically reject in the handshake // 3. We expected to read the EndOfHandshake signal, but we received something else CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message); - + gotValidConnection = false; } catch (InvalidOperationException) @@ -676,8 +675,8 @@ private void RunReadLoop(Stream localReadPipe, Stream localWritePipe, while (!exitLoop); } -#endregion + #endregion -#endregion + #endregion } } diff --git a/src/Shared/NodeEngineShutdownReason.cs b/src/Shared/NodeEngineShutdownReason.cs index 854a3033ba0..dc4f0f3069c 100644 --- a/src/Shared/NodeEngineShutdownReason.cs +++ b/src/Shared/NodeEngineShutdownReason.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/NodePacketFactory.cs b/src/Shared/NodePacketFactory.cs index c35e728860f..214ddfa20f9 100644 --- a/src/Shared/NodePacketFactory.cs +++ b/src/Shared/NodePacketFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Shared; diff --git a/src/Shared/NodeShutdown.cs b/src/Shared/NodeShutdown.cs index 1c6af10afec..9ce9426799e 100644 --- a/src/Shared/NodeShutdown.cs +++ b/src/Shared/NodeShutdown.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Shared/OutOfProcTaskHostTaskResult.cs b/src/Shared/OutOfProcTaskHostTaskResult.cs index c08d6bb0c34..f1f86a48ac6 100644 --- a/src/Shared/OutOfProcTaskHostTaskResult.cs +++ b/src/Shared/OutOfProcTaskHostTaskResult.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -67,13 +67,11 @@ internal OutOfProcTaskHostTaskResult(TaskCompleteType result, IDictionary 0) diff --git a/src/Shared/Pair.cs b/src/Shared/Pair.cs index 06b8b774508..85e688acb50 100644 --- a/src/Shared/Pair.cs +++ b/src/Shared/Pair.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; diff --git a/src/Shared/PlatformNegotiation.cs b/src/Shared/PlatformNegotiation.cs index d3ff339ced3..4a3faba5c34 100644 --- a/src/Shared/PlatformNegotiation.cs +++ b/src/Shared/PlatformNegotiation.cs @@ -1,3 +1,6 @@ +// 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.Collections.Generic; using Microsoft.Build.Framework; @@ -21,71 +24,71 @@ internal static string GetNearestPlatform(string referencedProjectPlatform, stri Dictionary? currentProjectLookupTable = ExtractLookupTable(platformLookupTable, log); if (string.IsNullOrEmpty(projectReferencePlatformsMetadata) && string.IsNullOrEmpty(referencedProjectPlatform)) - { - log?.LogWarningWithCodeFromResources("GetCompatiblePlatform.NoPlatformsListed", projectPath); - return string.Empty; - } + { + log?.LogWarningWithCodeFromResources("GetCompatiblePlatform.NoPlatformsListed", projectPath); + return string.Empty; + } - // Pull platformLookupTable metadata from the referenced project. This allows custom - // mappings on a per-ProjectReference basis. - Dictionary? projectReferenceLookupTable = ExtractLookupTable(projectReferenceLookupTableMetadata, log); + // Pull platformLookupTable metadata from the referenced project. This allows custom + // mappings on a per-ProjectReference basis. + Dictionary? projectReferenceLookupTable = ExtractLookupTable(projectReferenceLookupTableMetadata, log); - HashSet projectReferencePlatforms = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string s in projectReferencePlatformsMetadata.Split(MSBuildConstants.SemicolonChar, StringSplitOptions.RemoveEmptyEntries)) - { - projectReferencePlatforms.Add(s); - } + HashSet projectReferencePlatforms = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string s in projectReferencePlatformsMetadata.Split(MSBuildConstants.SemicolonChar, StringSplitOptions.RemoveEmptyEntries)) + { + projectReferencePlatforms.Add(s); + } - string buildProjectReferenceAs = string.Empty; + string buildProjectReferenceAs = string.Empty; - // If the referenced project has a defined `Platform` that's compatible, it will build that way by default. - // Don't set `buildProjectReferenceAs` and the `_GetProjectReferencePlatformProperties` target will handle the rest. - if (!string.IsNullOrEmpty(referencedProjectPlatform) && referencedProjectPlatform.Equals(currentProjectPlatform, StringComparison.OrdinalIgnoreCase)) - { - log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.ReferencedProjectHasDefinitivePlatform", projectPath, referencedProjectPlatform); - } - // Prefer matching platforms - else if (projectReferencePlatforms.Contains(currentProjectPlatform)) - { - buildProjectReferenceAs = currentProjectPlatform; - log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.SamePlatform"); - } - // Prioritize platformLookupTable **metadata** attached to the ProjectReference item - // before the current project's table. We do this to allow per-ProjectReference fine tuning. - else if (projectReferenceLookupTable != null && - projectReferenceLookupTable.ContainsKey(currentProjectPlatform) && - projectReferencePlatforms.Contains(projectReferenceLookupTable[currentProjectPlatform])) - { - buildProjectReferenceAs = projectReferenceLookupTable[currentProjectPlatform]; - log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.FoundMappingInTable", currentProjectPlatform, buildProjectReferenceAs, projectReferenceLookupTableMetadata); - } - // Current project's translation table follows - else if (currentProjectLookupTable != null && - currentProjectLookupTable.ContainsKey(currentProjectPlatform) && - projectReferencePlatforms.Contains(currentProjectLookupTable[currentProjectPlatform])) - { - buildProjectReferenceAs = currentProjectLookupTable[currentProjectPlatform]; - log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.FoundMappingInTable", currentProjectPlatform, buildProjectReferenceAs, platformLookupTable); - } - // AnyCPU if possible - else if (projectReferencePlatforms.Contains("AnyCPU")) - { - buildProjectReferenceAs = "AnyCPU"; - log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.AnyCPUDefault"); - } - else - { - // Keep NearestPlatform empty, log a warning. Common.CurrentVersion.targets will undefine - // Platform/PlatformTarget when this is the case. - log?.LogWarningWithCodeFromResources("GetCompatiblePlatform.NoCompatiblePlatformFound", projectPath); - } - // If the referenced project has a defined `Platform` that's compatible, it will build that way by default. - // If we're about to tell the reference to build using its default platform, don't pass it as a global property. - if (!string.IsNullOrEmpty(referencedProjectPlatform) && referencedProjectPlatform.Equals(buildProjectReferenceAs, StringComparison.OrdinalIgnoreCase)) - { - log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.ReferencedProjectHasDefinitivePlatform", projectPath, referencedProjectPlatform); - buildProjectReferenceAs = string.Empty; - } + // If the referenced project has a defined `Platform` that's compatible, it will build that way by default. + // Don't set `buildProjectReferenceAs` and the `_GetProjectReferencePlatformProperties` target will handle the rest. + if (!string.IsNullOrEmpty(referencedProjectPlatform) && referencedProjectPlatform.Equals(currentProjectPlatform, StringComparison.OrdinalIgnoreCase)) + { + log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.ReferencedProjectHasDefinitivePlatform", projectPath, referencedProjectPlatform); + } + // Prefer matching platforms + else if (projectReferencePlatforms.Contains(currentProjectPlatform)) + { + buildProjectReferenceAs = currentProjectPlatform; + log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.SamePlatform"); + } + // Prioritize platformLookupTable **metadata** attached to the ProjectReference item + // before the current project's table. We do this to allow per-ProjectReference fine tuning. + else if (projectReferenceLookupTable != null && + projectReferenceLookupTable.ContainsKey(currentProjectPlatform) && + projectReferencePlatforms.Contains(projectReferenceLookupTable[currentProjectPlatform])) + { + buildProjectReferenceAs = projectReferenceLookupTable[currentProjectPlatform]; + log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.FoundMappingInTable", currentProjectPlatform, buildProjectReferenceAs, projectReferenceLookupTableMetadata); + } + // Current project's translation table follows + else if (currentProjectLookupTable != null && + currentProjectLookupTable.ContainsKey(currentProjectPlatform) && + projectReferencePlatforms.Contains(currentProjectLookupTable[currentProjectPlatform])) + { + buildProjectReferenceAs = currentProjectLookupTable[currentProjectPlatform]; + log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.FoundMappingInTable", currentProjectPlatform, buildProjectReferenceAs, platformLookupTable); + } + // AnyCPU if possible + else if (projectReferencePlatforms.Contains("AnyCPU")) + { + buildProjectReferenceAs = "AnyCPU"; + log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.AnyCPUDefault"); + } + else + { + // Keep NearestPlatform empty, log a warning. Common.CurrentVersion.targets will undefine + // Platform/PlatformTarget when this is the case. + log?.LogWarningWithCodeFromResources("GetCompatiblePlatform.NoCompatiblePlatformFound", projectPath); + } + // If the referenced project has a defined `Platform` that's compatible, it will build that way by default. + // If we're about to tell the reference to build using its default platform, don't pass it as a global property. + if (!string.IsNullOrEmpty(referencedProjectPlatform) && referencedProjectPlatform.Equals(buildProjectReferenceAs, StringComparison.OrdinalIgnoreCase)) + { + log?.LogMessageFromResources(MessageImportance.Low, "GetCompatiblePlatform.ReferencedProjectHasDefinitivePlatform", projectPath, referencedProjectPlatform); + buildProjectReferenceAs = string.Empty; + } return buildProjectReferenceAs; } internal static Dictionary? ExtractLookupTable(string stringTable, TaskLoggingHelper? log = null) diff --git a/src/Shared/ProcessExtensions.cs b/src/Shared/ProcessExtensions.cs index 67025e4d7b5..260d12cc5d2 100644 --- a/src/Shared/ProcessExtensions.cs +++ b/src/Shared/ProcessExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/ProjectErrorUtilities.cs b/src/Shared/ProjectErrorUtilities.cs index e44989600e0..17e7fd9a914 100644 --- a/src/Shared/ProjectErrorUtilities.cs +++ b/src/Shared/ProjectErrorUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** @@ -36,12 +36,10 @@ internal static class ProjectErrorUtilities /// The condition to check. /// The of the element. /// The resource string for the error message. - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, IElementLocation elementLocation, - string resourceName - ) + string resourceName) { VerifyThrowInvalidProject(condition, null, elementLocation, resourceName); } @@ -52,12 +50,10 @@ string resourceName /// The of the element. /// The resource string for the error message. /// - internal static void ThrowInvalidProject - ( + internal static void ThrowInvalidProject( IElementLocation elementLocation, string resourceName, - T1 arg0 - ) + T1 arg0) { ThrowInvalidProject(null, elementLocation, resourceName, arg0); } @@ -69,13 +65,11 @@ T1 arg0 /// The of the element. /// The resource string for the error message. /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, IElementLocation elementLocation, string resourceName, - T1 arg0 - ) + T1 arg0) { VerifyThrowInvalidProject(condition, null, elementLocation, resourceName, arg0); } @@ -87,13 +81,11 @@ T1 arg0 /// The resource string for the error message. /// /// - internal static void ThrowInvalidProject - ( + internal static void ThrowInvalidProject( IElementLocation elementLocation, string resourceName, T1 arg0, - T2 arg1 - ) + T2 arg1) { ThrowInvalidProject(null, elementLocation, resourceName, arg0, arg1); } @@ -106,14 +98,12 @@ T2 arg1 /// /// /// - internal static void ThrowInvalidProject - ( + internal static void ThrowInvalidProject( IElementLocation elementLocation, string resourceName, T1 arg0, T2 arg1, - T3 arg2 - ) + T3 arg2) { ThrowInvalidProject(null, elementLocation, resourceName, arg0, arg1, arg2); } @@ -127,15 +117,13 @@ T3 arg2 /// /// /// - internal static void ThrowInvalidProject - ( + internal static void ThrowInvalidProject( IElementLocation elementLocation, string resourceName, T1 arg0, T2 arg1, T3 arg2, - T4 arg3 - ) + T4 arg3) { ThrowInvalidProject(null, elementLocation, resourceName, arg0, arg1, arg2, arg3); } @@ -146,12 +134,10 @@ T4 arg3 /// The of the element. /// The resource string for the error message. /// - internal static void ThrowInvalidProject - ( + internal static void ThrowInvalidProject( IElementLocation elementLocation, string resourceName, - params object[] args - ) + params object[] args) { ThrowInvalidProject(null, elementLocation, resourceName, args); } @@ -164,14 +150,12 @@ params object[] args /// The resource string for the error message. /// /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, IElementLocation elementLocation, string resourceName, T1 arg0, - T2 arg1 - ) + T2 arg1) { VerifyThrowInvalidProject(condition, null, elementLocation, resourceName, arg0, arg1); } @@ -185,15 +169,13 @@ T2 arg1 /// /// /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, IElementLocation elementLocation, string resourceName, T1 arg0, T2 arg1, - T3 arg2 - ) + T3 arg2) { VerifyThrowInvalidProject(condition, null, elementLocation, resourceName, arg0, arg1, arg2); } @@ -208,16 +190,14 @@ T3 arg2 /// /// /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, IElementLocation elementLocation, string resourceName, T1 arg0, T2 arg1, T3 arg2, - T4 arg3 - ) + T4 arg3) { VerifyThrowInvalidProject(condition, null, elementLocation, resourceName, arg0, arg1, arg2, arg3); } @@ -232,13 +212,11 @@ T4 arg3 /// error sub-category (can be null). /// The of the element. /// The resource string for the error message. - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, string errorSubCategoryResourceName, IElementLocation elementLocation, - string resourceName - ) + string resourceName) { if (!condition) { @@ -257,14 +235,12 @@ string resourceName /// The of the element. /// The resource string for the error message. /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, string errorSubCategoryResourceName, IElementLocation elementLocation, string resourceName, - T1 arg0 - ) + T1 arg0) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidProject() method, because that method always @@ -285,15 +261,13 @@ T1 arg0 /// The resource string for the error message. /// /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, string errorSubCategoryResourceName, IElementLocation elementLocation, string resourceName, T1 arg0, - T2 arg1 - ) + T2 arg1) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidProject() method, because that method always @@ -315,16 +289,14 @@ T2 arg1 /// /// /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, string errorSubCategoryResourceName, IElementLocation elementLocation, string resourceName, T1 arg0, T2 arg1, - T3 arg2 - ) + T3 arg2) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidProject() method, because that method always @@ -347,8 +319,7 @@ T3 arg2 /// /// /// - internal static void VerifyThrowInvalidProject - ( + internal static void VerifyThrowInvalidProject( bool condition, string errorSubCategoryResourceName, IElementLocation elementLocation, @@ -356,8 +327,7 @@ internal static void VerifyThrowInvalidProject T1 arg0, T2 arg1, T3 arg2, - T4 arg3 - ) + T4 arg3) { // PERF NOTE: check the condition here instead of pushing it into // the ThrowInvalidProject() method, because that method always @@ -381,13 +351,11 @@ T4 arg3 /// The of the element. /// The resource string for the error message. /// Extra arguments for formatting the error message. - private static void ThrowInvalidProject - ( + private static void ThrowInvalidProject( string errorSubCategoryResourceName, IElementLocation elementLocation, string resourceName, - params object[] args - ) + params object[] args) { ErrorUtilities.VerifyThrowInternalNull(elementLocation, nameof(elementLocation)); #if DEBUG diff --git a/src/Shared/ProjectFileErrorUtilities.cs b/src/Shared/ProjectFileErrorUtilities.cs index aa8bc142a3a..c6875603ce0 100644 --- a/src/Shared/ProjectFileErrorUtilities.cs +++ b/src/Shared/ProjectFileErrorUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -12,7 +12,7 @@ namespace Microsoft.Build.Shared /// /// This class contains methods that are useful for error checking and validation of project files. /// - static internal class ProjectFileErrorUtilities + internal static class ProjectFileErrorUtilities { /// /// This method is used to flag errors in the project file being processed. Do NOT use this method in place of @@ -24,12 +24,10 @@ static internal class ProjectFileErrorUtilities /// The invalid project file. /// The resource string for the error message. /// Extra arguments for formatting the error message. - internal static void ThrowInvalidProjectFile - ( + internal static void ThrowInvalidProjectFile( BuildEventFileInfo projectFile, string resourceName, - params object[] args - ) + params object[] args) { ThrowInvalidProjectFile(null, projectFile, resourceName, args); } @@ -45,13 +43,11 @@ params object[] args /// Any inner exception. May be null. /// The resource string for the error message. /// Extra arguments for formatting the error message. - internal static void ThrowInvalidProjectFile - ( + internal static void ThrowInvalidProjectFile( BuildEventFileInfo projectFile, Exception innerException, string resourceName, - params object[] args - ) + params object[] args) { VerifyThrowInvalidProjectFile(false, null, projectFile, innerException, resourceName, args); } @@ -67,13 +63,11 @@ params object[] args /// The invalid project file. /// The resource string for the error message. /// Extra arguments for formatting the error message. - internal static void VerifyThrowInvalidProjectFile - ( + internal static void VerifyThrowInvalidProjectFile( bool condition, BuildEventFileInfo projectFile, string resourceName, - params object[] args - ) + params object[] args) { VerifyThrowInvalidProjectFile(condition, null, projectFile, resourceName, args); } @@ -89,13 +83,11 @@ params object[] args /// The invalid project file. /// The resource string for the error message. /// Extra arguments for formatting the error message. - internal static void ThrowInvalidProjectFile - ( + internal static void ThrowInvalidProjectFile( string errorSubCategoryResourceName, BuildEventFileInfo projectFile, string resourceName, - params object[] args - ) + params object[] args) { VerifyThrowInvalidProjectFile(false, errorSubCategoryResourceName, projectFile, null, resourceName, args); } @@ -112,14 +104,12 @@ params object[] args /// The invalid project file. /// The resource string for the error message. /// Extra arguments for formatting the error message. - internal static void VerifyThrowInvalidProjectFile - ( + internal static void VerifyThrowInvalidProjectFile( bool condition, string errorSubCategoryResourceName, BuildEventFileInfo projectFile, string resourceName, - params object[] args - ) + params object[] args) { VerifyThrowInvalidProjectFile(condition, errorSubCategoryResourceName, projectFile, null, resourceName, args); } @@ -137,15 +127,13 @@ params object[] args /// The inner . /// The resource string for the error message. /// Extra arguments for formatting the error message. - internal static void VerifyThrowInvalidProjectFile - ( + internal static void VerifyThrowInvalidProjectFile( bool condition, string errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, string resourceName, - params object[] args - ) + params object[] args) { ErrorUtilities.VerifyThrow(projectFile != null, "Must specify the invalid project file. If project file is not available, use VerifyThrowInvalidProject() and pass in the XML node instead."); diff --git a/src/Shared/ProjectWriter.cs b/src/Shared/ProjectWriter.cs index 66f197081ec..bcbcf374cb2 100644 --- a/src/Shared/ProjectWriter.cs +++ b/src/Shared/ProjectWriter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Shared/PropertyParser.cs b/src/Shared/PropertyParser.cs index 607b92a1841..8144cc22191 100644 --- a/src/Shared/PropertyParser.cs +++ b/src/Shared/PropertyParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/QuotingUtilities.cs b/src/Shared/QuotingUtilities.cs index 72eca743bf6..eb25b416f0a 100644 --- a/src/Shared/QuotingUtilities.cs +++ b/src/Shared/QuotingUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; @@ -61,15 +61,13 @@ internal static class QuotingUtilities /// [out] a count of all pieces that were empty, and thus discarded, per remark (1) above /// /// ArrayList of all the pieces the string was split into. - internal static List SplitUnquoted - ( + internal static List SplitUnquoted( string input, int maxSplits, bool keepEmptySplits, bool unquote, out int emptySplits, - params char[] separator - ) + params char[] separator) { ErrorUtilities.VerifyThrow(maxSplits >= 2, "There is no point calling this method for less than two splits."); diff --git a/src/Shared/ReadOnlyCollection.cs b/src/Shared/ReadOnlyCollection.cs index 69454ab1b1d..452b28889d2 100644 --- a/src/Shared/ReadOnlyCollection.cs +++ b/src/Shared/ReadOnlyCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/ReadOnlyEmptyCollection.cs b/src/Shared/ReadOnlyEmptyCollection.cs index 76bbf5f5834..a29a5f75867 100644 --- a/src/Shared/ReadOnlyEmptyCollection.cs +++ b/src/Shared/ReadOnlyEmptyCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/ReadOnlyEmptyDictionary.cs b/src/Shared/ReadOnlyEmptyDictionary.cs index ced752ddd33..e4b1662bdeb 100644 --- a/src/Shared/ReadOnlyEmptyDictionary.cs +++ b/src/Shared/ReadOnlyEmptyDictionary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Shared/RegisteredTaskObjectCacheBase.cs b/src/Shared/RegisteredTaskObjectCacheBase.cs index 543cdc44891..7677de76590 100644 --- a/src/Shared/RegisteredTaskObjectCacheBase.cs +++ b/src/Shared/RegisteredTaskObjectCacheBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Shared/RegistryDelegates.cs b/src/Shared/RegistryDelegates.cs index 4883342d33f..a3eb5d25133 100644 --- a/src/Shared/RegistryDelegates.cs +++ b/src/Shared/RegistryDelegates.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32; using System.Collections.Generic; @@ -7,8 +7,8 @@ namespace Microsoft.Build.Shared { /// - /// Given a registry hive and a request view open the base key for that registry location. - /// + /// Given a registry hive and a request view open the base key for that registry location. + /// internal delegate RegistryKey OpenBaseKey(RegistryHive hive, RegistryView view); /// diff --git a/src/Shared/RegistryHelper.cs b/src/Shared/RegistryHelper.cs index fc26fd09f82..43b846f2478 100644 --- a/src/Shared/RegistryHelper.cs +++ b/src/Shared/RegistryHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.Versioning; diff --git a/src/Shared/ResourceUtilities.cs b/src/Shared/ResourceUtilities.cs index bf7fe3035c8..f6d9799f15f 100644 --- a/src/Shared/ResourceUtilities.cs +++ b/src/Shared/ResourceUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; #if !BUILDINGAPPXTASKS && DEBUG @@ -62,8 +62,7 @@ internal static string ExtractMessageCode(bool msbuildCodeOnly, string message, message[i + 4] < '0' || message[i + 4] > '9' || message[i + 5] < '0' || message[i + 5] > '9' || message[i + 6] < '0' || message[i + 6] > '9' || - message[i + 7] != ':' - ) + message[i + 7] != ':') { return message; } diff --git a/src/Shared/StringExtensions.cs b/src/Shared/StringExtensions.cs index e6009bfd5ef..40485f659b3 100644 --- a/src/Shared/StringExtensions.cs +++ b/src/Shared/StringExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/Shared/StrongNameHelpers.cs b/src/Shared/StrongNameHelpers.cs index d176b2c40a8..f72147f976d 100644 --- a/src/Shared/StrongNameHelpers.cs +++ b/src/Shared/StrongNameHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_STRONG_NAMES diff --git a/src/Shared/TaskEngineAssemblyResolver.cs b/src/Shared/TaskEngineAssemblyResolver.cs index 9a09e33310d..6f8cf5157d8 100644 --- a/src/Shared/TaskEngineAssemblyResolver.cs +++ b/src/Shared/TaskEngineAssemblyResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -63,7 +63,7 @@ internal void InstallHandler() #endif } - + /// /// Removes the event handler. diff --git a/src/Shared/TaskHostConfiguration.cs b/src/Shared/TaskHostConfiguration.cs index 7037787b2fe..822495b0179 100644 --- a/src/Shared/TaskHostConfiguration.cs +++ b/src/Shared/TaskHostConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -141,8 +141,7 @@ internal class TaskHostConfiguration : INodePacket /// Warning codes not to be treated as errors for the current project. /// Warning codes to be treated as messages for the current project. #endif - public TaskHostConfiguration - ( + public TaskHostConfiguration( int nodeId, string startupDirectory, IDictionary buildProcessEnvironment, @@ -162,8 +161,7 @@ public TaskHostConfiguration Dictionary globalParameters, ICollection warningsAsErrors, ICollection warningsNotAsErrors, - ICollection warningsAsMessages - ) + ICollection warningsAsMessages) { ErrorUtilities.VerifyThrowInternalLength(taskName, nameof(taskName)); ErrorUtilities.VerifyThrowInternalLength(taskLocation, nameof(taskLocation)); diff --git a/src/Shared/TaskHostTaskCancelled.cs b/src/Shared/TaskHostTaskCancelled.cs index 597607cc4db..d357e55b94a 100644 --- a/src/Shared/TaskHostTaskCancelled.cs +++ b/src/Shared/TaskHostTaskCancelled.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/TaskHostTaskComplete.cs b/src/Shared/TaskHostTaskComplete.cs index de13737cb1b..faad07dd31e 100644 --- a/src/Shared/TaskHostTaskComplete.cs +++ b/src/Shared/TaskHostTaskComplete.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/TaskLoader.cs b/src/Shared/TaskLoader.cs index f66497dc018..0dcfd58ba9d 100644 --- a/src/Shared/TaskLoader.cs +++ b/src/Shared/TaskLoader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -42,15 +42,23 @@ internal static bool IsTaskClass(Type type, object unused) /// /// Creates an ITask instance and returns it. /// - internal static ITask CreateTask(LoadedType loadedType, string taskName, string taskLocation, int taskLine, int taskColumn, LogError logError +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter + internal static ITask CreateTask( + LoadedType loadedType, + string taskName, + string taskLocation, + int taskLine, + int taskColumn, + LogError logError, #if FEATURE_APPDOMAIN - , AppDomainSetup appDomainSetup + AppDomainSetup appDomainSetup, #endif - , bool isOutOfProc + bool isOutOfProc #if FEATURE_APPDOMAIN , out AppDomain taskAppDomain #endif ) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { #if FEATURE_APPDOMAIN bool separateAppDomain = loadedType.HasLoadInSeparateAppDomainAttribute; @@ -66,14 +74,12 @@ internal static ITask CreateTask(LoadedType loadedType, string taskName, string { if (!loadedType.IsMarshalByRef) { - logError - ( + logError( taskLocation, taskLine, taskColumn, "TaskNotMarshalByRef", - taskName - ); + taskName); return null; } @@ -135,15 +141,13 @@ internal static ITask CreateTask(LoadedType loadedType, string taskName, string // to fail here. if (taskType != loadedType.Type) { - logError - ( + logError( taskLocation, taskLine, taskColumn, "ConflictingTaskAssembly", loadedType.Assembly.AssemblyFile, - loadedType.Type.GetTypeInfo().Assembly.Location - ); + loadedType.Type.GetTypeInfo().Assembly.Location); taskInstanceInOtherAppDomain = null; } diff --git a/src/Shared/TaskLoggingHelper.cs b/src/Shared/TaskLoggingHelper.cs index ff2b4901582..e3a4a2b9f7d 100644 --- a/src/Shared/TaskLoggingHelper.cs +++ b/src/Shared/TaskLoggingHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -303,15 +303,13 @@ public void LogMessage(MessageImportance importance, string message, params obje return; } - BuildMessageEventArgs e = new BuildMessageEventArgs - ( + BuildMessageEventArgs e = new BuildMessageEventArgs( message, helpKeyword: null, senderName: TaskName, importance, DateTime.UtcNow, - messageArgs - ); + messageArgs); // If BuildEngine is null, task attempted to log before it was set on it, // presumably in its constructor. This is not allowed, and all @@ -348,8 +346,7 @@ public void LogMessage(MessageImportance importance, string message, params obje /// The message string. /// Optional arguments for formatting the message string. /// Thrown when message is null. - public void LogMessage - ( + public void LogMessage( string subcategory, string code, string helpKeyword, @@ -360,8 +357,7 @@ public void LogMessage int endColumnNumber, MessageImportance importance, string message, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as BuildEngine methods from v4.5 onwards are thread safe. ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message)); @@ -380,8 +376,7 @@ params object[] messageArgs // that gives the user something. bool fillInLocation = (String.IsNullOrEmpty(file) && (lineNumber == 0) && (columnNumber == 0)); - var e = new BuildMessageEventArgs - ( + var e = new BuildMessageEventArgs( subcategory, code, fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file, @@ -394,8 +389,7 @@ params object[] messageArgs TaskName, importance, DateTime.UtcNow, - messageArgs - ); + messageArgs); BuildEngine.LogMessageEvent(e); } @@ -415,8 +409,7 @@ params object[] messageArgs /// The message string. /// Optional arguments for formatting the message string. /// Thrown when message is null. - public void LogCriticalMessage - ( + public void LogCriticalMessage( string subcategory, string code, string helpKeyword, @@ -426,8 +419,7 @@ public void LogCriticalMessage int endLineNumber, int endColumnNumber, string message, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as BuildEngine methods from v4.5 onwards are thread safe. ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message)); @@ -441,8 +433,7 @@ params object[] messageArgs // that gives the user something. bool fillInLocation = (String.IsNullOrEmpty(file) && (lineNumber == 0) && (columnNumber == 0)); - var e = new CriticalBuildMessageEventArgs - ( + var e = new CriticalBuildMessageEventArgs( subcategory, code, fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file, @@ -454,8 +445,7 @@ params object[] messageArgs helpKeyword, TaskName, DateTime.UtcNow, - messageArgs - ); + messageArgs); BuildEngine.LogMessageEvent(e); } @@ -513,9 +503,9 @@ public void LogMessageFromResources(MessageImportance importance, string message #endif } -#endregion + #endregion -#region ExternalProjectStarted/Finished logging methods + #region ExternalProjectStarted/Finished logging methods /// /// Small helper for logging the custom ExternalProjectStarted build event @@ -525,13 +515,11 @@ public void LogMessageFromResources(MessageImportance importance, string message /// help keyword /// project name /// targets we are going to build (empty indicates default targets) - public void LogExternalProjectStarted - ( + public void LogExternalProjectStarted( string message, string helpKeyword, string projectFile, - string targetNames - ) + string targetNames) { // No lock needed, as BuildEngine methods from v4.5 onwards are thread safe. var eps = new ExternalProjectStartedEventArgs(message, helpKeyword, TaskName, projectFile, targetNames); @@ -546,22 +534,20 @@ string targetNames /// help keyword /// project name /// true indicates project built successfully - public void LogExternalProjectFinished - ( + public void LogExternalProjectFinished( string message, string helpKeyword, string projectFile, - bool succeeded - ) + bool succeeded) { // No lock needed, as BuildEngine methods from v4.5 onwards are thread safe. var epf = new ExternalProjectFinishedEventArgs(message, helpKeyword, TaskName, projectFile, succeeded); BuildEngine.LogCustomEvent(epf); } -#endregion + #endregion -#region Command line logging methods + #region Command line logging methods /// /// Logs the command line for a task's underlying tool/executable/shell command. @@ -603,9 +589,9 @@ public void LogCommandLine(MessageImportance importance, string commandLine) BuildEngine.LogMessageEvent(e); } -#endregion + #endregion -#region Error logging methods + #region Error logging methods /// /// Logs an error using the specified string. @@ -634,8 +620,7 @@ public void LogError(string message, params object[] messageArgs) /// The message string. /// Optional arguments for formatting the message string. /// Thrown when message is null. - public void LogError - ( + public void LogError( string subcategory, string errorCode, string helpKeyword, @@ -645,8 +630,7 @@ public void LogError int endLineNumber, int endColumnNumber, string message, - params object[] messageArgs - ) + params object[] messageArgs) { LogError(subcategory, errorCode, helpKeyword, null, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, messageArgs); } @@ -667,8 +651,7 @@ params object[] messageArgs /// A link pointing to more information about the error. /// Optional arguments for formatting the message string. /// Thrown when message is null. - public void LogError - ( + public void LogError( string subcategory, string errorCode, string helpKeyword, @@ -679,8 +662,7 @@ public void LogError int endLineNumber, int endColumnNumber, string message, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as BuildEngine methods from v4.5 onwards are thread safe. ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message)); @@ -700,8 +682,7 @@ params object[] messageArgs // that gives the user something. bool fillInLocation = (String.IsNullOrEmpty(file) && (lineNumber == 0) && (columnNumber == 0)); - var e = new BuildErrorEventArgs - ( + var e = new BuildErrorEventArgs( subcategory, errorCode, fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file, @@ -714,8 +695,7 @@ params object[] messageArgs TaskName, helpLink, DateTime.UtcNow, - messageArgs - ); + messageArgs); BuildEngine.LogErrorEvent(e); HasLoggedErrors = true; @@ -748,8 +728,7 @@ public void LogErrorFromResources(string messageResourceName, params object[] me /// The name of the string resource containing the error message. /// Optional arguments for formatting the loaded string. /// Thrown when messageResourceName is null. - public void LogErrorFromResources - ( + public void LogErrorFromResources( string subcategoryResourceName, string errorCode, string helpKeyword, @@ -759,8 +738,7 @@ public void LogErrorFromResources int endLineNumber, int endColumnNumber, string messageResourceName, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as the logging methods are thread safe and the rest does not modify // global state. @@ -784,8 +762,7 @@ params object[] messageArgs ErrorUtilities.VerifyThrow(string.IsNullOrEmpty(messageCode), "Called LogErrorFromResources instead of LogErrorWithCodeFromResources, but message '" + throwAwayMessageBody + "' does have an error code '" + messageCode + "'"); #endif - LogError - ( + LogError( subcategory, errorCode, helpKeyword, @@ -794,8 +771,7 @@ params object[] messageArgs columnNumber, endLineNumber, endColumnNumber, - FormatResourceString(messageResourceName, messageArgs) - ); + FormatResourceString(messageResourceName, messageArgs)); } /// @@ -837,8 +813,7 @@ public void LogErrorWithCodeFromResources(string messageResourceName, params obj /// The name of the string resource containing the error message. /// Optional arguments for formatting the loaded string. /// Thrown when messageResourceName is null. - public void LogErrorWithCodeFromResources - ( + public void LogErrorWithCodeFromResources( string subcategoryResourceName, string file, int lineNumber, @@ -846,8 +821,7 @@ public void LogErrorWithCodeFromResources int endLineNumber, int endColumnNumber, string messageResourceName, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as the logging methods are thread safe and the rest does not modify // global state. @@ -869,8 +843,7 @@ params object[] messageArgs helpKeyword = HelpKeywordPrefix + messageResourceName; } - LogError - ( + LogError( subcategory, errorCode, helpKeyword, @@ -879,8 +852,7 @@ params object[] messageArgs columnNumber, endLineNumber, endColumnNumber, - message - ); + message); } /// @@ -968,9 +940,9 @@ public void LogErrorFromException(Exception exception, bool showStackTrace, bool LogError(null, null, null, file, 0, 0, 0, 0, message); } -#endregion + #endregion -#region Warning logging methods + #region Warning logging methods /// /// Logs a warning using the specified string. @@ -999,8 +971,7 @@ public void LogWarning(string message, params object[] messageArgs) /// The message string. /// Optional arguments for formatting the message string. /// Thrown when message is null. - public void LogWarning - ( + public void LogWarning( string subcategory, string warningCode, string helpKeyword, @@ -1010,8 +981,7 @@ public void LogWarning int endLineNumber, int endColumnNumber, string message, - params object[] messageArgs - ) + params object[] messageArgs) { LogWarning(subcategory, warningCode, helpKeyword, null, file, lineNumber, columnNumber, endLineNumber, endColumnNumber, message, messageArgs); } @@ -1032,8 +1002,7 @@ params object[] messageArgs /// The message string. /// Optional arguments for formatting the message string. /// Thrown when message is null. - public void LogWarning - ( + public void LogWarning( string subcategory, string warningCode, string helpKeyword, @@ -1044,8 +1013,7 @@ public void LogWarning int endLineNumber, int endColumnNumber, string message, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as BuildEngine methods from v4.5 onwards are thread safe. ErrorUtilities.VerifyThrowArgumentNull(message, nameof(message)); @@ -1070,8 +1038,7 @@ params object[] messageArgs // 2. If WarningsAsErrors is a non-null empty set (treat all warnings as errors) if (BuildEngine is IBuildEngine8 be8 && be8.ShouldTreatWarningAsError(warningCode)) { - LogError - ( + LogError( subcategory: subcategory, errorCode: warningCode, helpKeyword: helpKeyword, @@ -1082,13 +1049,11 @@ params object[] messageArgs endLineNumber: endLineNumber, endColumnNumber: endColumnNumber, message: message, - messageArgs: messageArgs - ); + messageArgs: messageArgs); return; } - var e = new BuildWarningEventArgs - ( + var e = new BuildWarningEventArgs( subcategory, warningCode, fillInLocation ? BuildEngine.ProjectFileOfTaskNode : file, @@ -1101,8 +1066,7 @@ params object[] messageArgs TaskName, helpLink, DateTime.UtcNow, - messageArgs - ); + messageArgs); BuildEngine.LogWarningEvent(e); } @@ -1134,8 +1098,7 @@ public void LogWarningFromResources(string messageResourceName, params object[] /// The name of the string resource containing the warning message. /// Optional arguments for formatting the loaded string. /// Thrown when messageResourceName is null. - public void LogWarningFromResources - ( + public void LogWarningFromResources( string subcategoryResourceName, string warningCode, string helpKeyword, @@ -1145,8 +1108,7 @@ public void LogWarningFromResources int endLineNumber, int endColumnNumber, string messageResourceName, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as log methods are thread safe and the rest does not modify // global state. @@ -1168,8 +1130,7 @@ params object[] messageArgs ErrorUtilities.VerifyThrow(string.IsNullOrEmpty(messageCode), "Called LogWarningFromResources instead of LogWarningWithCodeFromResources, but message '" + throwAwayMessageBody + "' does have an error code '" + messageCode + "'"); #endif - LogWarning - ( + LogWarning( subcategory, warningCode, helpKeyword, @@ -1178,8 +1139,7 @@ params object[] messageArgs columnNumber, endLineNumber, endColumnNumber, - FormatResourceString(messageResourceName, messageArgs) - ); + FormatResourceString(messageResourceName, messageArgs)); } /// @@ -1221,8 +1181,7 @@ public void LogWarningWithCodeFromResources(string messageResourceName, params o /// The name of the string resource containing the warning message. /// Optional arguments for formatting the loaded string. /// Thrown when messageResourceName is null. - public void LogWarningWithCodeFromResources - ( + public void LogWarningWithCodeFromResources( string subcategoryResourceName, string file, int lineNumber, @@ -1230,8 +1189,7 @@ public void LogWarningWithCodeFromResources int endLineNumber, int endColumnNumber, string messageResourceName, - params object[] messageArgs - ) + params object[] messageArgs) { // No lock needed, as log methods are thread safe and the rest does not modify // global state. @@ -1253,8 +1211,7 @@ params object[] messageArgs helpKeyword = HelpKeywordPrefix + messageResourceName; } - LogWarning - ( + LogWarning( subcategory, warningCode, helpKeyword, @@ -1263,8 +1220,7 @@ params object[] messageArgs columnNumber, endLineNumber, endColumnNumber, - message - ); + message); } /// @@ -1301,9 +1257,9 @@ public void LogWarningFromException(Exception exception, bool showStackTrace) LogWarning(message); } -#endregion + #endregion -#region Bulk logging methods + #region Bulk logging methods /// /// Logs errors/warnings/messages for each line of text in the given file. Errors/warnings are only logged for lines that @@ -1412,8 +1368,7 @@ public bool LogMessageFromText(string lineOfText, MessageImportance messageImpor { case CanonicalError.Parts.Category.Error: { - LogError - ( + LogError( messageParts.subcategory, messageParts.code, null, @@ -1422,8 +1377,7 @@ public bool LogMessageFromText(string lineOfText, MessageImportance messageImpor messageParts.column, messageParts.endLine, messageParts.endColumn, - messageParts.text - ); + messageParts.text); isError = true; break; @@ -1431,8 +1385,7 @@ public bool LogMessageFromText(string lineOfText, MessageImportance messageImpor case CanonicalError.Parts.Category.Warning: { - LogWarning - ( + LogWarning( messageParts.subcategory, messageParts.code, null, @@ -1441,8 +1394,7 @@ public bool LogMessageFromText(string lineOfText, MessageImportance messageImpor messageParts.column, messageParts.endLine, messageParts.endColumn, - messageParts.text - ); + messageParts.text); break; } @@ -1456,9 +1408,9 @@ public bool LogMessageFromText(string lineOfText, MessageImportance messageImpor return isError; } -#endregion + #endregion -#region Telemetry logging methods + #region Telemetry logging methods /// /// Logs telemetry with the specified event name and properties. @@ -1470,10 +1422,10 @@ public void LogTelemetry(string eventName, IDictionary propertie (BuildEngine as IBuildEngine5)?.LogTelemetry(eventName, properties); } -#endregion + #endregion #if FEATURE_APPDOMAIN -#region AppDomain Code + #region AppDomain Code /// /// InitializeLifetimeService is called when the remote object is activated. @@ -1559,7 +1511,7 @@ public void MarkAsInactive() } } -#endregion + #endregion #endif } } diff --git a/src/Shared/TaskLoggingHelperExtension.cs b/src/Shared/TaskLoggingHelperExtension.cs index 2607884b1db..58200403610 100644 --- a/src/Shared/TaskLoggingHelperExtension.cs +++ b/src/Shared/TaskLoggingHelperExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -88,7 +88,7 @@ public ResourceManager TaskSharedResources /// Thrown when resourceName is null. /// Thrown when the string resource indicated by resourceName does not exist. /// Thrown when the TaskResources property of the owner task is not set. - override public string FormatResourceString(string resourceName, params object[] args) + public override string FormatResourceString(string resourceName, params object[] args) { ErrorUtilities.VerifyThrowArgumentNull(resourceName, nameof(resourceName)); ErrorUtilities.VerifyThrowInvalidOperation(TaskResources != null, "Shared.TaskResourcesNotRegistered", TaskName); diff --git a/src/Shared/TaskParameter.cs b/src/Shared/TaskParameter.cs index c9dd8991a6a..cf4c7934afe 100644 --- a/src/Shared/TaskParameter.cs +++ b/src/Shared/TaskParameter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -117,12 +117,10 @@ public TaskParameter(object wrappedParameter) } // It's not null or invalid, so it should be a valid parameter type. - ErrorUtilities.VerifyThrow - ( + ErrorUtilities.VerifyThrow( TaskParameterTypeVerifier.IsValidInputParameter(wrappedParameterType) || TaskParameterTypeVerifier.IsValidOutputParameter(wrappedParameterType), "How did we manage to get a task parameter of type {0} that isn't a valid parameter type?", - wrappedParameterType - ); + wrappedParameterType); if (wrappedParameterType.IsArray) { @@ -179,9 +177,9 @@ public TaskParameter(object wrappedParameter) _parameterType = TaskParameterType.String; _wrappedParameter = (string)Convert.ChangeType(wrappedParameter, typeof(string), CultureInfo.InvariantCulture); } - // Also stringify known common value types, to avoid calling - // TranslateDotNet when they'll just be stringified on the - // output side + // Also stringify known common value types, to avoid calling + // TranslateDotNet when they'll just be stringified on the + // output side else if (wrappedParameterType == typeof(bool)) { _parameterType = TaskParameterType.Bool; @@ -549,7 +547,7 @@ private class TaskParameterTaskItem : ITaskItem, ITaskItem2 #if !TASKHOST - ,IMetadataContainer + , IMetadataContainer #endif { /// diff --git a/src/Shared/TaskParameterTypeVerifier.cs b/src/Shared/TaskParameterTypeVerifier.cs index 7ac8fa58f67..2b7d6160d84 100644 --- a/src/Shared/TaskParameterTypeVerifier.cs +++ b/src/Shared/TaskParameterTypeVerifier.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; diff --git a/src/Shared/TempFileUtilities.cs b/src/Shared/TempFileUtilities.cs index 50c2e6628be..5b20b80d4a4 100644 --- a/src/Shared/TempFileUtilities.cs +++ b/src/Shared/TempFileUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Shared/ThreadPoolExtensions.cs b/src/Shared/ThreadPoolExtensions.cs index 08dda3d4b57..6b0e40c314f 100644 --- a/src/Shared/ThreadPoolExtensions.cs +++ b/src/Shared/ThreadPoolExtensions.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Shared/ToolsetElement.cs b/src/Shared/ToolsetElement.cs index 21c374dea84..0e2f7591b55 100644 --- a/src/Shared/ToolsetElement.cs +++ b/src/Shared/ToolsetElement.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/Tracing.cs b/src/Shared/Tracing.cs index 625006b9718..71b52e4d565 100644 --- a/src/Shared/Tracing.cs +++ b/src/Shared/Tracing.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/TranslatorHelpers.cs b/src/Shared/TranslatorHelpers.cs index 6850b11f1a2..2835756fa6c 100644 --- a/src/Shared/TranslatorHelpers.cs +++ b/src/Shared/TranslatorHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -45,7 +45,7 @@ public static void Translate( } } - static ObjectTranslator AdaptFactory(NodePacketValueFactory valueFactory) where T : ITranslatable + private static ObjectTranslator AdaptFactory(NodePacketValueFactory valueFactory) where T : ITranslatable { void TranslateUsingValueFactory(ITranslator translator, ref T objectToTranslate) { @@ -117,7 +117,9 @@ public static void TranslateHashSet( NodePacketCollectionCreator> collectionFactory) where T : class, ITranslatable { if (!translator.TranslateNullable(hashSet)) + { return; + } int count = default; if (translator.Mode == TranslationDirection.WriteToStream) @@ -150,7 +152,9 @@ public static void TranslateHashSet( public static void Translate(this ITranslator translator, ref CultureInfo cultureInfo) { if (!translator.TranslateNullable(cultureInfo)) + { return; + } int lcid = default; @@ -170,7 +174,9 @@ public static void Translate(this ITranslator translator, ref CultureInfo cultur public static void Translate(this ITranslator translator, ref Version version) { if (!translator.TranslateNullable(version)) + { return; + } int major = 0; int minor = 0; @@ -210,7 +216,9 @@ public static void Translate(this ITranslator translator, ref Version version) public static void Translate(this ITranslator translator, ref AssemblyName assemblyName) { if (!translator.TranslateNullable(assemblyName)) + { return; + } string name = null; Version version = null; diff --git a/src/Shared/TypeLoader.cs b/src/Shared/TypeLoader.cs index 40d28f23b29..37150f3f85a 100644 --- a/src/Shared/TypeLoader.cs +++ b/src/Shared/TypeLoader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -193,7 +193,8 @@ private static Assembly LoadAssemblyUsingMetadataLoadContext(AssemblyLoadInfo as // Deduplicate between MSBuild assemblies and task dependencies. Dictionary assembliesDictionary = new(localAssemblies.Length + runtimeAssemblies.Length); - foreach (string localPath in localAssemblies) { + foreach (string localPath in localAssemblies) + { assembliesDictionary.Add(Path.GetFileName(localPath), localPath); } @@ -211,12 +212,10 @@ private static Assembly LoadAssemblyUsingMetadataLoadContext(AssemblyLoadInfo as /// any) is unambiguous; otherwise, if there are multiple types with the same name in different namespaces, the first type /// found will be returned. /// - internal LoadedType Load - ( + internal LoadedType Load( string typeName, AssemblyLoadInfo assembly, - bool useTaskHost = false - ) + bool useTaskHost = false) { return GetLoadedType(s_cacheOfLoadedTypesByFilter, typeName, assembly, useTaskHost); } @@ -227,11 +226,9 @@ internal LoadedType Load /// found will be returned. /// /// The loaded type, or null if the type was not found. - internal LoadedType ReflectionOnlyLoad - ( + internal LoadedType ReflectionOnlyLoad( string typeName, - AssemblyLoadInfo assembly - ) + AssemblyLoadInfo assembly) { return GetLoadedType(s_cacheOfReflectionOnlyLoadedTypesByFilter, typeName, assembly, useTaskHost: false); } diff --git a/src/Shared/UnitTests/AssemblyNameEx_Tests.cs b/src/Shared/UnitTests/AssemblyNameEx_Tests.cs index 3c0bf360279..12ef8396ae8 100644 --- a/src/Shared/UnitTests/AssemblyNameEx_Tests.cs +++ b/src/Shared/UnitTests/AssemblyNameEx_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -17,7 +17,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class AssemblyNameEx_Tests + public sealed class AssemblyNameEx_Tests { /// /// Delegate defines a function that produces an AssemblyNameExtension from a string. @@ -175,8 +175,7 @@ public void CompareTo() if ( a1.CompareBaseNameTo(a2) == 0 // Only check version if basenames match - && a1.Version != a2.Version - ) + && a1.Version != a2.Version) { if (a1.Version == null) { @@ -331,8 +330,7 @@ public void CreateAssemblyNameExtensionWithNoSimpleName() Assert.Throws(() => { AssemblyNameExtension extension = new AssemblyNameExtension("Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a", true); - } - ); + }); } } @@ -350,8 +348,7 @@ public void CreateAssemblyNameExtensionWithNoSimpleName2() AssemblyNameExtension extension = new AssemblyNameExtension("Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); AssemblyNameExtension extension2 = new AssemblyNameExtension("A, Version=2.0.0.0, Culture=en, PublicKeyToken=b03f5f7f11d50a3a"); extension2.PartialNameCompare(extension); - } - ); + }); } } @@ -706,7 +703,7 @@ public void VerifyAssemblyNameExSerialization(string assemblyName) using (MemoryStream ms = new MemoryStream(bytes)) { BinaryFormatter formatter = new BinaryFormatter(); - assemblyNameDeserialized = (AssemblyNameExtension) formatter.Deserialize(ms); + assemblyNameDeserialized = (AssemblyNameExtension)formatter.Deserialize(ms); } assemblyNameDeserialized.ShouldBe(assemblyNameOriginal); diff --git a/src/Shared/UnitTests/AssemblyResources.cs b/src/Shared/UnitTests/AssemblyResources.cs index baa3ffd33ba..311870a9e2b 100644 --- a/src/Shared/UnitTests/AssemblyResources.cs +++ b/src/Shared/UnitTests/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Shared/UnitTests/BuildEventArgsExtension.cs b/src/Shared/UnitTests/BuildEventArgsExtension.cs index b41117fb094..4ee4e78d47e 100644 --- a/src/Shared/UnitTests/BuildEventArgsExtension.cs +++ b/src/Shared/UnitTests/BuildEventArgsExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Shared/UnitTests/CopyOnWriteDictionary_Tests.cs b/src/Shared/UnitTests/CopyOnWriteDictionary_Tests.cs index f609286317e..7b77647dd70 100644 --- a/src/Shared/UnitTests/CopyOnWriteDictionary_Tests.cs +++ b/src/Shared/UnitTests/CopyOnWriteDictionary_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -47,8 +47,7 @@ public void Indexer_NotFound() { var dictionary = new CopyOnWriteDictionary(); object value = dictionary[string.Empty]; - } - ); + }); } /// /// Find with the same key inserted using TryGetValue diff --git a/src/Shared/UnitTests/EngineTestEnvironment.cs b/src/Shared/UnitTests/EngineTestEnvironment.cs index 649d0ff35db..93df7aebdc3 100644 --- a/src/Shared/UnitTests/EngineTestEnvironment.cs +++ b/src/Shared/UnitTests/EngineTestEnvironment.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Shared/UnitTests/ErrorUtilities_Tests.cs b/src/Shared/UnitTests/ErrorUtilities_Tests.cs index d8d83d96d9e..c3ac1d5a7be 100644 --- a/src/Shared/UnitTests/ErrorUtilities_Tests.cs +++ b/src/Shared/UnitTests/ErrorUtilities_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -77,8 +77,7 @@ public void VerifyThrowArgumentArraysSameLength1() Assert.Throws(() => { ErrorUtilities.VerifyThrowArgumentArraysSameLength(null, new string[1], string.Empty, string.Empty); - } - ); + }); } [Fact] @@ -87,8 +86,7 @@ public void VerifyThrowArgumentArraysSameLength2() Assert.Throws(() => { ErrorUtilities.VerifyThrowArgumentArraysSameLength(new string[1], null, string.Empty, string.Empty); - } - ); + }); } [Fact] @@ -97,8 +95,7 @@ public void VerifyThrowArgumentArraysSameLength3() Assert.Throws(() => { ErrorUtilities.VerifyThrowArgumentArraysSameLength(new string[1], new string[2], string.Empty, string.Empty); - } - ); + }); } [Fact] diff --git a/src/Shared/UnitTests/EscapingUtilities_Tests.cs b/src/Shared/UnitTests/EscapingUtilities_Tests.cs index 180c18a2a5d..9b756d3a3da 100644 --- a/src/Shared/UnitTests/EscapingUtilities_Tests.cs +++ b/src/Shared/UnitTests/EscapingUtilities_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Xunit; diff --git a/src/Shared/UnitTests/FileMatcher_Tests.cs b/src/Shared/UnitTests/FileMatcher_Tests.cs index 7f6d55178ac..b29b4238e8e 100644 --- a/src/Shared/UnitTests/FileMatcher_Tests.cs +++ b/src/Shared/UnitTests/FileMatcher_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -612,39 +612,34 @@ private static IReadOnlyList GetFileSystemEntries(FileMatcher.FileSystem if ( pattern == @"LONGDI~1" - && (@"D:\" == path || @"\\server\share\" == path || path.Length == 0) - ) + && (@"D:\" == path || @"\\server\share\" == path || path.Length == 0)) { return new string[] { Path.Combine(path, "LongDirectoryName") }; } else if ( pattern == @"LONGSU~1" - && (@"D:\LongDirectoryName" == path || @"\\server\share\LongDirectoryName" == path || @"LongDirectoryName" == path) - ) + && (@"D:\LongDirectoryName" == path || @"\\server\share\LongDirectoryName" == path || @"LongDirectoryName" == path)) { return new string[] { Path.Combine(path, "LongSubDirectory") }; } else if ( pattern == @"LONGFI~1.TXT" - && (@"D:\LongDirectoryName\LongSubDirectory" == path || @"\\server\share\LongDirectoryName\LongSubDirectory" == path || @"LongDirectoryName\LongSubDirectory" == path) - ) + && (@"D:\LongDirectoryName\LongSubDirectory" == path || @"\\server\share\LongDirectoryName\LongSubDirectory" == path || @"LongDirectoryName\LongSubDirectory" == path)) { return new string[] { Path.Combine(path, "LongFileName.txt") }; } else if ( pattern == @"pomegr~1" - && @"c:\apple\banana\tomato" == path - ) + && @"c:\apple\banana\tomato" == path) { return new string[] { Path.Combine(path, "pomegranate") }; } else if ( - @"c:\apple\banana\tomato\pomegranate\orange" == path - ) + @"c:\apple\banana\tomato\pomegranate\orange" == path) { // No files exist here. This is an empty directory. return Array.Empty(); @@ -787,8 +782,7 @@ public void NormalizeTest(string inputString, string expectedString) [Fact] public void BasicMatchDriver() { - MatchDriver - ( + MatchDriver( "Source" + Path.DirectorySeparatorChar + "**", new string[] // Files that exist and should match. { @@ -800,8 +794,7 @@ public void BasicMatchDriver() "Destination" + Path.DirectorySeparatorChar + "Bart.txt", "Destination" + Path.DirectorySeparatorChar + "Sub" + Path.DirectorySeparatorChar + "Homer.txt", }, - null - ); + null); } /// @@ -813,16 +806,14 @@ public void BasicMatchDriver() [Fact] public void Regress162390() { - MatchDriver - ( + MatchDriver( @"c:\?emp\foo.txt", new string[] { @"c:\temp\foo.txt" }, // Should match new string[] { @"c:\timp\foo.txt" }, // Shouldn't match new string[] // Should not even consider. { @"c:\temp\sub\foo.txt" - } - ); + }); } /* @@ -839,11 +830,9 @@ public void GetLongFileNameForShortLocalPath() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"D:\LONGDI~1\LONGSU~1\LONGFI~1.TXT", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } @@ -857,11 +846,9 @@ public void GetLongFileNameForShortLocalPath() [Fact] public void GetLongFileNameForLongLocalPath() { - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"D:\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } @@ -880,11 +867,9 @@ public void GetLongFileNameForShortUncPath() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"\\server\share\LONGDI~1\LONGSU~1\LONGFI~1.TXT", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } @@ -898,11 +883,9 @@ public void GetLongFileNameForShortUncPath() [Fact] public void GetLongFileNameForLongUncPath() { - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"\\server\share\LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } @@ -921,11 +904,9 @@ public void GetLongFileNameForRelativePath() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"LONGDI~1\LONGSU~1\LONGFI~1.TXT", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"LongDirectoryName\LongSubDirectory\LongFileName.txt", longPath); } @@ -944,11 +925,9 @@ public void GetLongFileNameForRelativePathPreservesTrailingSlash() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"LONGDI~1\LONGSU~1\", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"LongDirectoryName\LongSubDirectory\", longPath); } @@ -967,11 +946,9 @@ public void GetLongFileNameForRelativePathPreservesExtraSlashes() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"LONGDI~1\\LONGSU~1\\", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"LongDirectoryName\\LongSubDirectory\\", longPath); } @@ -990,11 +967,9 @@ public void GetLongFileNameForMixedLongAndShort() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"c:\apple\banana\tomato\pomegr~1\orange\", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"c:\apple\banana\tomato\pomegranate\orange\", longPath); } @@ -1014,11 +989,9 @@ public void GetLongFileNameWherePartOfThePathDoesntExist() return; // "Short names are for Windows only" } - string longPath = FileMatcher.GetLongPathName - ( + string longPath = FileMatcher.GetLongPathName( @"c:\apple\banana\tomato\pomegr~1\orange\chocol~1\vanila~1", - new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries) - ); + new FileMatcher.GetFileSystemEntries(FileMatcherTest.GetFileSystemEntries)); Assert.Equal(@"c:\apple\banana\tomato\pomegranate\orange\chocol~1\vanila~1", longPath); } @@ -1152,50 +1125,38 @@ public void ParentWithoutSlash() // because we don't know whether foo is a file or folder. // Same for UNC - ValidateNoFileMatch - ( + ValidateNoFileMatch( "\\\\server\\c$\\Documents and Settings\\User\\**", "\\\\server\\c$\\Documents and Settings\\User", - true - ); + true); } [Fact] public void Unc() { // Check UNC functionality - ValidateFileMatch - ( + ValidateFileMatch( "\\\\server\\c$\\**\\*.cs", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", - true - ); + true); - ValidateNoFileMatch - ( + ValidateNoFileMatch( "\\\\server\\c$\\**\\*.cs", "\\\\server\\c$\\Documents and Settings\\User\\Source.txt", - true - ); - ValidateFileMatch - ( + true); + ValidateFileMatch( "\\\\**", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", - true - ); - ValidateFileMatch - ( + true); + ValidateFileMatch( "\\\\**\\*.*", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", - true - ); + true); - ValidateFileMatch - ( + ValidateFileMatch( "**", "\\\\server\\c$\\Documents and Settings\\User\\Source.cs", - true - ); + true); } [Fact] @@ -1524,7 +1485,7 @@ public void RemoveProjectDirectory() strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\" : "/").ToArray(); Assert.Equal("1.file", strings[0]); - strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directory\\1.file" : "/directory/1.file"}; + strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directory\\1.file" : "/directory/1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\" : "/").ToArray(); Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "directory\\1.file" : "directory/1.file"); @@ -1533,12 +1494,12 @@ public void RemoveProjectDirectory() Assert.Equal("1.file", strings[0]); strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file" }; - strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory" ).ToArray(); + strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory").ToArray(); Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\1.file" : "/1.file"); strings = new string[1] { NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file" }; strings = FileMatcher.RemoveProjectDirectory(strings, NativeMethodsShared.IsWindows ? "c:\\directory" : "/directory").ToArray(); - Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file" ); + Assert.Equal(strings[0], NativeMethodsShared.IsWindows ? "c:\\directorymorechars\\1.file" : "/directorymorechars/1.file"); if (NativeMethodsShared.IsWindows) { @@ -1571,24 +1532,21 @@ public void RemoveProjectDirectory() { @"src/a.cs", @"src/a\b\b.cs", - } - )] + })] [InlineData( @"src/test/**/*.cs", // Include Pattern new string[] // Matching files { @"src/test/a.cs", @"src/test/a\b\c.cs", - } - )] + })] [InlineData( @"src/test/**/a/b/**/*.cs", // Include Pattern new string[] // Matching files { @"src/test/dir\a\b\a.cs", @"src/test/dir\a\b\c\a.cs", - } - )] + })] public void IncludePatternShouldNotPreserveUserSlashesInFixedDirPart(string include, string[] matching) { MatchDriver(include, null, matching, null, null, normalizeAllPaths: false, normalizeExpectedMatchingFiles: true); @@ -1612,8 +1570,7 @@ public void IncludePatternShouldNotPreserveUserSlashesInFixedDirPart(string incl @"bin\foo.cs", @"bin\bar\foo.cs", @"bin\bar\" - } - )] + })] [InlineData( @"**\*.cs", // Include Pattern new[] // Exclude patterns @@ -1634,8 +1591,7 @@ public void IncludePatternShouldNotPreserveUserSlashesInFixedDirPart(string incl @"bin\foo.cs", @"bin\bar\foo.cs", @"bin\bar\" - } - )] + })] public void ExcludePattern(string include, string[] exclude, string[] matching, string[] nonMatching, string[] untouchable) { MatchDriver(include, exclude, matching, nonMatching, untouchable); @@ -1662,8 +1618,7 @@ public void ExcludeSpecificFiles() @"Program_old.cs", @"Properties\AssemblyInfo_old.cs" }, - Array.Empty() // Non matching files that shouldn't be touched - ); + Array.Empty()); // Non matching files that shouldn't be touched } [Fact] @@ -1695,8 +1650,7 @@ public void ExcludePatternAndSpecificFiles() @"bin\foo.cs", @"bin\bar\foo.cs", @"bin\bar\" - } - ); + }); } [Theory] @@ -1728,8 +1682,7 @@ public void ExcludePatternAndSpecificFiles() { @"src\Common\Properties\", @"src\Common\Properties\AssemblyInfo.cs", - } - )] + })] [InlineData( @"**\*.cs", // Include Pattern new[] // Exclude patterns @@ -1758,8 +1711,7 @@ public void ExcludePatternAndSpecificFiles() new[] // Non matching files that shouldn't be touched { @"src\Common\Properties\" - } - )] + })] [InlineData( @"src\**\proj\**\*.cs", // Include Pattern new[] // Exclude patterns @@ -1789,8 +1741,7 @@ public void ExcludePatternAndSpecificFiles() }, new string[] // Non matching files that shouldn't be touched { - } - )] + })] // patterns with excludes that ideally would prune entire recursive subtrees (files in pruned tree aren't touched at all) but the exclude pattern is too complex for that to work with the current logic public void ExcludeComplexPattern(string include, string[] exclude, string[] matching, string[] nonMatching, string[] untouchable) { @@ -1806,8 +1757,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "", "^(?)(?)$", false, - true - )] + true)] // ... anywhere is invalid [InlineData( @"...\foo", @@ -1816,8 +1766,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "", "", false, - false - )] + false)] // : not placed at second index is invalid [InlineData( "http://www.website.com", @@ -1826,8 +1775,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "", "", false, - false - )] + false)] // ** not alone in filename part is invalid [InlineData( "**foo", @@ -1836,8 +1784,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "**foo", "", false, - false - )] + false)] // ** not alone in filename part is invalid [InlineData( "foo**", @@ -1846,8 +1793,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "foo**", "", false, - false - )] + false)] // ** not alone between slashes in wildcard part is invalid [InlineData( @"**foo\bar", @@ -1856,8 +1802,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "bar", "", false, - false - )] + false)] // .. placed after any ** is invalid [InlineData( @"**\..\bar", @@ -1866,8 +1811,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "bar", "", false, - false - )] + false)] // Common wildcard characters in wildcard and filename part [InlineData( @"*fo?ba?\*fo?ba?", @@ -1876,8 +1820,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "*fo?ba?", @"^(?[^/\\]*fo.ba.[/\\]+)(?[^/\\]*fo.ba.)$", true, - true - )] + true)] // Special case for ? and * when trailing . in filename part [InlineData( "?oo*.", @@ -1886,8 +1829,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "?oo*.", @"^(?)(?[^\.].oo[^\.]*)$", false, - true - )] + true)] // Skip the .* portion of any *.* sequence in filename part [InlineData( "*.*foo*.*", @@ -1896,8 +1838,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "*.*foo*.*", @"^(?)(?[^/\\]*foo[^/\\]*)$", false, - true - )] + true)] // Collapse successive directory separators [InlineData( @"\foo///bar\\\?foo///bar\\\foo", @@ -1906,8 +1847,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "foo", @"^[/\\]+foo[/\\]+bar[/\\]+(?.foo[/\\]+bar[/\\]+)(?foo)$", true, - true - )] + true)] // Collapse successive relative separators [InlineData( @"\./.\foo/.\./bar\./.\?foo/.\./bar\./.\foo", @@ -1916,8 +1856,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "foo", @"^[/\\]+foo[/\\]+bar[/\\]+(?.foo[/\\]+bar[/\\]+)(?foo)$", true, - true - )] + true)] // Collapse successive recursive operators [InlineData( @"foo\**/**\bar/**\**/foo\**/**\bar", @@ -1926,8 +1865,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "bar", @"^foo[/\\]+(?((.*/)|(.*\\)|())bar((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/))foo((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/)))(?bar)$", true, - true - )] + true)] // Collapse all three cases combined [InlineData( @"foo\\\.///**\\\.///**\\\.///bar\\\.///**\\\.///**\\\.///foo\\\.///**\\\.///**\\\.///bar", @@ -1936,8 +1874,7 @@ public void ExcludeComplexPattern(string include, string[] exclude, string[] mat "bar", @"^foo[/\\]+(?((.*/)|(.*\\)|())bar((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/))foo((/)|(\\)|(/.*/)|(/.*\\)|(\\.*\\)|(\\.*/)))(?bar)$", true, - true - )] + true)] public void GetFileSpecInfoCommon( string filespec, string expectedFixedDirectoryPart, @@ -1945,8 +1882,7 @@ public void GetFileSpecInfoCommon( string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, - bool expectedIsLegalFileSpec - ) + bool expectedIsLegalFileSpec) { if (NativeMethodsShared.IsUnixLike) { @@ -1960,8 +1896,7 @@ bool expectedIsLegalFileSpec expectedFilenamePart, expectedMatchFileExpression, expectedNeedsRecursion, - expectedIsLegalFileSpec - ); + expectedIsLegalFileSpec); } [PlatformSpecific(TestPlatforms.Windows)] @@ -1974,8 +1909,7 @@ bool expectedIsLegalFileSpec "$()+.[^{", @"^\$\(\)\+\.\[\^\{[/\\]+(?.\$\(\)\+\.\[\^\{[/\\]+)(?\$\(\)\+\.\[\^\{)$", true, - true - )] + true)] // Preserve UNC paths in fixed directory part [InlineData( @"\\\.\foo/bar", @@ -1984,8 +1918,7 @@ bool expectedIsLegalFileSpec "bar", @"^\\\\foo[/\\]+(?)(?bar)$", false, - true - )] + true)] public void GetFileSpecInfoWindows( string filespec, string expectedFixedDirectoryPart, @@ -1993,8 +1926,7 @@ public void GetFileSpecInfoWindows( string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, - bool expectedIsLegalFileSpec - ) + bool expectedIsLegalFileSpec) { TestGetFileSpecInfo( filespec, @@ -2003,8 +1935,7 @@ bool expectedIsLegalFileSpec expectedFilenamePart, expectedMatchFileExpression, expectedNeedsRecursion, - expectedIsLegalFileSpec - ); + expectedIsLegalFileSpec); } [PlatformSpecific(TestPlatforms.AnyUnix)] @@ -2017,8 +1948,7 @@ bool expectedIsLegalFileSpec "$()+.[^{|", @"^\$\(\)\+\.\[\^\{\|[/\\]+(?.\$\(\)\+\.\[\^\{\|[/\\]+)(?\$\(\)\+\.\[\^\{\|)$", true, - true - )] + true)] // Collapse leading successive directory separators in fixed directory part [InlineData( @"\\\.\foo/bar", @@ -2027,8 +1957,7 @@ bool expectedIsLegalFileSpec "bar", @"^[/\\]+foo[/\\]+(?)(?bar)$", false, - true - )] + true)] public void GetFileSpecInfoUnix( string filespec, string expectedFixedDirectoryPart, @@ -2036,8 +1965,7 @@ public void GetFileSpecInfoUnix( string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, - bool expectedIsLegalFileSpec - ) + bool expectedIsLegalFileSpec) { TestGetFileSpecInfo( filespec, @@ -2046,8 +1974,7 @@ bool expectedIsLegalFileSpec expectedFilenamePart, expectedMatchFileExpression, expectedNeedsRecursion, - expectedIsLegalFileSpec - ); + expectedIsLegalFileSpec); } private void TestGetFileSpecInfo( @@ -2057,8 +1984,7 @@ private void TestGetFileSpecInfo( string expectedFilenamePart, string expectedMatchFileExpression, bool expectedNeedsRecursion, - bool expectedIsLegalFileSpec - ) + bool expectedIsLegalFileSpec) { FileMatcher.Default.GetFileSpecInfo( filespec, @@ -2066,8 +1992,7 @@ bool expectedIsLegalFileSpec out string wildcardDirectoryPart, out string filenamePart, out bool needsRecursion, - out bool isLegalFileSpec - ); + out bool isLegalFileSpec); string matchFileExpression = isLegalFileSpec ? FileMatcher.RegularExpressionFromFileSpec(fixedDirectoryPart, wildcardDirectoryPart, filenamePart) : string.Empty; @@ -2080,7 +2005,7 @@ out bool isLegalFileSpec isLegalFileSpec.ShouldBe(expectedIsLegalFileSpec); } -#region Support functions. + #region Support functions. /// /// This support class simulates a file system. @@ -2125,12 +2050,10 @@ internal class MockFileSystem /// First set of files. /// Second set of files. /// Third set of files. - internal MockFileSystem - ( + internal MockFileSystem( string[] fileSet1, string[] fileSet2, - string[] fileSet3 - ) + string[] fileSet3) { _fileSet1 = fileSet1; _fileSet2 = fileSet2; @@ -2193,8 +2116,7 @@ private int GetMatchingFiles(string[] candidates, string path, string pattern, I if ( pattern == null || - String.Equals(pattern, "*.*", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(pattern, "*.*", StringComparison.OrdinalIgnoreCase)) { ++hits; files.Add(FileMatcher.Normalize(candidate)); @@ -2273,16 +2195,14 @@ private void GetMatchingDirectories(string[] candidates, string path, string pat if ( String.Equals(pattern, "*.*", StringComparison.OrdinalIgnoreCase) - || pattern == null - ) + || pattern == null) { directories.Add(FileMatcher.Normalize(match)); } else if // Match patterns like ?emp ( pattern.Substring(0, 1) == "?" - && pattern.Length == baseMatch.Length - ) + && pattern.Length == baseMatch.Length) { string tail = pattern.Substring(1); string baseMatchTail = baseMatch.Substring(1); @@ -2473,13 +2393,11 @@ internal bool DirectoryExists(string path) /// Files that exist and should be matched. /// Files that exists and should not be matched. /// Files that exist but should not be requested. - private static void MatchDriver - ( + private static void MatchDriver( string filespec, string[] matchingFiles, string[] nonmatchingFiles, - string[] untouchableFiles - ) + string[] untouchableFiles) { MatchDriver(filespec, null, matchingFiles, nonmatchingFiles, untouchableFiles); } @@ -2490,14 +2408,12 @@ string[] untouchableFiles /// /// To preserve current MSBuild behaviour, it only does so if the path is not rooted. Rooted paths do not support forward slashes (as observed on MSBuild 14.0.25420.1) /// - private static void MatchDriverWithDifferentSlashes - ( + private static void MatchDriverWithDifferentSlashes( string filespec, string[] excludeFilespecs, string[] matchingFiles, string[] nonmatchingFiles, - string[] untouchableFiles - ) + string[] untouchableFiles) { // tests should call this method with backward slashes Assert.DoesNotContain(filespec, "/"); @@ -2521,12 +2437,11 @@ private static void MatchDriver(string filespec, string[] excludeFilespecs, stri var fileMatcher = new FileMatcher(new FileSystemAdapter(mockFileSystem), mockFileSystem.GetAccessibleFileSystemEntries); - string[] files = fileMatcher.GetFiles - ( + string[] files = fileMatcher.GetFiles( String.Empty, /* we don't need project directory as we use mock filesystem */ filespec, - excludeFilespecs?.ToList() - ).FileList; + excludeFilespecs?.ToList()) + .FileList; Func normalizeAllFunc = (paths => normalizeAllPaths ? paths.Select(MockFileSystem.Normalize).ToArray() : paths); Func normalizeMatching = (paths => normalizeExpectedMatchingFiles ? paths.Select(MockFileSystem.Normalize).ToArray() : paths); @@ -2592,25 +2507,21 @@ private static IReadOnlyList GetFileSystemEntriesLoopBack(FileMatcher.Fi private static FileMatcher loopBackFileMatcher = new FileMatcher(FileSystems.Default, GetFileSystemEntriesLoopBack); - private static void ValidateSplitFileSpec - ( + private static void ValidateSplitFileSpec( string filespec, string expectedFixedDirectoryPart, string expectedWildcardDirectoryPart, - string expectedFilenamePart - ) + string expectedFilenamePart) { string fixedDirectoryPart; string wildcardDirectoryPart; string filenamePart; - loopBackFileMatcher.SplitFileSpec - ( + loopBackFileMatcher.SplitFileSpec( filespec, out fixedDirectoryPart, out wildcardDirectoryPart, - out filenamePart - ); + out filenamePart); expectedFixedDirectoryPart = FileUtilities.FixFilePath(expectedFixedDirectoryPart); expectedWildcardDirectoryPart = FileUtilities.FixFilePath(expectedWildcardDirectoryPart); @@ -2620,8 +2531,7 @@ out filenamePart ( expectedWildcardDirectoryPart != wildcardDirectoryPart || expectedFixedDirectoryPart != fixedDirectoryPart - || expectedFilenamePart != filenamePart - ) + || expectedFilenamePart != filenamePart) { Console.WriteLine("Expect Fixed '{0}' got '{1}'", expectedFixedDirectoryPart, fixedDirectoryPart); Console.WriteLine("Expect Wildcard '{0}' got '{1}'", expectedWildcardDirectoryPart, wildcardDirectoryPart); @@ -2634,12 +2544,10 @@ out filenamePart * Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they * do indeed match. *************************************************************************************/ - private static void ValidateFileMatch - ( + private static void ValidateFileMatch( string filespec, string fileToMatch, - bool shouldBeRecursive - ) + bool shouldBeRecursive) { ValidateFileMatch(filespec, fileToMatch, shouldBeRecursive, /* Simulate filesystem? */ true); } @@ -2648,13 +2556,11 @@ bool shouldBeRecursive * Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they * do indeed match. *************************************************************************************/ - private static void ValidateFileMatch - ( + private static void ValidateFileMatch( string filespec, string fileToMatch, bool shouldBeRecursive, - bool fileSystemSimulation - ) + bool fileSystemSimulation) { if (!IsFileMatchAssertIfIllegal(filespec, fileToMatch, shouldBeRecursive)) { @@ -2664,13 +2570,11 @@ bool fileSystemSimulation // Now, simulate a filesystem with only fileToMatch. Make sure the file exists that way. if (fileSystemSimulation) { - MatchDriver - ( + MatchDriver( filespec, new string[] { fileToMatch }, null, - null - ); + null); } } @@ -2678,12 +2582,10 @@ bool fileSystemSimulation * Given a pattern (filespec) and a candidate filename (fileToMatch). Verify that they * DON'T match. *************************************************************************************/ - private static void ValidateNoFileMatch - ( + private static void ValidateNoFileMatch( string filespec, string fileToMatch, - bool shouldBeRecursive - ) + bool shouldBeRecursive) { if (IsFileMatchAssertIfIllegal(filespec, fileToMatch, shouldBeRecursive)) { @@ -2691,33 +2593,27 @@ bool shouldBeRecursive } // Now, simulate a filesystem with only fileToMatch. Make sure the file doesn't exist that way. - MatchDriver - ( + MatchDriver( filespec, null, new string[] { fileToMatch }, - null - ); + null); } /************************************************************************************* * Verify that the given filespec is illegal. *************************************************************************************/ - private static void ValidateIllegal - ( - string filespec - ) + private static void ValidateIllegal( + string filespec) { Regex regexFileMatch; bool needsRecursion; bool isLegalFileSpec; - loopBackFileMatcher.GetFileSpecInfoWithRegexObject - ( + loopBackFileMatcher.GetFileSpecInfoWithRegexObject( filespec, out regexFileMatch, out needsRecursion, - out isLegalFileSpec - ); + out isLegalFileSpec); if (isLegalFileSpec) { @@ -2726,24 +2622,20 @@ out isLegalFileSpec // Now, FileMatcher is supposed to take any legal file name and just return it immediately. // Let's see if it does. - MatchDriver - ( + MatchDriver( filespec, // Not legal. new string[] { filespec }, // Should match null, - null - ); + null); } /************************************************************************************* * Given a pattern (filespec) and a candidate filename (fileToMatch) return true if * FileMatcher would say that they match. *************************************************************************************/ - private static bool IsFileMatchAssertIfIllegal - ( + private static bool IsFileMatchAssertIfIllegal( string filespec, string fileToMatch, - bool shouldBeRecursive - ) + bool shouldBeRecursive) { FileMatcher.Result match = FileMatcher.Default.FileMatch(filespec, fileToMatch); @@ -2761,7 +2653,7 @@ bool shouldBeRecursive return match.isMatch; } -#endregion + #endregion private class FileSystemAdapter : IFileSystem { diff --git a/src/Shared/UnitTests/FileUtilities_Tests.cs b/src/Shared/UnitTests/FileUtilities_Tests.cs index 006a7b607d8..199b46c85f1 100644 --- a/src/Shared/UnitTests/FileUtilities_Tests.cs +++ b/src/Shared/UnitTests/FileUtilities_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -158,8 +158,7 @@ public void GetItemSpecModifierOnBadPath() Assert.Throws(() => { TestGetItemSpecModifierOnBadPath(Directory.GetCurrentDirectory()); - } - ); + }); } /// /// Exercises FileUtilities.ItemSpecModifiers.GetItemSpecModifier on a bad path. @@ -172,8 +171,7 @@ public void GetItemSpecModifierOnBadPath2() Assert.Throws(() => { TestGetItemSpecModifierOnBadPath(null); - } - ); + }); } private static void TestGetItemSpecModifierOnBadPath(string currentDirectory) @@ -203,7 +201,10 @@ public void GetFileInfoNoThrowBasic() } finally { - if (file != null) File.Delete(file); + if (file != null) + { + File.Delete(file); + } } } @@ -265,9 +266,9 @@ public void GetDirectoryWithTrailingSlash() } [Theory] - [InlineData("foo.txt", new[] { ".txt" })] - [InlineData("foo.txt", new[] { ".TXT" })] - [InlineData("foo.txt", new[] { ".EXE", ".TXT" })] + [InlineData("foo.txt", new[] { ".txt" })] + [InlineData("foo.txt", new[] { ".TXT" })] + [InlineData("foo.txt", new[] { ".EXE", ".TXT" })] public void HasExtension_WhenFileNameHasExtension_ReturnsTrue(string fileName, string[] allowedExtensions) { var result = FileUtilities.HasExtension(fileName, allowedExtensions); @@ -279,13 +280,13 @@ public void HasExtension_WhenFileNameHasExtension_ReturnsTrue(string fileName, s } [Theory] - [InlineData("foo.txt", new[] { ".DLL" })] - [InlineData("foo.txt", new[] { ".EXE", ".DLL" })] - [InlineData("foo.exec", new[] { ".exe", })] - [InlineData("foo.exe", new[] { ".exec", })] - [InlineData("foo", new[] { ".exe", })] - [InlineData("", new[] { ".exe" })] - [InlineData(null, new[] { ".exe" })] + [InlineData("foo.txt", new[] { ".DLL" })] + [InlineData("foo.txt", new[] { ".EXE", ".DLL" })] + [InlineData("foo.exec", new[] { ".exe", })] + [InlineData("foo.exe", new[] { ".exec", })] + [InlineData("foo", new[] { ".exe", })] + [InlineData("", new[] { ".exe" })] + [InlineData(null, new[] { ".exe" })] public void HasExtension_WhenFileNameDoesNotHaveExtension_ReturnsFalse(string fileName, string[] allowedExtensions) { var result = FileUtilities.HasExtension(fileName, allowedExtensions); @@ -441,8 +442,7 @@ public void NormalizePathThatDoesntFitIntoMaxPath() string fullPath = @"c:\aardvark\aardvark\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\1234567890\a.cs"; Assert.Equal(fullPath, FileUtilities.NormalizePath(Path.Combine(currentDirectory, filePath))); - } - ); + }); } [Fact] @@ -462,8 +462,7 @@ public void NormalizePathNull() Assert.Throws(() => { Assert.Null(FileUtilities.NormalizePath(null, null)); - } - ); + }); } [Fact] @@ -472,8 +471,7 @@ public void NormalizePathEmpty() Assert.Throws(() => { Assert.Null(FileUtilities.NormalizePath(String.Empty)); - } - ); + }); } [Fact] @@ -484,8 +482,7 @@ public void NormalizePathBadUNC1() Assert.Throws(() => { Assert.Null(FileUtilities.NormalizePath(@"\\")); - } - ); + }); } [Fact] @@ -496,8 +493,7 @@ public void NormalizePathBadUNC2() Assert.Throws(() => { Assert.Null(FileUtilities.NormalizePath(@"\\XXX\")); - } - ); + }); } [Fact] @@ -508,8 +504,7 @@ public void NormalizePathBadUNC3() Assert.Throws(() => { Assert.Equal(@"\\localhost", FileUtilities.NormalizePath(@"\\localhost")); - } - ); + }); } [Fact] @@ -528,7 +523,7 @@ public void NormalizePathTooLongWithDots() } #if FEATURE_LEGACY_GETFULLPATH - [Fact(Skip="https://github.com/dotnet/msbuild/issues/4205")] + [Fact(Skip = "https://github.com/dotnet/msbuild/issues/4205")] [PlatformSpecific(TestPlatforms.Windows)] public void NormalizePathBadGlobalroot() { @@ -543,8 +538,7 @@ From Path.cs // with this for security reasons. * */ Assert.Null(FileUtilities.NormalizePath(@"\\?\globalroot\XXX")); - } - ); + }); } #endif @@ -898,8 +892,7 @@ public void GenerateTempBatchFileWithBadExtension() Assert.Throws(() => { FileUtilities.GetTemporaryFile("|"); - } - ); + }); } /// @@ -914,8 +907,7 @@ public void GenerateTempBatchFileWithBadDirectory() Assert.Throws(() => { FileUtilities.GetTemporaryFile("|", null, ".tmp"); - } - ); + }); } [Fact] diff --git a/src/Shared/UnitTests/ImmutableDictionary_Tests.cs b/src/Shared/UnitTests/ImmutableDictionary_Tests.cs index 9ac90118d3a..e0ecf9bc051 100644 --- a/src/Shared/UnitTests/ImmutableDictionary_Tests.cs +++ b/src/Shared/UnitTests/ImmutableDictionary_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // We don't automatically run these tests against the BCL implementation of ImmutableDictionary as it would require dual-compiling // this file. When making changes to this test, though, it is recommended to run them manually by uncommenting the following line. diff --git a/src/Shared/UnitTests/MockEngine.cs b/src/Shared/UnitTests/MockEngine.cs index 7d54b8e7217..7797ba2dadf 100644 --- a/src/Shared/UnitTests/MockEngine.cs +++ b/src/Shared/UnitTests/MockEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -217,25 +217,21 @@ internal string Log public bool IsRunningMultipleNodes { get; set; } - public bool BuildProjectFile - ( + public bool BuildProjectFile( string projectFileName, string[] targetNames, IDictionary globalPropertiesPassedIntoTask, - IDictionary targetOutputs - ) + IDictionary targetOutputs) { return BuildProjectFile(projectFileName, targetNames, globalPropertiesPassedIntoTask, targetOutputs, null); } - public bool BuildProjectFile - ( + public bool BuildProjectFile( string projectFileName, string[] targetNames, IDictionary globalPropertiesPassedIntoTask, IDictionary targetOutputs, - string toolsVersion - ) + string toolsVersion) { var finalGlobalProperties = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -255,16 +251,14 @@ string toolsVersion return project.Build(targetNames, loggers); } - public bool BuildProjectFilesInParallel - ( + public bool BuildProjectFilesInParallel( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, - bool unloadProjectsOnCompletion - ) + bool unloadProjectsOnCompletion) { bool includeTargetOutputs = targetOutputsPerProject != null; @@ -287,15 +281,13 @@ bool unloadProjectsOnCompletion return result.Result; } - public BuildEngineResult BuildProjectFilesInParallel - ( + public BuildEngineResult BuildProjectFilesInParallel( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList[] undefineProperties, string[] toolsVersion, - bool returnTargetOutputs - ) + bool returnTargetOutputs) { List> targetOutputsPerProject = null; @@ -347,42 +339,32 @@ public void Reacquire() { } - public bool BuildProjectFile - ( - string projectFileName - ) + public bool BuildProjectFile( + string projectFileName) { return (_projectCollection.LoadProject(projectFileName)).Build(); } - public bool BuildProjectFile - ( + public bool BuildProjectFile( string projectFileName, - string[] targetNames - ) + string[] targetNames) { return (_projectCollection.LoadProject(projectFileName)).Build(targetNames); } - public bool BuildProjectFile - ( + public bool BuildProjectFile( string projectFileName, - string targetName - ) + string targetName) { return (_projectCollection.LoadProject(projectFileName)).Build(targetName); } - public void UnregisterAllLoggers - ( - ) + public void UnregisterAllLoggers() { _projectCollection.UnregisterAllLoggers(); } - public void UnloadAllProjects - ( - ) + public void UnloadAllProjects() { _projectCollection.UnloadAllProjects(); } diff --git a/src/Shared/UnitTests/MockLogger.cs b/src/Shared/UnitTests/MockLogger.cs index 2f07fca6d10..db10c0e6d6d 100644 --- a/src/Shared/UnitTests/MockLogger.cs +++ b/src/Shared/UnitTests/MockLogger.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -270,113 +270,113 @@ internal void LoggerEventHandler(object sender, BuildEventArgs eventArgs) } break; case BuildErrorEventArgs e: - { - string logMessage = $"{e.File}({e.LineNumber},{e.ColumnNumber}): {e.Subcategory} error {e.Code}: {e.Message}"; - _fullLog.AppendLine(logMessage); - _testOutputHelper?.WriteLine(logMessage); + { + string logMessage = $"{e.File}({e.LineNumber},{e.ColumnNumber}): {e.Subcategory} error {e.Code}: {e.Message}"; + _fullLog.AppendLine(logMessage); + _testOutputHelper?.WriteLine(logMessage); - ++ErrorCount; - Errors.Add(e); - break; - } + ++ErrorCount; + Errors.Add(e); + break; + } default: - { - // Log the message unless we are a build finished event and logBuildFinished is set to false. - bool logMessage = !(eventArgs is BuildFinishedEventArgs) || LogBuildFinished; - if (logMessage) { - _fullLog.AppendLine(eventArgs.Message); - _testOutputHelper?.WriteLine(eventArgs.Message); + // Log the message unless we are a build finished event and logBuildFinished is set to false. + bool logMessage = !(eventArgs is BuildFinishedEventArgs) || LogBuildFinished; + if (logMessage) + { + _fullLog.AppendLine(eventArgs.Message); + _testOutputHelper?.WriteLine(eventArgs.Message); + } + break; } - break; - } } // Log the specific type of event it was switch (eventArgs) { case ExternalProjectStartedEventArgs args: - { - ExternalProjectStartedEvents.Add(args); - break; - } + { + ExternalProjectStartedEvents.Add(args); + break; + } case ExternalProjectFinishedEventArgs finishedEventArgs: - { - ExternalProjectFinishedEvents.Add(finishedEventArgs); - break; - } + { + ExternalProjectFinishedEvents.Add(finishedEventArgs); + break; + } case ProjectEvaluationStartedEventArgs evaluationStartedEventArgs: - { - EvaluationStartedEvents.Add(evaluationStartedEventArgs); - break; - } + { + EvaluationStartedEvents.Add(evaluationStartedEventArgs); + break; + } case ProjectEvaluationFinishedEventArgs evaluationFinishedEventArgs: - { - EvaluationFinishedEvents.Add(evaluationFinishedEventArgs); - break; - } + { + EvaluationFinishedEvents.Add(evaluationFinishedEventArgs); + break; + } case ProjectStartedEventArgs startedEventArgs: - { - ProjectStartedEvents.Add(startedEventArgs); - break; - } + { + ProjectStartedEvents.Add(startedEventArgs); + break; + } case ProjectFinishedEventArgs finishedEventArgs: - { - ProjectFinishedEvents.Add(finishedEventArgs); - break; - } + { + ProjectFinishedEvents.Add(finishedEventArgs); + break; + } case TargetStartedEventArgs targetStartedEventArgs: - { - TargetStartedEvents.Add(targetStartedEventArgs); - break; - } + { + TargetStartedEvents.Add(targetStartedEventArgs); + break; + } case TargetFinishedEventArgs targetFinishedEventArgs: - { - TargetFinishedEvents.Add(targetFinishedEventArgs); - break; - } + { + TargetFinishedEvents.Add(targetFinishedEventArgs); + break; + } case TaskStartedEventArgs taskStartedEventArgs: - { - TaskStartedEvents.Add(taskStartedEventArgs); - break; - } + { + TaskStartedEvents.Add(taskStartedEventArgs); + break; + } case TaskFinishedEventArgs taskFinishedEventArgs: - { - TaskFinishedEvents.Add(taskFinishedEventArgs); - break; - } + { + TaskFinishedEvents.Add(taskFinishedEventArgs); + break; + } case BuildMessageEventArgs buildMessageEventArgs: - { - BuildMessageEvents.Add(buildMessageEventArgs); - break; - } + { + BuildMessageEvents.Add(buildMessageEventArgs); + break; + } case BuildStartedEventArgs buildStartedEventArgs: - { - BuildStartedEvents.Add(buildStartedEventArgs); - break; - } - case BuildFinishedEventArgs buildFinishedEventArgs: - { - BuildFinishedEvents.Add(buildFinishedEventArgs); - - if (!AllowTaskCrashes) { - // We should not have any task crashes. Sometimes a test will validate that their expected error - // code appeared, but not realize it then crashed. - AssertLogDoesntContain("MSB4018"); + BuildStartedEvents.Add(buildStartedEventArgs); + break; } + case BuildFinishedEventArgs buildFinishedEventArgs: + { + BuildFinishedEvents.Add(buildFinishedEventArgs); - // We should not have any Engine crashes. - AssertLogDoesntContain("MSB0001"); + if (!AllowTaskCrashes) + { + // We should not have any task crashes. Sometimes a test will validate that their expected error + // code appeared, but not realize it then crashed. + AssertLogDoesntContain("MSB4018"); + } - // Console.Write in the context of a unit test is very expensive. A hundred - // calls to Console.Write can easily take two seconds on a fast machine. Therefore, only - // do the Console.Write once at the end of the build. + // We should not have any Engine crashes. + AssertLogDoesntContain("MSB0001"); - PrintFullLog(); + // Console.Write in the context of a unit test is very expensive. A hundred + // calls to Console.Write can easily take two seconds on a fast machine. Therefore, only + // do the Console.Write once at the end of the build. - break; - } + PrintFullLog(); + + break; + } } } } @@ -434,7 +434,10 @@ internal void AssertLogContains(bool isCaseSensitive, params string[] contains) if (currentLine.Contains(comparer)) { index++; - if (index == contains.Length) break; + if (index == contains.Length) + { + break; + } } currentLine = reader.ReadLine(); diff --git a/src/Shared/UnitTests/NativeMethodsShared_Tests.cs b/src/Shared/UnitTests/NativeMethodsShared_Tests.cs index a5652d24cf0..e93424bcca7 100644 --- a/src/Shared/UnitTests/NativeMethodsShared_Tests.cs +++ b/src/Shared/UnitTests/NativeMethodsShared_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Shared/UnitTests/ObjectModelHelpers.cs b/src/Shared/UnitTests/ObjectModelHelpers.cs index a8f02e7d2cc..ac61dc8380c 100644 --- a/src/Shared/UnitTests/ObjectModelHelpers.cs +++ b/src/Shared/UnitTests/ObjectModelHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -418,26 +418,22 @@ internal static void AssertItemsMatch(string expectedItemsString, ITaskItem[] ac Assert.True( actualMetadataValue.Length > 0 || expectedMetadataValue.Length == 0, - string.Format("Item '{0}' does not have expected metadata '{1}'.", actualItem.ItemSpec, metadataName) - ); + string.Format("Item '{0}' does not have expected metadata '{1}'.", actualItem.ItemSpec, metadataName)); Assert.True( actualMetadataValue.Length == 0 || expectedMetadataValue.Length > 0, - string.Format("Item '{0}' has unexpected metadata {1}={2}.", actualItem.ItemSpec, metadataName, actualMetadataValue) - ); - - Assert.Equal( - expectedMetadataValue, - actualMetadataValue - // string.Format - // ( - // "Item '{0}' has metadata {1}={2} instead of expected {1}={3}.", - // actualItem.ItemSpec, - // metadataName, - // actualMetadataValue, - // expectedMetadataValue - // ) - ); + string.Format("Item '{0}' has unexpected metadata {1}={2}.", actualItem.ItemSpec, metadataName, actualMetadataValue)); + + Assert.Equal(expectedMetadataValue, actualMetadataValue); + + // string.Format + // ( + // "Item '{0}' has metadata {1}={2} instead of expected {1}={3}.", + // actualItem.ItemSpec, + // metadataName, + // actualMetadataValue, + // expectedMetadataValue + // ) } } expectedItems.RemoveAt(expectedItemIndex); @@ -710,23 +706,19 @@ internal static Project CreateInMemoryProject(ProjectCollection e, string xml, I /// /// May be null /// May be null - internal static Project CreateInMemoryProject - ( + internal static Project CreateInMemoryProject( ProjectCollection projectCollection, string xml, ILogger logger /* May be null */, - string toolsVersion /* may be null */ - ) + string toolsVersion) /* may be null */ { XmlReaderSettings readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }; - Project project = new Project - ( + Project project = new Project( XmlReader.Create(new StringReader(CleanupFileContents(xml)), readerSettings), null, toolsVersion, - projectCollection - ); + projectCollection); Guid guid = Guid.NewGuid(); project.FullPath = Path.Combine(TempProjectDir, "Temporary" + guid.ToString("N") + ".csproj"); @@ -746,22 +738,18 @@ string toolsVersion /* may be null */ /// /// /// - internal static MockLogger BuildProjectExpectSuccess - ( + internal static MockLogger BuildProjectExpectSuccess( string projectContents, - ITestOutputHelper testOutputHelper = null - ) + ITestOutputHelper testOutputHelper = null) { MockLogger logger = new MockLogger(testOutputHelper); BuildProjectExpectSuccess(projectContents, logger); return logger; } - internal static void BuildProjectExpectSuccess - ( + internal static void BuildProjectExpectSuccess( string projectContents, - params ILogger[] loggers - ) + params ILogger[] loggers) { Project project = CreateInMemoryProject(projectContents, logger: null); // logger is null so we take care of loggers ourselves project.Build(loggers).ShouldBeTrue(); @@ -773,10 +761,8 @@ params ILogger[] loggers /// /// /// - internal static MockLogger BuildProjectExpectFailure - ( - string projectContents - ) + internal static MockLogger BuildProjectExpectFailure( + string projectContents) { MockLogger logger = new MockLogger(); BuildProjectExpectFailure(projectContents, logger); @@ -784,11 +770,9 @@ string projectContents return logger; } - internal static void BuildProjectExpectFailure - ( + internal static void BuildProjectExpectFailure( string projectContents, - ILogger logger - ) + ILogger logger) { Project project = CreateInMemoryProject(projectContents, logger); @@ -802,11 +786,9 @@ ILogger logger /// /// /// - internal static void CompareProjectContents - ( + internal static void CompareProjectContents( Project project, - string newExpectedProjectContents - ) + string newExpectedProjectContents) { // Get the new XML for the project, normalizing the whitespace. string newActualProjectContents = project.Xml.RawXml; @@ -996,13 +978,11 @@ internal static Project LoadProjectFileInTempProjectDirectory(string projectFile /// Can be null. /// /// - internal static bool BuildTempProjectFileWithTargets - ( + internal static bool BuildTempProjectFileWithTargets( string projectFileRelativePath, string[] targets, IDictionary globalProperties, - ILogger logger - ) + ILogger logger) { // Build the default targets. List loggers = new List(1); @@ -1042,7 +1022,10 @@ internal static void DeleteTempFiles(string[] files) { for (int i = 0; i < files.Length; i++) { - if (FileSystems.Default.FileExists(files[i])) File.Delete(files[i]); + if (FileSystems.Default.FileExists(files[i])) + { + File.Delete(files[i]); + } } } @@ -1660,8 +1643,7 @@ internal static TransientTestFile CreateProjectFile( int[] projectReferences = null, Dictionary projectReferenceTargets = null, string defaultTargets = null, - string extraContent = null - ) + string extraContent = null) { var sb = new StringBuilder(64); @@ -1767,8 +1749,7 @@ internal static ProjectGraph CreateProjectGraph( entryProjectFiles, globalProperties ?? new Dictionary(), projectCollection ?? env.CreateProjectCollection() - .Collection - ); + .Collection); string GetExtraContent(int projectNum) { @@ -2208,8 +2189,7 @@ public override byte[] ReadFileAllBytes(string path) public override IEnumerable EnumerateFiles( string path, string searchPattern = "*", - SearchOption searchOption = SearchOption.TopDirectoryOnly - ) + SearchOption searchOption = SearchOption.TopDirectoryOnly) { IncrementCalls(ref _fileSystemCalls); @@ -2219,8 +2199,7 @@ public override IEnumerable EnumerateFiles( public override IEnumerable EnumerateDirectories( string path, string searchPattern = "*", - SearchOption searchOption = SearchOption.TopDirectoryOnly - ) + SearchOption searchOption = SearchOption.TopDirectoryOnly) { IncrementCalls(ref _fileSystemCalls); @@ -2230,8 +2209,7 @@ public override IEnumerable EnumerateDirectories( public override IEnumerable EnumerateFileSystemEntries( string path, string searchPattern = "*", - SearchOption searchOption = SearchOption.TopDirectoryOnly - ) + SearchOption searchOption = SearchOption.TopDirectoryOnly) { IncrementCalls(ref _fileSystemCalls); diff --git a/src/Shared/UnitTests/PrintLineDebugger_Tests.cs b/src/Shared/UnitTests/PrintLineDebugger_Tests.cs index a9cd5ddb7ff..761c0be4177 100644 --- a/src/Shared/UnitTests/PrintLineDebugger_Tests.cs +++ b/src/Shared/UnitTests/PrintLineDebugger_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #if DEBUG using System; using System.Collections.Generic; @@ -59,7 +60,7 @@ public void CompositeWriterCanWriteToMultipleWriters() var writer2 = new MockWriter(); var compositeWriter = new PrintLineDebuggerWriters.CompositeWriter( - new [] + new[] { writer1.Writer(), writer2.Writer() diff --git a/src/Shared/UnitTests/ResourceUtilities_Tests.cs b/src/Shared/UnitTests/ResourceUtilities_Tests.cs index c9cdaa5ff45..bfc98a664e2 100644 --- a/src/Shared/UnitTests/ResourceUtilities_Tests.cs +++ b/src/Shared/UnitTests/ResourceUtilities_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Xunit; diff --git a/src/Shared/UnitTests/StreamHelpers.cs b/src/Shared/UnitTests/StreamHelpers.cs index b2130e2458b..f4150ee4723 100644 --- a/src/Shared/UnitTests/StreamHelpers.cs +++ b/src/Shared/UnitTests/StreamHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -7,14 +7,14 @@ namespace Microsoft.Build.UnitTests { - sealed internal class StreamHelpers + internal sealed class StreamHelpers { /// /// Take a string and convert it to a StreamReader. /// /// /// - static internal StreamReader StringToStreamReader(string value) + internal static StreamReader StringToStreamReader(string value) { MemoryStream m = new MemoryStream(); #if FEATURE_ENCODING_DEFAULT diff --git a/src/Shared/UnitTests/TaskParameter_Tests.cs b/src/Shared/UnitTests/TaskParameter_Tests.cs index 9fdb8aa1c8d..a33b226229a 100644 --- a/src/Shared/UnitTests/TaskParameter_Tests.cs +++ b/src/Shared/UnitTests/TaskParameter_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -131,7 +131,7 @@ public void IntArrayParameter() Assert.Equal(15, wrappedParameter2[1]); } - enum TestEnumForParameter + private enum TestEnumForParameter { Something, SomethingElse diff --git a/src/Shared/UnitTests/TestAssemblyInfo.cs b/src/Shared/UnitTests/TestAssemblyInfo.cs index ef9c42456db..3491d4ebcee 100644 --- a/src/Shared/UnitTests/TestAssemblyInfo.cs +++ b/src/Shared/UnitTests/TestAssemblyInfo.cs @@ -1,4 +1,7 @@ -using System; +// 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.IO; using System.Linq; using System.Runtime.InteropServices; @@ -24,7 +27,7 @@ namespace Microsoft.Build.UnitTests { public class MSBuildTestAssemblyFixture : IDisposable { - bool _disposed; + private bool _disposed; private TestEnvironment _testEnvironment; public MSBuildTestAssemblyFixture() @@ -131,7 +134,7 @@ public void Dispose() public class MSBuildTestEnvironmentFixture : IDisposable { - bool _disposed; + private bool _disposed; private TestEnvironment _testEnvironment; public MSBuildTestEnvironmentFixture() diff --git a/src/Shared/UnitTests/TestData/GlobbingTestData.cs b/src/Shared/UnitTests/TestData/GlobbingTestData.cs index 58a898ebb5e..645154fd820 100644 --- a/src/Shared/UnitTests/TestData/GlobbingTestData.cs +++ b/src/Shared/UnitTests/TestData/GlobbingTestData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Shared/UnitTests/TestEnvironment.cs b/src/Shared/UnitTests/TestEnvironment.cs index 51ea0482d88..6e531508885 100644 --- a/src/Shared/UnitTests/TestEnvironment.cs +++ b/src/Shared/UnitTests/TestEnvironment.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -85,11 +85,15 @@ private void Cleanup() // Reset test variants foreach (var variant in _variants) + { variant.Revert(); + } // Assert invariants foreach (var item in _invariants) + { item.AssertInvariant(Output); + } SetEnvironmentVariable("MSBUILDDISABLEFEATURESFROMVERSION", ""); BuildEnvironmentHelper.ResetInstance_ForUnitTestsOnly(); @@ -414,7 +418,7 @@ void AssertDictionaryInclusion(IDictionary superset, IDictionary subset, string { // workaround for https://github.com/dotnet/msbuild/pull/3866 // if the initial environment had empty keys, then MSBuild will accidentally remove them via Environment.SetEnvironmentVariable - if (operation != "removed" || !string.IsNullOrEmpty((string) subset[key])) + if (operation != "removed" || !string.IsNullOrEmpty((string)subset[key])) { superset.Contains(key).ShouldBe(true, $"environment variable {operation}: {key}"); superset[key].ShouldBe(subset[key]); diff --git a/src/Shared/UnitTests/TestProgram.cs b/src/Shared/UnitTests/TestProgram.cs index 39524b6054b..6bb39ebf67d 100644 --- a/src/Shared/UnitTests/TestProgram.cs +++ b/src/Shared/UnitTests/TestProgram.cs @@ -1,8 +1,10 @@ -using System; -using System.Collections.Generic; +// 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.Collections.Generic; -class Program +internal class Program { public static int Main(string[] args) { diff --git a/src/Shared/UnitTests/TypeLoader_Dependencies_Tests.cs b/src/Shared/UnitTests/TypeLoader_Dependencies_Tests.cs index f9f2e430531..d1387eeb0b4 100644 --- a/src/Shared/UnitTests/TypeLoader_Dependencies_Tests.cs +++ b/src/Shared/UnitTests/TypeLoader_Dependencies_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; diff --git a/src/Shared/UnitTests/TypeLoader_Tests.cs b/src/Shared/UnitTests/TypeLoader_Tests.cs index 54aa9961901..742bfca4919 100644 --- a/src/Shared/UnitTests/TypeLoader_Tests.cs +++ b/src/Shared/UnitTests/TypeLoader_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -57,7 +57,7 @@ public void Regress_Mutation_ParameterOrderDoesntMatter() { Assert.True(TypeLoader.IsPartialTypeNameMatch("Csc", "Microsoft.Build.Tasks.Csc")); } - + [Fact] public void LoadNonExistingAssembly() @@ -140,7 +140,7 @@ public void LoadOutsideAssembly() } } - [Fact (Skip = "https://github.com/dotnet/msbuild/issues/325")] + [Fact(Skip = "https://github.com/dotnet/msbuild/issues/325")] public void LoadInsideAssemblyWhenGivenOutsideAssemblyWithSameName() { using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder)) diff --git a/src/Shared/UnitTests/XmakeAttributes_Tests.cs b/src/Shared/UnitTests/XmakeAttributes_Tests.cs index 3f51a4c8233..7f6c1016f2e 100644 --- a/src/Shared/UnitTests/XmakeAttributes_Tests.cs +++ b/src/Shared/UnitTests/XmakeAttributes_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; diff --git a/src/Shared/UnitTests/XmlUtilities_Tests.cs b/src/Shared/UnitTests/XmlUtilities_Tests.cs index 244ceaaa532..c8dd9ccdac6 100644 --- a/src/Shared/UnitTests/XmlUtilities_Tests.cs +++ b/src/Shared/UnitTests/XmlUtilities_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Shared/VersionUtilities.cs b/src/Shared/VersionUtilities.cs index 0266205b1ce..399f1871b85 100644 --- a/src/Shared/VersionUtilities.cs +++ b/src/Shared/VersionUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -96,7 +96,7 @@ internal static Version ConvertToVersion(string version, bool throwException) } } - sealed internal class ReverseStringGenericComparer : IComparer + internal sealed class ReverseStringGenericComparer : IComparer { /// /// Static accessor for a ReverseVersionGenericComparer @@ -113,7 +113,7 @@ int IComparer.Compare(string x, string y) } } - sealed internal class ReverseVersionGenericComparer : IComparer + internal sealed class ReverseVersionGenericComparer : IComparer { /// /// Static accessor for a ReverseVersionGenericComparer diff --git a/src/Shared/VisualStudioConstants.cs b/src/Shared/VisualStudioConstants.cs index e654b86e24b..b99fd731d21 100644 --- a/src/Shared/VisualStudioConstants.cs +++ b/src/Shared/VisualStudioConstants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Shared/XMakeAttributes.cs b/src/Shared/XMakeAttributes.cs index 94cd21f7169..cf101e49ced 100644 --- a/src/Shared/XMakeAttributes.cs +++ b/src/Shared/XMakeAttributes.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -248,14 +248,11 @@ internal static bool TryMergeRuntimeValues(string runtimeA, string runtimeB, out ( runtimeA.Equals(actualCurrentRuntime, StringComparison.OrdinalIgnoreCase) || runtimeA.Equals(MSBuildRuntimeValues.currentRuntime, StringComparison.OrdinalIgnoreCase) || - runtimeA.Equals(MSBuildRuntimeValues.any, StringComparison.OrdinalIgnoreCase) - ) && + runtimeA.Equals(MSBuildRuntimeValues.any, StringComparison.OrdinalIgnoreCase)) && ( runtimeB.Equals(actualCurrentRuntime, StringComparison.OrdinalIgnoreCase) || runtimeB.Equals(MSBuildRuntimeValues.currentRuntime, StringComparison.OrdinalIgnoreCase) || - runtimeB.Equals(MSBuildRuntimeValues.any, StringComparison.OrdinalIgnoreCase) - ) - ) + runtimeB.Equals(MSBuildRuntimeValues.any, StringComparison.OrdinalIgnoreCase))) { mergedRuntime = actualCurrentRuntime; return true; @@ -390,14 +387,11 @@ internal static bool TryMergeArchitectureValues(string architectureA, string arc ( architectureA.Equals(currentArchitecture, StringComparison.OrdinalIgnoreCase) || architectureA.Equals(MSBuildArchitectureValues.currentArchitecture, StringComparison.OrdinalIgnoreCase) || - architectureA.Equals(MSBuildArchitectureValues.any, StringComparison.OrdinalIgnoreCase) - ) && + architectureA.Equals(MSBuildArchitectureValues.any, StringComparison.OrdinalIgnoreCase)) && ( architectureB.Equals(currentArchitecture, StringComparison.OrdinalIgnoreCase) || architectureB.Equals(MSBuildArchitectureValues.currentArchitecture, StringComparison.OrdinalIgnoreCase) || - architectureB.Equals(MSBuildArchitectureValues.any, StringComparison.OrdinalIgnoreCase) - ) - ) + architectureB.Equals(MSBuildArchitectureValues.any, StringComparison.OrdinalIgnoreCase))) { mergedArchitecture = currentArchitecture; return true; diff --git a/src/Shared/XMakeElements.cs b/src/Shared/XMakeElements.cs index 26edc3345c2..15938e97587 100644 --- a/src/Shared/XMakeElements.cs +++ b/src/Shared/XMakeElements.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Shared/XmlUtilities.cs b/src/Shared/XmlUtilities.cs index 941958a13fe..e37749e172c 100644 --- a/src/Shared/XmlUtilities.cs +++ b/src/Shared/XmlUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -12,7 +12,7 @@ namespace Microsoft.Build.Shared /// /// This class contains utility methods for XML manipulation. /// - static internal class XmlUtilities + internal static class XmlUtilities { /// /// This method renames an XML element. Well, actually you can't directly @@ -50,11 +50,11 @@ internal static XmlElementWithLocation RenameXmlElement(XmlElementWithLocation o newElement.AppendChild(oldElement.FirstChild); } - - - // Add the new element in the same place the old element was. - oldElement.ParentNode?.ReplaceChild(newElement, oldElement); - + + + // Add the new element in the same place the old element was. + oldElement.ParentNode?.ReplaceChild(newElement, oldElement); + return newElement; } diff --git a/src/StringTools.Benchmark/Program.cs b/src/StringTools.Benchmark/Program.cs index cfda6e36d5f..0b51ad900e4 100644 --- a/src/StringTools.Benchmark/Program.cs +++ b/src/StringTools.Benchmark/Program.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using BenchmarkDotNet.Running; diff --git a/src/StringTools.Benchmark/SpanBasedStringBuilder_Benchmark.cs b/src/StringTools.Benchmark/SpanBasedStringBuilder_Benchmark.cs index d3e2dc5501d..b4cc4806e20 100644 --- a/src/StringTools.Benchmark/SpanBasedStringBuilder_Benchmark.cs +++ b/src/StringTools.Benchmark/SpanBasedStringBuilder_Benchmark.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using BenchmarkDotNet.Attributes; using System.Text; diff --git a/src/StringTools.UnitTests/InterningTestData.cs b/src/StringTools.UnitTests/InterningTestData.cs index e0ce99f19de..0e34b3ca39a 100644 --- a/src/StringTools.UnitTests/InterningTestData.cs +++ b/src/StringTools.UnitTests/InterningTestData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/StringTools.UnitTests/SpanBasedStringBuilder_Tests.cs b/src/StringTools.UnitTests/SpanBasedStringBuilder_Tests.cs index 4ce6f2c2cc2..1cd5bc6f38f 100644 --- a/src/StringTools.UnitTests/SpanBasedStringBuilder_Tests.cs +++ b/src/StringTools.UnitTests/SpanBasedStringBuilder_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if NET35_UNITTEST extern alias StringToolsNet35; diff --git a/src/StringTools.UnitTests/StringTools_Tests.cs b/src/StringTools.UnitTests/StringTools_Tests.cs index 3ad975ca3a0..233f2a12ee0 100644 --- a/src/StringTools.UnitTests/StringTools_Tests.cs +++ b/src/StringTools.UnitTests/StringTools_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if NET35_UNITTEST extern alias StringToolsNet35; diff --git a/src/StringTools.UnitTests/WeakStringCache_Tests.cs b/src/StringTools.UnitTests/WeakStringCache_Tests.cs index b2e1da93006..75c418f48ca 100644 --- a/src/StringTools.UnitTests/WeakStringCache_Tests.cs +++ b/src/StringTools.UnitTests/WeakStringCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if NET35_UNITTEST extern alias StringToolsNet35; @@ -108,7 +108,7 @@ private void AddStringsWithSameHashCode(int numberOfStrings) for (int i = 0; i < numberOfStrings; i++) { InternableString stringCopy = new InternableString(new string(cachedStrings[i].ToCharArray())); - string cachedStringFromCache =_cache.GetOrCreateEntry(ref stringCopy, out bool cacheHit); + string cachedStringFromCache = _cache.GetOrCreateEntry(ref stringCopy, out bool cacheHit); cacheHit.ShouldBeFalse(); cachedStringFromCache.ShouldNotBeSameAs(cachedStrings[i]); } diff --git a/src/StringTools/AssemblyInfo.cs b/src/StringTools/AssemblyInfo.cs index 0a8c0ee0a72..e2df1be8118 100644 --- a/src/StringTools/AssemblyInfo.cs +++ b/src/StringTools/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.CompilerServices; diff --git a/src/StringTools/InternableString.Simple.cs b/src/StringTools/InternableString.Simple.cs index 7dd2b72b9ac..cffe45afc46 100644 --- a/src/StringTools/InternableString.Simple.cs +++ b/src/StringTools/InternableString.Simple.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/StringTools/InternableString.cs b/src/StringTools/InternableString.cs index 6a2bbcc3473..413aad9fb88 100644 --- a/src/StringTools/InternableString.cs +++ b/src/StringTools/InternableString.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/StringTools/SpanBasedStringBuilder.Simple.cs b/src/StringTools/SpanBasedStringBuilder.Simple.cs index 86e38c2907f..6090363a24f 100644 --- a/src/StringTools/SpanBasedStringBuilder.Simple.cs +++ b/src/StringTools/SpanBasedStringBuilder.Simple.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/StringTools/SpanBasedStringBuilder.cs b/src/StringTools/SpanBasedStringBuilder.cs index 8bb5a13cc09..0bea471d8be 100644 --- a/src/StringTools/SpanBasedStringBuilder.cs +++ b/src/StringTools/SpanBasedStringBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/StringTools/StringTools.cs b/src/StringTools/StringTools.cs index 664057961b5..93b06619b5d 100644 --- a/src/StringTools/StringTools.cs +++ b/src/StringTools/StringTools.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/StringTools/WeakStringCache.Concurrent.cs b/src/StringTools/WeakStringCache.Concurrent.cs index 3261141fcbf..bf9373e798c 100644 --- a/src/StringTools/WeakStringCache.Concurrent.cs +++ b/src/StringTools/WeakStringCache.Concurrent.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/StringTools/WeakStringCache.Locking.cs b/src/StringTools/WeakStringCache.Locking.cs index 1000c4cbf7d..3ce4b0e7645 100644 --- a/src/StringTools/WeakStringCache.Locking.cs +++ b/src/StringTools/WeakStringCache.Locking.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/StringTools/WeakStringCache.cs b/src/StringTools/WeakStringCache.cs index cedde724390..5e3434fd4ef 100644 --- a/src/StringTools/WeakStringCache.cs +++ b/src/StringTools/WeakStringCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/StringTools/WeakStringCacheInterner.cs b/src/StringTools/WeakStringCacheInterner.cs index 34366af3cfc..dbf21b00b33 100644 --- a/src/StringTools/WeakStringCacheInterner.cs +++ b/src/StringTools/WeakStringCacheInterner.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -30,7 +30,7 @@ private enum InternResult /// private readonly WeakStringCache _weakStringCache = new WeakStringCache(); -#region Statistics + #region Statistics /// /// Number of times the regular interning path found the string in the cache. /// @@ -58,7 +58,7 @@ private enum InternResult /// private Dictionary? _internCallCountsByString; -#endregion + #endregion /// /// Try to intern the string. diff --git a/src/Tasks.UnitTests/Al_Tests.cs b/src/Tasks.UnitTests/Al_Tests.cs index 6d2d0884c8e..b1a777002cc 100644 --- a/src/Tasks.UnitTests/Al_Tests.cs +++ b/src/Tasks.UnitTests/Al_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Tasks; @@ -16,7 +16,7 @@ namespace Microsoft.Build.UnitTests * Test the AL task in various ways. * */ - sealed public class AlTests + public sealed class AlTests { /// /// Tests the AlgorithmId parameter diff --git a/src/Tasks.UnitTests/AppConfig_Tests.cs b/src/Tasks.UnitTests/AppConfig_Tests.cs index eb4762b3a62..a627834cc7d 100644 --- a/src/Tasks.UnitTests/AppConfig_Tests.cs +++ b/src/Tasks.UnitTests/AppConfig_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/Tasks.UnitTests/AspNetCompiler_Tests.cs b/src/Tasks.UnitTests/AspNetCompiler_Tests.cs index 2b49c25b8d6..0b3829c05e4 100644 --- a/src/Tasks.UnitTests/AspNetCompiler_Tests.cs +++ b/src/Tasks.UnitTests/AspNetCompiler_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Microsoft.Build.Evaluation; @@ -16,7 +16,7 @@ namespace Microsoft.Build.UnitTests * Test the AspNetCompiler task in various ways. * */ - sealed public class AspNetCompilerTests + public sealed class AspNetCompilerTests { [Fact] public void NoParameters() diff --git a/src/Tasks.UnitTests/AssemblyDependency/AssemblyFoldersFromConfig_Tests.cs b/src/Tasks.UnitTests/AssemblyDependency/AssemblyFoldersFromConfig_Tests.cs index a3dec6636fb..fdda7956108 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/AssemblyFoldersFromConfig_Tests.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/AssemblyFoldersFromConfig_Tests.cs @@ -1,4 +1,7 @@ -using System.IO; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.UnitTests; @@ -28,7 +31,7 @@ public AssemblyFoldersFromConfig_Tests(ITestOutputHelper output) : base(output) Path.Combine(s_rootPathPrefix, "assemblyfromconfig", "folder501000x86", "v5assembly.dll") }); } - + [Fact] public void AssemblyFoldersFromConfigTest() { @@ -42,10 +45,10 @@ public void AssemblyFoldersFromConfigTest() ResolveAssemblyReference t = new ResolveAssemblyReference { BuildEngine = new MockEngine(_output), - Assemblies = new ITaskItem[] {new TaskItem("assemblyfromconfig2")}, - SearchPaths = new[] {moniker} + Assemblies = new ITaskItem[] { new TaskItem("assemblyfromconfig2") }, + SearchPaths = new[] { moniker } }; - + Execute(t); Assert.Single(t.ResolvedFiles); @@ -71,8 +74,8 @@ public void AssemblyFoldersFromConfigPlatformSpecificAssemblyFirstTest() ResolveAssemblyReference t = new ResolveAssemblyReference { BuildEngine = new MockEngine(_output), - Assemblies = new ITaskItem[] {new TaskItem("assemblyfromconfig_common.dll")}, - SearchPaths = new[] {moniker}, + Assemblies = new ITaskItem[] { new TaskItem("assemblyfromconfig_common.dll") }, + SearchPaths = new[] { moniker }, TargetProcessorArchitecture = "x86" }; @@ -145,8 +148,8 @@ public void AssemblyFoldersFromConfigFileNotFoundTest() ResolveAssemblyReference t = new ResolveAssemblyReference { BuildEngine = new MockEngine(_output), - Assemblies = new ITaskItem[] {new TaskItem("assemblyfromconfig_common.dll")}, - SearchPaths = new[] {moniker}, + Assemblies = new ITaskItem[] { new TaskItem("assemblyfromconfig_common.dll") }, + SearchPaths = new[] { moniker }, TargetProcessorArchitecture = "x86" }; diff --git a/src/Tasks.UnitTests/AssemblyDependency/FilePrimary.cs b/src/Tasks.UnitTests/AssemblyDependency/FilePrimary.cs index 2f60c7dcd48..74fa0155f91 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/FilePrimary.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/FilePrimary.cs @@ -1,3 +1,6 @@ +// 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.IO; using Microsoft.Build.Framework; @@ -50,13 +53,11 @@ public void Exists() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -93,8 +94,7 @@ public void BadAppconfigOldVersion() // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + "\n" + "\n" + @@ -102,8 +102,7 @@ public void BadAppconfigOldVersion() "\n" + "\n" + "\n" + - "\n" - ); + "\n"); try { @@ -146,8 +145,7 @@ public void BadAppconfigNewVersion() // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + "\n" + "\n" + @@ -155,8 +153,7 @@ public void BadAppconfigNewVersion() "\n" + "\n" + "\n" + - "\n" - ); + "\n"); try { @@ -228,13 +225,11 @@ public void ExistsPromotedDependencyInTheBlackList() }; // Construct the app.config. - appConfigFile = WriteAppConfig - ( + appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -250,10 +245,8 @@ public void ExistsPromotedDependencyInTheBlackList() Assert.True(succeeded); Assert.Empty(t.ResolvedDependencyFiles); - engine.AssertLogDoesntContain - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogDoesntContain( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); } finally { @@ -290,13 +283,11 @@ public void ExistsDifferentName() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -343,13 +334,11 @@ public void ExistsOldVersionRange() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -396,13 +385,11 @@ public void HighVersionDoesntExist() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -447,13 +434,11 @@ public void LowVersionDoesntExist() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); diff --git a/src/Tasks.UnitTests/AssemblyDependency/GlobalAssemblyCacheTests.cs b/src/Tasks.UnitTests/AssemblyDependency/GlobalAssemblyCacheTests.cs index df51e79f8f4..fc611cfbcda 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/GlobalAssemblyCacheTests.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/GlobalAssemblyCacheTests.cs @@ -1,3 +1,6 @@ +// 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.Collections; using System.Collections.Generic; @@ -185,8 +188,7 @@ public void VerifyEmptyPublicKeyspecificVersion() { AssemblyNameExtension fusionName = new AssemblyNameExtension("System, PublicKeyToken="); string path = GlobalAssemblyCache.GetLocation(fusionName, SystemProcessorArchitecture.None, getRuntimeVersion, new Version("2.0.50727"), false, new FileExists(MockFileExists), _getPathFromFusionName, _gacEnumerator, true); - } - ); + }); } /// @@ -285,8 +287,7 @@ public void SystemRuntimeDepends_No_Build() // build mode t.FindDependencies = true; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -303,9 +304,7 @@ public void SystemRuntimeDepends_No_Build() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal("false", t.DependsOnSystemRuntime, true); // "Expected no System.Runtime dependency found during build." Assert.Equal("false", t.DependsOnNETStandard, true); // "Expected no netstandard dependency found during build." @@ -313,8 +312,7 @@ public void SystemRuntimeDepends_No_Build() // intelli build mode t.FindDependencies = false; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -331,9 +329,7 @@ public void SystemRuntimeDepends_No_Build() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal("false", t.DependsOnSystemRuntime, true); // "Expected no System.Runtime dependency found during intellibuild." Assert.Equal("false", t.DependsOnNETStandard, true); // "Expected no netstandard dependency found during intellibuild." @@ -361,8 +357,7 @@ public void SystemRuntimeDepends_Yes() t.FindDependencies = true; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -379,17 +374,14 @@ public void SystemRuntimeDepends_Yes() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during build." // intelli build mode t.FindDependencies = false; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -406,9 +398,7 @@ public void SystemRuntimeDepends_Yes() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during intellibuild." } @@ -435,8 +425,7 @@ public void SystemRuntimeDepends_Yes_Indirect() t.FindDependencies = true; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -453,17 +442,14 @@ public void SystemRuntimeDepends_Yes_Indirect() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during build." // intelli build mode t.FindDependencies = false; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -480,9 +466,7 @@ public void SystemRuntimeDepends_Yes_Indirect() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal("true", t.DependsOnSystemRuntime, true); // "Expected System.Runtime dependency found during intellibuild." } diff --git a/src/Tasks.UnitTests/AssemblyDependency/InstalledSDKResolverFixture.cs b/src/Tasks.UnitTests/AssemblyDependency/InstalledSDKResolverFixture.cs index 8f295e908d8..d502a4a7486 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/InstalledSDKResolverFixture.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/InstalledSDKResolverFixture.cs @@ -1,3 +1,6 @@ +// 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 Microsoft.Build.Framework; using Microsoft.Build.Tasks; diff --git a/src/Tasks.UnitTests/AssemblyDependency/Miscellaneous.cs b/src/Tasks.UnitTests/AssemblyDependency/Miscellaneous.cs index 01d46289a95..750c73b673e 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/Miscellaneous.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/Miscellaneous.cs @@ -1,3 +1,6 @@ +// 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.Collections; using System.Collections.Generic; @@ -2473,16 +2476,12 @@ public void Regress242970() // For {CandidateAssemblyFiles} we don't even want to see a comment logged for files with non-standard extensions. // This is because {CandidateAssemblyFiles} is very likely to contain non-assemblies and its best not to clutter // up the log. - engine.AssertLogDoesntContain - ( - String.Format(".hiddenfile") - ); + engine.AssertLogDoesntContain( + String.Format(".hiddenfile")); // ...but we do want to see a log entry for standard extensions, even if the base file name is empty. - engine.AssertLogContains - ( - String.Format(@"NonUI\testDirectoryRoot\.dll") - ); + engine.AssertLogContains( + String.Format(@"NonUI\testDirectoryRoot\.dll")); } /// @@ -3198,10 +3197,8 @@ public void Regress444793() Assert.True(succeeded); engine.AssertLogDoesntContain("MSB4018"); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("General.MalformedAssemblyName"), "c:\\DoesntExist\\System.Xml.dll") - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("General.MalformedAssemblyName"), "c:\\DoesntExist\\System.Xml.dll")); } /// @@ -3222,10 +3219,8 @@ public void RawFileNameDoesntExist() bool succeeded = Execute(t); Assert.True(succeeded); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("General.MalformedAssemblyName"), "c:\\DoesntExist\\System.Xml.dll") - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("General.MalformedAssemblyName"), "c:\\DoesntExist\\System.Xml.dll")); } /// @@ -3437,7 +3432,7 @@ public void ResolveBadImageInSecondary() // There should have been no warning about the exception because it's only a dependency Assert.Equal(0, engine.Warnings); - + // There should have been no ugly callstack dumped engine.AssertLogDoesntContain("Microsoft.Build.UnitTests"); } @@ -4932,11 +4927,9 @@ public void Regress276548_AssemblyNameDifferentThanFusionName() { new TaskItem("A") }; - t.Assemblies[0].SetMetadata - ( + t.Assemblies[0].SetMetadata( "HintPath", - @"c:\MyNameMismatch\Foo.dll" - ); + @"c:\MyNameMismatch\Foo.dll"); t.SearchPaths = new string[] { @@ -4968,11 +4961,9 @@ public void Regress314573_VeryLongPaths() { new TaskItem("A") // Resolved by HintPath }; - t.Assemblies[0].SetMetadata - ( + t.Assemblies[0].SetMetadata( "HintPath", - veryLongFile - ); + veryLongFile); t.SearchPaths = new string[] { @@ -5140,11 +5131,9 @@ public void Regress271273_BogusAppConfig() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" - ); + " \n"); try { @@ -5227,13 +5216,11 @@ public void Regress339786_CrossVersionsWithAppConfig() t.Assemblies[1].SetMetadata("HintPath", @"C:\Regress339786\FolderA\A.dll"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); t.AppConfigFile = appConfigFile; try @@ -5306,13 +5293,11 @@ public void Regress407623_RedistListDoesNotImplyPresenceInFrameworks() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistFile) }; @@ -5392,13 +5377,11 @@ public void Regress435487_FxFileResolvedByHintPathShouldByCopyLocal() try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistFile) }; @@ -5423,16 +5406,14 @@ public void PartialNameMatchingFromRedist() try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + // Simple name match where everything is the same except for version "" + "" + "" + - "" - ); + ""); AssemblyName v1 = new AssemblyName("A, Culture=de-DE, PublicKeyToken=a5d015c7d5a0b012, Version=1.0.0.0"); AssemblyName v2 = new AssemblyName("A, Culture=Neutral, PublicKeyToken=a5d015c7d5a0b012, Version=2.0.0.0"); @@ -5716,8 +5697,7 @@ public void RedistListGenerateBlackListNotFoundSubsetFiles() new AssemblyTableInfo("c:\\AnotherRandomDirectory.xml", "TargetFrameworkDirectory") }, whiteListErrors, - whiteListErrorFileNames - ); + whiteListErrorFileNames); // Since there were no white list expect the black list to return null Assert.Empty(blackList); // "Expected to have no assemblies in the black list" @@ -5741,11 +5721,9 @@ public void RedistListGenerateBlackListGarbageSubsetListFiles() string garbageSubsetFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( garbageSubsetFile, - "RandomGarbage, i am a bad file with random goo rather than anything important" - ); + "RandomGarbage, i am a bad file with random goo rather than anything important"); AssemblyTableInfo redistListInfo = new AssemblyTableInfo(redistFile, "TargetFrameworkDirectory"); AssemblyTableInfo subsetListInfo = new AssemblyTableInfo(garbageSubsetFile, "TargetFrameworkDirectory"); @@ -5979,11 +5957,9 @@ public void RedistListNoAssembliesinRedistList() File.WriteAllText(subsetListPath, _xmlOnlySubset); try { - File.WriteAllText - ( + File.WriteAllText( redistListPath, - "RANDOMBOOOOOGOOGOOG" - ); + "RANDOMBOOOOOGOOGOOG"); t.InstalledAssemblyTables = new ITaskItem[] { new TaskItem(redistListPath) }; t.IgnoreDefaultInstalledAssemblyTables = true; @@ -6122,15 +6098,13 @@ public void RedistListGenerateBlackListGoodListsSubsetIsSuperSet() string goodSubsetFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( goodSubsetFile, "" + "" + "" + "" + - "" - ); + ""); AssemblyTableInfo redistListInfo = new AssemblyTableInfo(redistFile, "TargetFrameworkDirectory"); AssemblyTableInfo subsetListInfo = new AssemblyTableInfo(goodSubsetFile, "TargetFrameworkDirectory"); @@ -6234,8 +6208,7 @@ public void SubsetListFinderNullFrameworkDirectory() { SubsetListFinder finder = new SubsetListFinder(Array.Empty()); finder.GetSubsetListPathsFromDisk(null); - } - ); + }); } /// /// Test the case where the subsetsToSearchFor are passed in as null @@ -6246,8 +6219,7 @@ public void SubsetListFinderNullSubsetToSearchFor() Assert.Throws(() => { SubsetListFinder finder = new SubsetListFinder(null); - } - ); + }); } /// /// Test the case where the subsetsToSearchFor are an empty array @@ -7060,8 +7032,7 @@ public void TestProfileNameNull() { ResolveAssemblyReference rar = new ResolveAssemblyReference(); rar.ProfileName = null; - } - ); + }); } /// /// Make sure we get an argument null exception when the ProfileFullFrameworkFolders is set to null @@ -7073,8 +7044,7 @@ public void TestProfileFullFrameworkFoldersFoldersNull() { ResolveAssemblyReference rar = new ResolveAssemblyReference(); rar.FullFrameworkFolders = null; - } - ); + }); } /// /// Make sure we get an argument null exception when the ProfileFullFrameworkAssemblyTables is set to null @@ -7086,8 +7056,7 @@ public void TestProfileFullFrameworkAssemblyTablesNull() { ResolveAssemblyReference rar = new ResolveAssemblyReference(); rar.FullFrameworkAssemblyTables = null; - } - ); + }); } /// /// Verify that setting a subset and a profile at the same time will cause an error to be logged and rar to return false @@ -7381,8 +7350,7 @@ public void NullInstalledSubsetTables() { ResolveAssemblyReference reference = new ResolveAssemblyReference(); reference.InstalledAssemblySubsetTables = null; - } - ); + }); } /// /// Verify the case where the targetFrameworkSubsets are null @@ -7394,8 +7362,7 @@ public void NullTargetFrameworkSubsets() { ResolveAssemblyReference reference = new ResolveAssemblyReference(); reference.TargetFrameworkSubsets = null; - } - ); + }); } /// /// Verify the case where the FulltargetFrameworkSubsetNames are null @@ -7407,8 +7374,7 @@ public void NullFullTargetFrameworkSubsetNames() { ResolveAssemblyReference reference = new ResolveAssemblyReference(); reference.FullTargetFrameworkSubsetNames = null; - } - ); + }); } /// /// Test the case where a non existent subset list path is used and no additional subsets are passed in. @@ -7937,10 +7903,8 @@ public void Regress315619_TwoWeaklyNamedPrimariesIsInsoluble() Execute(t); - e.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.ConflictUnsolvable"), @"MyAssembly, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", "MyAssembly, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=null") - ); + e.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.ConflictUnsolvable"), @"MyAssembly, Version=2.0.0.0, Culture=Neutral, PublicKeyToken=null", "MyAssembly, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=null")); } /// @@ -7981,15 +7945,13 @@ public void ForwardRedistRoot() try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + "" + "" + - "" - ); + ""); t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistFile) }; @@ -8111,8 +8073,7 @@ public void VerifyGetSimpleNamesIsSorted() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + @@ -8121,8 +8082,7 @@ public void VerifyGetSimpleNamesIsSorted() "" + "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8158,13 +8118,11 @@ public void VerifyAssemblyInRedistListNonWindowsRedistName() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8188,13 +8146,11 @@ public void VerifyAssemblyInRedistListWindowsRedistName() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8218,13 +8174,11 @@ public void VerifyAssemblyInRedistListPartialMatches() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8260,13 +8214,11 @@ public void VerifyAssemblyInRedistListDiffVersion() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8291,13 +8243,11 @@ public void VerifyAssemblyInRedistListDiffPublicKey() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8322,13 +8272,11 @@ public void VerifyAssemblyInRedistListDiffCulture() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); @@ -8353,13 +8301,11 @@ public void VerifyAssemblyInRedistListDiffSimpleName() string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, "" + "" + - "" - ); + ""); AssemblyTableInfo tableInfo = new AssemblyTableInfo(redistFile, "DoesNotExist"); RedistList redist = RedistList.GetRedistList(new AssemblyTableInfo[] { tableInfo }); diff --git a/src/Tasks.UnitTests/AssemblyDependency/NonSpecificVersionStrictPrimary.cs b/src/Tasks.UnitTests/AssemblyDependency/NonSpecificVersionStrictPrimary.cs index f3eb199906b..33ab353147d 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/NonSpecificVersionStrictPrimary.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/NonSpecificVersionStrictPrimary.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; @@ -20,7 +23,7 @@ public NonSpecificVersionStrictPrimary(ITestOutputHelper output) : base(output) /// Return the default search paths. /// /// - new internal string[] DefaultPaths + internal new string[] DefaultPaths { get { return new string[] { s_myComponentsV05Path, s_myComponentsV10Path, s_myComponentsV20Path, s_myComponentsV30Path }; } } @@ -55,13 +58,11 @@ public void Exists() // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -109,13 +110,11 @@ public void ExistsDifferentName() assemblyNames[0].SetMetadata("SpecificVersion", "false"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -164,13 +163,11 @@ public void ExistsOldVersionRange() assemblyNames[0].SetMetadata("SpecificVersion", "false"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -218,13 +215,11 @@ public void HighVersionDoesntExist() assemblyNames[0].SetMetadata("SpecificVersion", "false"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -272,13 +267,11 @@ public void LowVersionDoesntExist() assemblyNames[0].SetMetadata("SpecificVersion", "false"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); diff --git a/src/Tasks.UnitTests/AssemblyDependency/Perf.cs b/src/Tasks.UnitTests/AssemblyDependency/Perf.cs index e5eddbe032a..7564fe66bff 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/Perf.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/Perf.cs @@ -1,3 +1,6 @@ +// 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.Collections.Generic; using Microsoft.Build.Framework; diff --git a/src/Tasks.UnitTests/AssemblyDependency/ReferenceTests.cs b/src/Tasks.UnitTests/AssemblyDependency/ReferenceTests.cs index c71984f0c87..800790125d1 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/ReferenceTests.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/ReferenceTests.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using Microsoft.Build.Framework; using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; diff --git a/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceCacheSerialization.cs b/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceCacheSerialization.cs index 7cf61ab2860..8c5291e2f7a 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceCacheSerialization.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceCacheSerialization.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceTestFixture.cs b/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceTestFixture.cs index 0ac1240605f..690a1eb3dd8 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceTestFixture.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/ResolveAssemblyReferenceTestFixture.cs @@ -1,3 +1,6 @@ +// 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.Collections; using System.Collections.Concurrent; @@ -1051,8 +1054,7 @@ internal static AssemblyNameExtension GetAssemblyName(string path) if ( - String.Equals(path, @"c:\OldClrBug\MyFileLoadExceptionAssembly.dll", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(path, @"c:\OldClrBug\MyFileLoadExceptionAssembly.dll", StringComparison.OrdinalIgnoreCase)) { // An older LKG of the CLR could throw a FileLoadException if it doesn't recognize // the assembly. We need to support this for dogfooding purposes. @@ -1061,8 +1063,7 @@ internal static AssemblyNameExtension GetAssemblyName(string path) if ( - String.Equals(path, @"c:\Regress313086\mscorlib.dll", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(path, @"c:\Regress313086\mscorlib.dll", StringComparison.OrdinalIgnoreCase)) { // This is an mscorlib that returns null for its assembly name. return null; @@ -1070,8 +1071,7 @@ internal static AssemblyNameExtension GetAssemblyName(string path) if ( - String.Equals(path, Path.Combine(s_myVersion20Path, "BadImage.dll"), StringComparison.OrdinalIgnoreCase) - ) + String.Equals(path, Path.Combine(s_myVersion20Path, "BadImage.dll"), StringComparison.OrdinalIgnoreCase)) { throw new System.BadImageFormatException(@"The format of the file '" + Path.Combine(s_myVersion20Path, "BadImage.dll") + "' is invalid"); } @@ -1080,8 +1080,7 @@ internal static AssemblyNameExtension GetAssemblyName(string path) ( String.Equals(path, Path.Combine(s_myProjectPath, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) || String.Equals(path, Path.Combine(s_myVersion20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) - || String.Equals(path, Path.Combine(s_myVersionPocket20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) - ) + || String.Equals(path, Path.Combine(s_myVersionPocket20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase)) { // This is an mscorlib.dll with no metadata. return null; @@ -1090,8 +1089,7 @@ internal static AssemblyNameExtension GetAssemblyName(string path) if ( String.Equals(path, Path.Combine(s_myVersion20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) - || String.Equals(path, Path.Combine(s_myVersionPocket20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) - ) + || String.Equals(path, Path.Combine(s_myVersionPocket20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase)) { // This is an mscorlib.dll with no metadata. return null; @@ -1256,8 +1254,7 @@ internal static AssemblyNameExtension GetAssemblyName(string path) if ( - String.Equals(path, Path.Combine(s_myVersion20Path, "System.Data.dll"), StringComparison.OrdinalIgnoreCase) - ) + String.Equals(path, Path.Combine(s_myVersion20Path, "System.Data.dll"), StringComparison.OrdinalIgnoreCase)) { // Simulate a strongly named assembly. return new AssemblyNameExtension(AssemblyRef.SystemData); @@ -1792,14 +1789,12 @@ internal static AssemblyNameExtension GetAssemblyName(string path) /// Receives the list of dependencies. /// Receives the list of associated scatter files. /// Receives the assembly framework name. - internal static void GetAssemblyMetadata - ( + internal static void GetAssemblyMetadata( string path, ConcurrentDictionary assemblyMetadataCache, out AssemblyNameExtension[] dependencies, out string[] scatterFiles, - out FrameworkNameVersioning frameworkName - ) + out FrameworkNameVersioning frameworkName) { dependencies = GetDependencies(path); scatterFiles = null; @@ -1818,10 +1813,8 @@ out FrameworkNameVersioning frameworkName /// /// Cached implementation. Given an assembly name, crack it open and retrieve the TargetFrameworkAttribute /// - internal static FrameworkNameVersioning GetTargetFrameworkAttribute - ( - string path - ) + internal static FrameworkNameVersioning GetTargetFrameworkAttribute( + string path) { FrameworkNameVersioning frameworkName = null; @@ -2095,8 +2088,7 @@ internal static AssemblyNameExtension[] GetDependencies(string path) if ( String.Equals(path, Path.Combine(s_myVersion20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) - || String.Equals(path, Path.Combine(s_myVersionPocket20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase) - ) + || String.Equals(path, Path.Combine(s_myVersionPocket20Path, "mscorlib.dll"), StringComparison.OrdinalIgnoreCase)) { return Array.Empty(); } @@ -2611,16 +2603,14 @@ private static IEnumerable GetRegistrySubKeyNames(RegistryKey baseKey, s || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v1.0\AssemblyFoldersEx\Infragistics.MyControlWithPastTargetNDPVersion.1.0", StringComparison.OrdinalIgnoreCase) || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.x86chk\AssemblyFoldersEx\RawDropControls", StringComparison.OrdinalIgnoreCase) || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\ZControlA", StringComparison.OrdinalIgnoreCase) - || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\ZControlB", StringComparison.OrdinalIgnoreCase) - ) + || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\ZControlB", StringComparison.OrdinalIgnoreCase)) { return Array.Empty(); } if ( - String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0", StringComparison.OrdinalIgnoreCase)) { // This control has a service pack return new string[] { "sp1", "sp2" }; @@ -2813,32 +2803,28 @@ private static string GetRegistrySubKeyDefaultValue(RegistryKey baseKey, string ( String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithFutureTargetNDPVersion.1.0", StringComparison.OrdinalIgnoreCase) || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithPastTargetNDPVersion.1.0", StringComparison.OrdinalIgnoreCase) - || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0", StringComparison.OrdinalIgnoreCase) - ) + || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0", StringComparison.OrdinalIgnoreCase)) { return s_myComponentsV20Path; } if ( - String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0", StringComparison.OrdinalIgnoreCase)) { return @"C:\MyComponentBase"; } if ( - String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0\sp1", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0\sp1", StringComparison.OrdinalIgnoreCase)) { return @"C:\MyComponentServicePack1"; } if ( - String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0\sp2", StringComparison.OrdinalIgnoreCase) - ) + String.Equals(subKey, @"Software\Microsoft\.NetFramework\v2.0.50727\AssemblyFoldersEx\Infragistics.MyControlWithServicePack.1.0\sp2", StringComparison.OrdinalIgnoreCase)) { return @"C:\MyComponentServicePack2"; } @@ -2846,8 +2832,7 @@ private static string GetRegistrySubKeyDefaultValue(RegistryKey baseKey, string if ( String.Equals(subKey, @"Software\Microsoft\.NetFramework\v1.0\AssemblyFoldersEx\Infragistics.MyNDP1Control.1.0", StringComparison.OrdinalIgnoreCase) - || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v1.0\AssemblyFoldersEx\Infragistics.MyControlWithPastTargetNDPVersion.1.0", StringComparison.OrdinalIgnoreCase) - ) + || String.Equals(subKey, @"Software\Microsoft\.NetFramework\v1.0\AssemblyFoldersEx\Infragistics.MyControlWithPastTargetNDPVersion.1.0", StringComparison.OrdinalIgnoreCase)) { return s_myComponentsV10Path; } @@ -3010,26 +2995,24 @@ protected static bool Execute(ResolveAssemblyReference t, bool buildConsistencyC t.FindSerializationAssemblies = false; t.FindRelatedFiles = false; t.StateFile = null; - t.Execute - ( - fileExists, - directoryExists, - getDirectories, - getAssemblyName, - getAssemblyMetadata, - #if FEATURE_WIN32_REGISTRY - getRegistrySubKeyNames, - getRegistrySubKeyDefaultValue, - #endif - getLastWriteTime, - getRuntimeVersion, - #if FEATURE_WIN32_REGISTRY - openBaseKey, - #endif - checkIfAssemblyIsInGac, - isWinMDFile, - readMachineTypeFromPEHeader - ); + t.Execute( + fileExists, + directoryExists, + getDirectories, + getAssemblyName, + getAssemblyMetadata, +#if FEATURE_WIN32_REGISTRY + getRegistrySubKeyNames, + getRegistrySubKeyDefaultValue, +#endif + getLastWriteTime, + getRuntimeVersion, +#if FEATURE_WIN32_REGISTRY + openBaseKey, +#endif + checkIfAssemblyIsInGac, + isWinMDFile, + readMachineTypeFromPEHeader); // A few checks. These should always be true or it may be a perf issue for project load. ITaskItem[] loadModeResolvedFiles = Array.Empty(); @@ -3071,27 +3054,25 @@ protected static bool Execute(ResolveAssemblyReference t, bool buildConsistencyC string cache = rarCacheFile; t.StateFile = cache; File.Delete(t.StateFile); - succeeded = - t.Execute - ( - fileExists, - directoryExists, - getDirectories, - getAssemblyName, - getAssemblyMetadata, - #if FEATURE_WIN32_REGISTRY - getRegistrySubKeyNames, - getRegistrySubKeyDefaultValue, - #endif - getLastWriteTime, - getRuntimeVersion, - #if FEATURE_WIN32_REGISTRY - openBaseKey, - #endif - checkIfAssemblyIsInGac, - isWinMDFile, - readMachineTypeFromPEHeader - ); + succeeded = + t.Execute( + fileExists, + directoryExists, + getDirectories, + getAssemblyName, + getAssemblyMetadata, +#if FEATURE_WIN32_REGISTRY + getRegistrySubKeyNames, + getRegistrySubKeyDefaultValue, +#endif + getLastWriteTime, + getRuntimeVersion, +#if FEATURE_WIN32_REGISTRY + openBaseKey, +#endif + checkIfAssemblyIsInGac, + isWinMDFile, + readMachineTypeFromPEHeader); if (FileUtilities.FileExistsNoThrow(t.StateFile)) { Assert.Single(t.FilesWritten); @@ -3153,11 +3134,9 @@ internal void ExecuteRAROnItemsAndRedist(ResolveAssemblyReference t, MockEngine string redistFile = FileUtilities.GetTemporaryFileName(); try { - File.WriteAllText - ( + File.WriteAllText( redistFile, - redistString - ); + redistString); t.InstalledAssemblyTables = new TaskItem[] { new TaskItem(redistFile) }; diff --git a/src/Tasks.UnitTests/AssemblyDependency/SpecificVersionPrimary.cs b/src/Tasks.UnitTests/AssemblyDependency/SpecificVersionPrimary.cs index 5a9399898b1..e845e40d540 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/SpecificVersionPrimary.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/SpecificVersionPrimary.cs @@ -1,3 +1,6 @@ +// 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.IO; using Microsoft.Build.Framework; @@ -51,13 +54,11 @@ public void Exists() assemblyNames[0].SetMetadata("SpecificVersion", "true"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -118,13 +119,11 @@ public void ExistsDifferentName() assemblyNames[0].SetMetadata("SpecificVersion", "true"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -173,13 +172,11 @@ public void ExistsOldVersionRange() assemblyNames[0].SetMetadata("SpecificVersion", "true"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -228,13 +225,11 @@ public void HighVersionDoesntExist() assemblyNames[0].SetMetadata("SpecificVersion", "true"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -282,13 +277,11 @@ public void LowVersionDoesntExist() assemblyNames[0].SetMetadata("SpecificVersion", "true"); // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); diff --git a/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependency.cs b/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependency.cs index e44eed3c3b8..6c39feba98b 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependency.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependency.cs @@ -1,3 +1,6 @@ +// 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.Collections.Generic; using System.IO; @@ -23,10 +26,10 @@ public StronglyNamedDependency(ITestOutputHelper output) : base(output) /// Return the default search paths. /// /// - new internal string[] DefaultPaths - { - get { return new string[] { s_myApp_V10Path, @"C:\Framework\Whidbey", @"C:\Framework\Everett" }; } - } + internal new string[] DefaultPaths + { + get { return new string[] { s_myApp_V10Path, @"C:\Framework\Whidbey", @"C:\Framework\Everett" }; } + } /// /// In this case, @@ -41,7 +44,7 @@ public StronglyNamedDependency(ITestOutputHelper output) : base(output) /// We automatically unify FX dependencies. /// [Fact] - [Trait("Category", "mono-osx-failing")] + [Trait("Category", "mono-osx-failing")] public void Exists() { // This WriteLine is a hack. On a slow machine, the Tasks unittest fails because remoting @@ -73,15 +76,11 @@ public void Exists() t.ResolvedDependencyFiles[0].GetMetadata("FusionName") .ShouldBe("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKey, StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByFrameworkRetarget"), "1.0.5000.0", Path.Combine(s_myApp_V10Path, "DependsOnEverettSystem.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByFrameworkRetarget"), "1.0.5000.0", Path.Combine(s_myApp_V10Path, "DependsOnEverettSystem.dll"))); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.NotCopyLocalBecausePrerequisite")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.NotCopyLocalBecausePrerequisite"))); t.ResolvedDependencyFiles[0].GetMetadata("CopyLocal").ShouldBe("false", StringCompareShould.IgnoreCase); } @@ -116,16 +115,14 @@ public void HighVersionDoesntExist() t.BuildEngine = engine; t.Assemblies = assemblyNames; - t.SearchPaths = new string[] { s_myApp_V10Path, @"C:\Framework\Everett" }; + t.SearchPaths = new string[] { s_myApp_V10Path, @"C:\Framework\Everett" }; bool succeeded = Execute(t); Assert.True(succeeded); Assert.Empty(t.ResolvedDependencyFiles); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByFrameworkRetarget"), "1.0.5000.0", Path.Combine(s_myApp_V10Path, "DependsOnEverettSystem.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByFrameworkRetarget"), "1.0.5000.0", Path.Combine(s_myApp_V10Path, "DependsOnEverettSystem.dll"))); } [Fact] @@ -133,8 +130,8 @@ public void VerifyAssemblyPulledOutOfFrameworkDoesntGetFrameworkFileAttribute() { MockEngine e = new MockEngine(_output); - string actualFrameworkDirectory = s_myVersion20Path; - string alternativeFrameworkDirectory = s_myVersion40Path; + string actualFrameworkDirectory = s_myVersion20Path; + string alternativeFrameworkDirectory = s_myVersion40Path; ITaskItem[] items = new TaskItem[] { new TaskItem(Path.Combine(actualFrameworkDirectory, "System.dll")) }; diff --git a/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAppConfig.cs b/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAppConfig.cs index 3bb0ff19545..1c67ddd8750 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAppConfig.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAppConfig.cs @@ -1,3 +1,6 @@ +// 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.IO; using Microsoft.Build.Framework; @@ -22,9 +25,9 @@ public StronglyNamedDependencyAppConfig(ITestOutputHelper output) : base(output) /// Return the default search paths. /// /// - new internal string[] DefaultPaths - { - get { return new string[] { s_myApp_V05Path, s_myApp_V10Path, s_myComponentsV05Path, s_myComponentsV10Path, s_myComponentsV20Path, s_myComponentsV30Path }; } + internal new string[] DefaultPaths + { + get { return new string[] { s_myApp_V05Path, s_myApp_V10Path, s_myComponentsV05Path, s_myComponentsV10Path, s_myComponentsV20Path, s_myComponentsV30Path }; } } @@ -52,13 +55,11 @@ public void Exists() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -73,10 +74,8 @@ public void Exists() Assert.True(succeeded); Assert.Single(t.ResolvedDependencyFiles); t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // Cleanup. File.Delete(appConfigFile); @@ -127,13 +126,11 @@ public void ExistsPromotedDependencyInTheBlackList() }; // Construct the app.config. - appConfigFile = WriteAppConfig - ( + appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -149,10 +146,8 @@ public void ExistsPromotedDependencyInTheBlackList() Assert.True(succeeded); Assert.Empty(t.ResolvedDependencyFiles); - engine.AssertLogDoesntContain - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogDoesntContain( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); } finally { @@ -190,13 +185,11 @@ public void ExistsDifferentName() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -242,13 +235,11 @@ public void ExistsOldVersionRange() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -263,10 +254,8 @@ public void ExistsOldVersionRange() Assert.True(succeeded); Assert.Single(t.ResolvedDependencyFiles); t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // Cleanup. File.Delete(appConfigFile); @@ -298,13 +287,11 @@ public void HighVersionDoesntExist() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -320,28 +307,20 @@ public void HighVersionDoesntExist() Assert.Empty(t.ResolvedDependencyFiles); string shouldContain; - string code = t.Log.ExtractMessageCode - ( + string code = t.Log.ExtractMessageCode( String.Format(AssemblyResources.GetString("ResolveAssemblyReference.FailedToResolveReference"), String.Format(AssemblyResources.GetString("General.CouldNotLocateAssembly"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")), - out shouldContain - ); + out shouldContain); - engine.AssertLogContains - ( - shouldContain - ); + engine.AssertLogContains( + shouldContain); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UNIFyMe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); @@ -374,13 +353,11 @@ public void LowVersionDoesntExist() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -395,10 +372,8 @@ public void LowVersionDoesntExist() Assert.True(succeeded); Assert.Single(t.ResolvedDependencyFiles); t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "0.5.0.0", appConfigFile, Path.Combine(s_myApp_V05Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "0.5.0.0", appConfigFile, Path.Combine(s_myApp_V05Path, "DependsOnUnified.dll"))); // Cleanup. File.Delete(appConfigFile); @@ -424,13 +399,11 @@ public void GarbageVersionInAppConfigFile() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -468,13 +441,11 @@ public void GarbageAppConfigMissingOldVersion() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -487,10 +458,8 @@ public void GarbageAppConfigMissingOldVersion() bool succeeded = Execute(t); Assert.False(succeeded); Assert.Equal(1, engine.Errors); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("AppConfig.BindingRedirectMissingOldVersion")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("AppConfig.BindingRedirectMissingOldVersion"))); // Cleanup. File.Delete(appConfigFile); @@ -516,13 +485,11 @@ public void GarbageAppConfigMissingNewVersion() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -535,10 +502,8 @@ public void GarbageAppConfigMissingNewVersion() bool succeeded = Execute(t); Assert.False(succeeded); Assert.Equal(1, engine.Errors); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("AppConfig.BindingRedirectMissingNewVersion")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("AppConfig.BindingRedirectMissingNewVersion"))); // Cleanup. File.Delete(appConfigFile); @@ -565,13 +530,11 @@ public void GarbageAppConfigAssemblyNameMissingPKTAndCulture() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -611,13 +574,11 @@ public void AppConfigSpecifiedWhenAutoUnifyEqualsTrue() }; // Construct the app.config. - string appConfigFile = WriteAppConfig - ( + string appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); diff --git a/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAutoUnify.cs b/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAutoUnify.cs index dc4c11e5ef6..a283f172b13 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAutoUnify.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/StronglyNamedDependencyAutoUnify.cs @@ -1,3 +1,6 @@ +// 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.IO; using Microsoft.Build.Framework; @@ -22,9 +25,9 @@ public StronglyNamedDependencyAutoUnify(ITestOutputHelper output) : base(output) /// Return the default search paths. /// /// - new internal string[] DefaultPaths + internal new string[] DefaultPaths { - get { return new string[] { s_myApp_V05Path, s_myApp_V10Path, s_myApp_V20Path, s_myApp_V30Path, s_myComponentsV05Path, s_myComponentsV10Path, s_myComponentsV20Path, s_myComponentsV30Path }; } + get { return new string[] { s_myApp_V05Path, s_myApp_V10Path, s_myApp_V20Path, s_myApp_V30Path, s_myComponentsV05Path, s_myComponentsV10Path, s_myComponentsV20Path, s_myComponentsV30Path }; } } @@ -81,15 +84,11 @@ internal void ExistsImpl(RARSimulationMode rarSimulationMode = RARSimulationMode t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V20Path, StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); } } @@ -155,17 +154,13 @@ public void ExistsWithPrimaryReferenceOnBlackList() Assert.Contains(Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"), t.ResolvedFiles[0].ItemSpec); // "Expected the ItemSpec of the resolved file to be the item spec of the 1.0.0.0 assembly"); Assert.Single(t.ResolvedDependencyFiles); // "Expected there to be two resolved dependencies" t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V10Path, StringCompareShould.IgnoreCase); + t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V10Path, StringCompareShould.IgnoreCase); - engine.AssertLogDoesntContain - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL") - ); + engine.AssertLogDoesntContain( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, ProcessorArchitecture=MSIL")); - engine.AssertLogDoesntContain - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll")) - ); + engine.AssertLogDoesntContain( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); } finally { @@ -222,13 +217,11 @@ public void ExistsPromotedDependencyInTheBlackList() }; // Construct the app.config. - appConfigFile = WriteAppConfig - ( + appConfigFile = WriteAppConfig( " \n" + " \n" + " \n" + - " \n" - ); + " \n"); // Now, pass feed resolved primary references into ResolveAssemblyReference. ResolveAssemblyReference t = new ResolveAssemblyReference(); @@ -244,10 +237,8 @@ public void ExistsPromotedDependencyInTheBlackList() Assert.True(succeeded); Assert.Empty(t.ResolvedDependencyFiles); - engine.AssertLogDoesntContain - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogDoesntContain( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAppConfig"), "1.0.0.0", appConfigFile, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); } finally { @@ -318,8 +309,8 @@ public void ExistsWithBothDependentReferenceOnBlackList() Assert.True(succeeded); Assert.Empty(t.ResolvedFiles); // "Expected there to be no resolved files" - Assert.False(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to not be the item spec of the 1.0.0.0 assembly"); - Assert.False(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to not be the item spec of the 2.0.0.0 assembly" + Assert.False(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to not be the item spec of the 1.0.0.0 assembly"); + Assert.False(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to not be the item spec of the 2.0.0.0 assembly" string stringList = ResolveAssemblyReference.GenerateSubSetName(null, new ITaskItem[] { new TaskItem(subsetListPath) }); engine.AssertLogContains(t.Log.FormatResourceString("ResolveAssemblyReference.FailBecauseDependentAssemblyInExclusionList", assemblyNames[0].ItemSpec, "UniFYme, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", stringList)); @@ -392,25 +383,19 @@ public void MultipleUnifiedFromNamesMiddlePrimaryOnBlackList() Assert.True(succeeded); Assert.Equal(2, t.ResolvedFiles.Length); // "Expected to find two resolved assemblies" - Assert.True(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 1.0.0.0 assembly"); - Assert.True(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 2.0.0.0 assembly"); + Assert.True(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 1.0.0.0 assembly"); + Assert.True(ContainsItem(t.ResolvedFiles, Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); // "Expected the ItemSpec of the resolved file to be the item spec of the 2.0.0.0 assembly"); t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V20Path, StringCompareShould.IgnoreCase); + t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V20Path, StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); - engine.AssertLogDoesntContain - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "2.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll")) - ); + engine.AssertLogDoesntContain( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "2.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); } /// @@ -455,22 +440,16 @@ public void MultipleUnifiedFromNames() Assert.True(succeeded); t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V30Path, StringCompareShould.IgnoreCase); - - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") - ); - - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll")) - ); - - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "2.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll")) - ); + t.ResolvedDependencyFiles[0].ItemSpec.ShouldBe(s_unifyMeDll_V30Path, StringCompareShould.IgnoreCase); + + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnifiedDependency"), "UniFYme, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")); + + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "1.0.0.0", Path.Combine(s_myApp_V10Path, "DependsOnUnified.dll"))); + + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "2.0.0.0", Path.Combine(s_myApp_V20Path, "DependsOnUnified.dll"))); } /// @@ -513,10 +492,8 @@ public void LowVersionDoesntExist() Assert.True(succeeded); Assert.Single(t.ResolvedDependencyFiles); t.ResolvedDependencyFiles[0].GetMetadata("FusionName").ShouldBe("UnifyMe, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", StringCompareShould.IgnoreCase); - engine.AssertLogContains - ( - String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "0.5.0.0", Path.Combine(s_myApp_V05Path, "DependsOnUnified.dll")) - ); + engine.AssertLogContains( + String.Format(AssemblyResources.GetString("ResolveAssemblyReference.UnificationByAutoUnify"), "0.5.0.0", Path.Combine(s_myApp_V05Path, "DependsOnUnified.dll"))); } } } diff --git a/src/Tasks.UnitTests/AssemblyDependency/SuggestedRedirects.cs b/src/Tasks.UnitTests/AssemblyDependency/SuggestedRedirects.cs index 932411bcf01..9df8866c63a 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/SuggestedRedirects.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/SuggestedRedirects.cs @@ -1,3 +1,6 @@ +// 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.Collections.Generic; using System.IO; @@ -107,20 +110,15 @@ public void ConflictBetweenCopyLocalDependencies() Assert.True(ContainsItem(t.SuggestedRedirects, @"D, Culture=neutral, PublicKeyToken=aaaaaaaaaaaaaaaa")); // "Expected to find suggested redirect, but didn't" Assert.Equal(1, engine.Warnings); // "Should only be one warning for suggested redirects." Assert.Contains( - String.Format - ( - AssemblyResources.GetString - ( - "ResolveAssemblyReference.ConflictRedirectSuggestion" - ), + String.Format( + AssemblyResources.GetString( + "ResolveAssemblyReference.ConflictRedirectSuggestion"), "D, Culture=neutral, PublicKeyToken=aaaaaaaaaaaaaaaa", "1.0.0.0", s_myLibraries_V1_DDllPath, "2.0.0.0", - s_myLibraries_V2_DDllPath - ), - engine.Log - ); + s_myLibraries_V2_DDllPath), + engine.Log); } @@ -361,8 +359,8 @@ public void RedirectsAreSuggestedInExternallyResolvedGraph() t.Assemblies = new ITaskItem[] { - new TaskItem("A", new Dictionary { ["ExternallyResolved"] = "true" } ), - new TaskItem("B", new Dictionary { ["ExternallyResolved"] = "true" } ), + new TaskItem("A", new Dictionary { ["ExternallyResolved"] = "true" }), + new TaskItem("B", new Dictionary { ["ExternallyResolved"] = "true" }), }; t.SearchPaths = new string[] diff --git a/src/Tasks.UnitTests/AssemblyDependency/TaskTranslatorHelpers.cs b/src/Tasks.UnitTests/AssemblyDependency/TaskTranslatorHelpers.cs index dd423c774cb..bf6e3c2a05c 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/TaskTranslatorHelpers.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/TaskTranslatorHelpers.cs @@ -1,3 +1,6 @@ +// 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.Collections.Generic; using System.IO; @@ -13,7 +16,7 @@ namespace Microsoft.Build.UnitTests.ResolveAssemblyReference_Tests { public class TaskTranslatorHelpers { - MemoryStream _serializationStream; + private MemoryStream _serializationStream; [Fact] public void NullFrameworkName() @@ -51,7 +54,9 @@ public void ValidFrameworkName(FrameworkName value) private ITranslator GetReadTranslator() { if (_serializationStream == null) + { throw new InvalidOperationException("GetWriteTranslator has to be called before GetReadTranslator"); + } _serializationStream.Seek(0, SeekOrigin.Begin); return BinaryTranslator.GetReadTranslator(_serializationStream, null); diff --git a/src/Tasks.UnitTests/AssemblyDependency/VerifyIgnoreVersionForFrameworkReference.cs b/src/Tasks.UnitTests/AssemblyDependency/VerifyIgnoreVersionForFrameworkReference.cs index a71ac08e145..52277dbbd1f 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/VerifyIgnoreVersionForFrameworkReference.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/VerifyIgnoreVersionForFrameworkReference.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; diff --git a/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkAttribute.cs b/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkAttribute.cs index deea5b3f0fe..ba882c518f0 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkAttribute.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkAttribute.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Tasks; @@ -369,8 +372,7 @@ public void HigherVersionDirectDependenciesFalse() t.TargetFrameworkMonikerDisplayName = "Foo"; t.SearchPaths = new string[] { @"c:\Frameworks\" }; Assert.True( - t.Execute - ( + t.Execute( fileExists, directoryExists, getDirectories, @@ -387,9 +389,7 @@ public void HigherVersionDirectDependenciesFalse() #endif checkIfAssemblyIsInGac, isWinMDFile, - readMachineTypeFromPEHeader - ) - ); + readMachineTypeFromPEHeader)); Assert.Equal(0, e.Warnings); // "No warning expected in this scenario." diff --git a/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkHigherThanRedist.cs b/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkHigherThanRedist.cs index 4ff1910ebc4..99483aec16d 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkHigherThanRedist.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/VerifyTargetFrameworkHigherThanRedist.cs @@ -1,3 +1,6 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using System.Collections.Generic; using System.IO; using Microsoft.Build.Framework; diff --git a/src/Tasks.UnitTests/AssemblyDependency/WinMDTests.cs b/src/Tasks.UnitTests/AssemblyDependency/WinMDTests.cs index ab733088c21..84859e9d33f 100644 --- a/src/Tasks.UnitTests/AssemblyDependency/WinMDTests.cs +++ b/src/Tasks.UnitTests/AssemblyDependency/WinMDTests.cs @@ -1,3 +1,6 @@ +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks.UnitTests/AssemblyInfo.cs b/src/Tasks.UnitTests/AssemblyInfo.cs index 7f6f30fcef9..3b5d7bbb185 100644 --- a/src/Tasks.UnitTests/AssemblyInfo.cs +++ b/src/Tasks.UnitTests/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Tasks.UnitTests/AssemblyRefs.cs b/src/Tasks.UnitTests/AssemblyRefs.cs index a5c0c90df62..9f7d536594c 100644 --- a/src/Tasks.UnitTests/AssemblyRefs.cs +++ b/src/Tasks.UnitTests/AssemblyRefs.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + internal static class FXAssembly { internal const string Version = "4.0.0.0"; diff --git a/src/Tasks.UnitTests/AssemblyRegistrationCache_Tests.cs b/src/Tasks.UnitTests/AssemblyRegistrationCache_Tests.cs index 63991dcb033..8cf97318e7a 100644 --- a/src/Tasks.UnitTests/AssemblyRegistrationCache_Tests.cs +++ b/src/Tasks.UnitTests/AssemblyRegistrationCache_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Shouldly; @@ -9,7 +9,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class AssemblyRegistrationCache_Tests + public sealed class AssemblyRegistrationCache_Tests { [Fact] public void ExerciseCache() diff --git a/src/Tasks.UnitTests/AssignCulture_Tests.cs b/src/Tasks.UnitTests/AssignCulture_Tests.cs index 3ea88706f9c..e6ddc3e2dd3 100644 --- a/src/Tasks.UnitTests/AssignCulture_Tests.cs +++ b/src/Tasks.UnitTests/AssignCulture_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -11,7 +11,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class AssignCulture_Tests + public sealed class AssignCulture_Tests { /* * Method: Basic diff --git a/src/Tasks.UnitTests/AssignLinkMetadata_Tests.cs b/src/Tasks.UnitTests/AssignLinkMetadata_Tests.cs index 07fadfaaf21..899517b56d0 100644 --- a/src/Tasks.UnitTests/AssignLinkMetadata_Tests.cs +++ b/src/Tasks.UnitTests/AssignLinkMetadata_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -49,7 +49,7 @@ public void InvalidItemPath() AssignLinkMetadata t = new AssignLinkMetadata { BuildEngine = new MockEngine(), - Items = new ITaskItem[] {new TaskItem(item)} + Items = new ITaskItem[] { new TaskItem(item) } }; bool success = t.Execute(); @@ -69,7 +69,7 @@ public void Basic() AssignLinkMetadata t = new AssignLinkMetadata { BuildEngine = new MockEngine(), - Items = new ITaskItem[] {new TaskItem(item)} + Items = new ITaskItem[] { new TaskItem(item) } }; bool success = t.Execute(); @@ -97,7 +97,7 @@ public void InvalidItemPathWithOtherValidItem() AssignLinkMetadata t = new AssignLinkMetadata { BuildEngine = new MockEngine(), - Items = new ITaskItem[] {new TaskItem(item1), new TaskItem(item2)} + Items = new ITaskItem[] { new TaskItem(item1), new TaskItem(item2) } }; bool success = t.Execute(); @@ -121,7 +121,7 @@ public void DontOverrideLink() AssignLinkMetadata t = new AssignLinkMetadata { BuildEngine = new MockEngine(), - Items = new ITaskItem[] {new TaskItem(item)} + Items = new ITaskItem[] { new TaskItem(item) } }; bool success = t.Execute(); @@ -143,7 +143,7 @@ public void OutsideDefiningProjectCone() AssignLinkMetadata t = new AssignLinkMetadata { BuildEngine = new MockEngine(), - Items = new ITaskItem[] {new TaskItem(item)} + Items = new ITaskItem[] { new TaskItem(item) } }; bool success = t.Execute(); @@ -163,7 +163,7 @@ public void NoDefiningProjectMetadata() AssignLinkMetadata t = new AssignLinkMetadata { BuildEngine = new MockEngine(), - Items = new ITaskItem[] {item} + Items = new ITaskItem[] { item } }; bool success = t.Execute(); diff --git a/src/Tasks.UnitTests/AssignProjectConfiguration_Tests.cs b/src/Tasks.UnitTests/AssignProjectConfiguration_Tests.cs index a9535bfac91..048fa815c50 100644 --- a/src/Tasks.UnitTests/AssignProjectConfiguration_Tests.cs +++ b/src/Tasks.UnitTests/AssignProjectConfiguration_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -20,7 +20,7 @@ namespace Microsoft.Build.UnitTests /// in ResolveNonMSBuildProjectOutput_Tests. /// Here, only test the AssignProjectConfiguration specific code /// - sealed public class AssignProjectConfiguration_Tests + public sealed class AssignProjectConfiguration_Tests { private readonly ITestOutputHelper _output; diff --git a/src/Tasks.UnitTests/AssignTargetPath_Tests.cs b/src/Tasks.UnitTests/AssignTargetPath_Tests.cs index 3638a86206f..2289f896eaf 100644 --- a/src/Tasks.UnitTests/AssignTargetPath_Tests.cs +++ b/src/Tasks.UnitTests/AssignTargetPath_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Framework; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class AssignTargetPath_Tests + public sealed class AssignTargetPath_Tests { [Fact] public void Regress314791() diff --git a/src/Tasks.UnitTests/AxImp_Tests.cs b/src/Tasks.UnitTests/AxImp_Tests.cs index 331347bcec0..77a7674dd7d 100644 --- a/src/Tasks.UnitTests/AxImp_Tests.cs +++ b/src/Tasks.UnitTests/AxImp_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Microsoft.Build.Tasks; @@ -10,7 +10,7 @@ namespace Microsoft.Build.UnitTests.AxTlbImp_Tests { - sealed public class AxImp_Tests + public sealed class AxImp_Tests { /// /// Tests that the assembly being imported is passed to the command line diff --git a/src/Tasks.UnitTests/AxTlbBaseTask_Tests.cs b/src/Tasks.UnitTests/AxTlbBaseTask_Tests.cs index 56c1a5e53b5..9d33db3278f 100644 --- a/src/Tasks.UnitTests/AxTlbBaseTask_Tests.cs +++ b/src/Tasks.UnitTests/AxTlbBaseTask_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests.AxTlbImp_Tests { - sealed public class AxTlbBaseTask_Tests + public sealed class AxTlbBaseTask_Tests { /// /// Tests the /delaysign switch @@ -320,7 +320,7 @@ public void TaskFailsWhenImproperlySigned() } } - sealed internal class Utilities + internal sealed class Utilities { /// /// Given an instance of an AxImp task, executes that task (assuming all necessary parameters diff --git a/src/Tasks.UnitTests/CSharpParserUtilitites_Tests.cs b/src/Tasks.UnitTests/CSharpParserUtilitites_Tests.cs index fd6a6f4a794..abcd1bfa727 100644 --- a/src/Tasks.UnitTests/CSharpParserUtilitites_Tests.cs +++ b/src/Tasks.UnitTests/CSharpParserUtilitites_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Xunit; @@ -8,7 +8,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CSharpParserUtilititesTests + public sealed class CSharpParserUtilititesTests { // Try just and empty file [Fact] @@ -372,8 +372,7 @@ public void Preprocessor(string fileContents) [Fact(Skip = "Preprocessor is not yet implemented.")] public void PreprocessorNamespaceInFalsePreprocessorBlock() { - AssertParse - ( + AssertParse( @" #if (false) namespace i @@ -413,10 +412,8 @@ public void Regress_Mutation_SingleLineCommentsShouldBeIgnored(string fileConten */ private static void AssertParse(string source, string expectedClassName) { - ExtractedClassName className = CSharpParserUtilities.GetFirstClassNameFullyQualified - ( - StreamHelpers.StringToStream(source) - ); + ExtractedClassName className = CSharpParserUtilities.GetFirstClassNameFullyQualified( + StreamHelpers.StringToStream(source)); Assert.Equal(expectedClassName, className.Name); } diff --git a/src/Tasks.UnitTests/CSharpTokenizer_Tests.cs b/src/Tasks.UnitTests/CSharpTokenizer_Tests.cs index 26897d3ef06..f9613d173c6 100644 --- a/src/Tasks.UnitTests/CSharpTokenizer_Tests.cs +++ b/src/Tasks.UnitTests/CSharpTokenizer_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -11,7 +11,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CSharpTokenizerTests + public sealed class CSharpTokenizerTests { // Simple whitespace handling. [Fact] @@ -105,8 +105,8 @@ Form feed character (U+000C) [Fact] public void NamespacePlusClass() { - AssertTokenize - ("namespace MyNamespace { class MyClass {} }\x0d", + AssertTokenize( + "namespace MyNamespace { class MyClass {} }\x0d", ".Keyword.Whitespace.Identifier.Whitespace.OpenScope.Whitespace.Keyword.Whitespace.Identifier.Whitespace.OpenScope.CloseScope.Whitespace.CloseScope.Whitespace"); } @@ -114,12 +114,10 @@ public void NamespacePlusClass() [Fact] public void EscapedKeywordMakesIdentifier() { - AssertTokenize - ( + AssertTokenize( "namespace @namespace { class @class {} }\x0d", "namespace namespace { class class {} }\x0d", // Resulting tokens have '@' stripped. - ".Keyword.Whitespace.Identifier.Whitespace.OpenScope.Whitespace.Keyword.Whitespace.Identifier.Whitespace.OpenScope.CloseScope.Whitespace.CloseScope.Whitespace" - ); + ".Keyword.Whitespace.Identifier.Whitespace.OpenScope.Whitespace.Keyword.Whitespace.Identifier.Whitespace.OpenScope.CloseScope.Whitespace.CloseScope.Whitespace"); } // Check boolean literals @@ -248,7 +246,7 @@ public void EscapedKeywordMakesIdentifier() * Also, the source must be regenerated exactly when the tokens are concatenated * back together, */ - static private void AssertTokenize(string source, string expectedTokenKey) + private static void AssertTokenize(string source, string expectedTokenKey) { // Most of the time, we expect the rebuilt source to be the same as the input source. AssertTokenize(source, source, expectedTokenKey); @@ -261,7 +259,7 @@ static private void AssertTokenize(string source, string expectedTokenKey) * Also, the source must be regenerated exactly when the tokens are concatenated * back together, */ - static private void AssertTokenizeUnicode(string source, string expectedTokenKey) + private static void AssertTokenizeUnicode(string source, string expectedTokenKey) { // Most of the time, we expect the rebuilt source to be the same as the input source. AssertTokenizeUnicode(source, source, expectedTokenKey); @@ -274,12 +272,10 @@ static private void AssertTokenizeUnicode(string source, string expectedTokenKey * Also, the source must be regenerated exactly when the tokens are concatenated * back together, */ - static private void AssertTokenize - ( + private static void AssertTokenize( string source, string expectedTokenKey, - int expectedLastLineNumber - ) + int expectedLastLineNumber) { // Most of the time, we expect the rebuilt source to be the same as the input source. AssertTokenize(source, source, expectedTokenKey, expectedLastLineNumber); @@ -292,12 +288,10 @@ int expectedLastLineNumber * Also, the source must be regenerated exactly when the tokens are concatenated * back together, */ - static private void AssertTokenizeUnicode - ( + private static void AssertTokenizeUnicode( string source, string expectedTokenKey, - int expectedLastLineNumber - ) + int expectedLastLineNumber) { // Most of the time, we expect the rebuilt source to be the same as the input source. AssertTokenizeUnicode(source, source, expectedTokenKey, expectedLastLineNumber); @@ -310,12 +304,10 @@ int expectedLastLineNumber * Also compare the source that is regenerated by concatenating all of the tokens * to 'expectedSource'. */ - static private void AssertTokenize - ( + private static void AssertTokenize( string source, string expectedSource, - string expectedTokenKey - ) + string expectedTokenKey) { // Two lines is the most common test case. AssertTokenize(source, expectedSource, expectedTokenKey, 1); @@ -328,12 +320,10 @@ string expectedTokenKey * Also compare the source that is regenerated by concatenating all of the tokens * to 'expectedSource'. */ - static private void AssertTokenizeUnicode - ( + private static void AssertTokenizeUnicode( string source, string expectedSource, - string expectedTokenKey - ) + string expectedTokenKey) { // Two lines is the most common test case. AssertTokenizeUnicode(source, expectedSource, expectedTokenKey, 1); @@ -346,21 +336,17 @@ string expectedTokenKey * Also compare the source that is regenerated by concatenating all of the tokens * to 'expectedSource'. */ - static private void AssertTokenizeUnicode - ( + private static void AssertTokenizeUnicode( string source, string expectedSource, string expectedTokenKey, - int expectedLastLineNumber - ) + int expectedLastLineNumber) { - AssertTokenizeStream - ( + AssertTokenizeStream( StreamHelpers.StringToStream(source, System.Text.Encoding.Unicode), expectedSource, expectedTokenKey, - expectedLastLineNumber - ); + expectedLastLineNumber); } /* @@ -370,13 +356,11 @@ int expectedLastLineNumber * Also compare the source that is regenerated by concatenating all of the tokens * to 'expectedSource'. */ - static private void AssertTokenize - ( + private static void AssertTokenize( string source, string expectedSource, string expectedTokenKey, - int expectedLastLineNumber - ) + int expectedLastLineNumber) { // This version of AssertTokenize tests several different encodings. // The reason is that we want to be sure each of these works in the @@ -396,19 +380,15 @@ int expectedLastLineNumber * Also compare the source that is regenerated by concatenating all of the tokens * to 'expectedSource'. */ - static private void AssertTokenizeStream - ( + private static void AssertTokenizeStream( Stream source, string expectedSource, string expectedTokenKey, - int expectedLastLineNumber - ) + int expectedLastLineNumber) { - CSharpTokenizer tokens = new CSharpTokenizer - ( + CSharpTokenizer tokens = new CSharpTokenizer( source, - false - ); + false); string results = ""; string tokenKey = ""; int lastLine = 0; diff --git a/src/Tasks.UnitTests/CallTarget_Tests.cs b/src/Tasks.UnitTests/CallTarget_Tests.cs index 289347e1b69..61348a8a483 100644 --- a/src/Tasks.UnitTests/CallTarget_Tests.cs +++ b/src/Tasks.UnitTests/CallTarget_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -14,7 +14,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CallTarget_Tests : IDisposable + public sealed class CallTarget_Tests : IDisposable { public CallTarget_Tests() { @@ -122,7 +122,7 @@ public void FailsWithOnlyTargetErrors() "); - logger.ErrorCount.ShouldBe (1); + logger.ErrorCount.ShouldBe(1); } /// diff --git a/src/Tasks.UnitTests/CodeTaskFactoryTests.cs b/src/Tasks.UnitTests/CodeTaskFactoryTests.cs index 4a7d4708b26..538e51342f3 100644 --- a/src/Tasks.UnitTests/CodeTaskFactoryTests.cs +++ b/src/Tasks.UnitTests/CodeTaskFactoryTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System; diff --git a/src/Tasks.UnitTests/ComReferenceWalker_Tests.cs b/src/Tasks.UnitTests/ComReferenceWalker_Tests.cs index fa7909f7c4b..54f66e923a1 100644 --- a/src/Tasks.UnitTests/ComReferenceWalker_Tests.cs +++ b/src/Tasks.UnitTests/ComReferenceWalker_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -14,7 +14,7 @@ namespace Microsoft.Build.UnitTests { public class ComReferenceWalker_Tests { - static private int MockReleaseComObject(object o) + private static int MockReleaseComObject(object o) { return 0; } diff --git a/src/Tasks.UnitTests/ComReference_Tests.cs b/src/Tasks.UnitTests/ComReference_Tests.cs index 855313c7070..09a21f0bb38 100644 --- a/src/Tasks.UnitTests/ComReference_Tests.cs +++ b/src/Tasks.UnitTests/ComReference_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -11,7 +11,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class ComReference_Tests + public sealed class ComReference_Tests { private static Dictionary s_existingFiles = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -20,7 +20,9 @@ private static Dictionary ExistingFilesDictionary get { if (s_existingFiles.Count != 0) + { return s_existingFiles; + } s_existingFiles.Add(@"C:\test\typelib1.dll", string.Empty); s_existingFiles.Add(@"C:\test\typelib2\2.dll", string.Empty); diff --git a/src/Tasks.UnitTests/CombinePath_Tests.cs b/src/Tasks.UnitTests/CombinePath_Tests.cs index def89f55a3a..cee148bb2c5 100644 --- a/src/Tasks.UnitTests/CombinePath_Tests.cs +++ b/src/Tasks.UnitTests/CombinePath_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CombinePath_Tests + public sealed class CombinePath_Tests { /// /// Base path is relative. Paths are relative. diff --git a/src/Tasks.UnitTests/CommandLineBuilderExtension_Tests.cs b/src/Tasks.UnitTests/CommandLineBuilderExtension_Tests.cs index 2652a9d8deb..97b019804eb 100644 --- a/src/Tasks.UnitTests/CommandLineBuilderExtension_Tests.cs +++ b/src/Tasks.UnitTests/CommandLineBuilderExtension_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CommandLineBuilderExtensionTest + public sealed class CommandLineBuilderExtensionTest { /* * Method: AppendItemWithInvalidBooleanAttribute @@ -38,13 +38,11 @@ public void AppendItemWithInvalidBooleanAttribute() // Validate that a legitimate bool works first. try { - c.AppendSwitchIfNotNull - ( + c.AppendSwitchIfNotNull( "/myswitch:", new ITaskItem[] { i }, new string[] { "Name", "Private" }, - new bool[] { false, true } - ); + new bool[] { false, true }); Assert.Equal(@"/myswitch:MyResource.bmp,Kenny,Private", c.ToString()); } catch (ArgumentException e) @@ -54,15 +52,12 @@ public void AppendItemWithInvalidBooleanAttribute() // Now try a bogus boolean. i.SetMetadata("Private", "Maybe"); // This is our flag. - c.AppendSwitchIfNotNull - ( + c.AppendSwitchIfNotNull( "/myswitch:", new ITaskItem[] { i }, new string[] { "Name", "Private" }, - new bool[] { false, true } - ); // <-- Expect an ArgumentException here. - } - ); + new bool[] { false, true }); // <-- Expect an ArgumentException here. + }); } /// /// When appending an ITaskItem[] where some of the optional attributes are @@ -87,13 +82,11 @@ public void AppendItemWithMissingAttribute() CommandLineBuilderExtension c = new CommandLineBuilderExtension(); - c.AppendSwitchIfNotNull - ( + c.AppendSwitchIfNotNull( "/myswitch:", new ITaskItem[] { i, j }, new string[] { "Name", "HintPath", "Access" }, - null - ); + null); Assert.Equal( @"/myswitch:MySoundEffect.wav,Kenny " diff --git a/src/Tasks.UnitTests/CommandLineGenerator_Tests.cs b/src/Tasks.UnitTests/CommandLineGenerator_Tests.cs index 9a99b37b197..3e7b7c32d9d 100644 --- a/src/Tasks.UnitTests/CommandLineGenerator_Tests.cs +++ b/src/Tasks.UnitTests/CommandLineGenerator_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CommandLineGenerator_Tests + public sealed class CommandLineGenerator_Tests { private const string testXamlFile = @" diff --git a/src/Tasks.UnitTests/CommandLine_Support.cs b/src/Tasks.UnitTests/CommandLine_Support.cs index 57d7bc48213..0c33111ede9 100644 --- a/src/Tasks.UnitTests/CommandLine_Support.cs +++ b/src/Tasks.UnitTests/CommandLine_Support.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -18,14 +18,14 @@ namespace Microsoft.Build.UnitTests * Test the Csc task in various ways. * */ - sealed internal class CommandLine + internal sealed class CommandLine { /// /// Invokes the ValidateParameters on the given ToolTask instance. We need to use reflection since /// ValidateParameters is inaccessible to Tasks unit tests. /// /// - static internal bool CallValidateParameters(ToolTask task) + internal static bool CallValidateParameters(ToolTask task) { MethodInfo validateMethod = typeof(ToolTask).GetMethod("ValidateParameters", BindingFlags.Instance | BindingFlags.NonPublic); return (bool)validateMethod.Invoke(task, null); @@ -68,9 +68,13 @@ internal static int ValidateHasParameter(ToolTaskExtension t, string parameter, CommandLineBuilderExtension b = new CommandLineBuilderExtension(); if (useResponseFile) + { t.AddResponseFileCommands(b); + } else + { t.AddCommandLineCommands(b); + } string cl = b.ToString(); string msg = String.Format("Command-line = [{0}]\r\n", cl); @@ -144,15 +148,18 @@ internal static void ValidateNoParameterStartsWith( ToolTaskExtension t, string startsWith, string except, - bool useResponseFile - ) + bool useResponseFile) { CommandLineBuilderExtension b = new CommandLineBuilderExtension(); if (useResponseFile) + { t.AddResponseFileCommands(b); + } else + { t.AddCommandLineCommands(b); + } string cl = b.ToString(); @@ -197,9 +204,13 @@ internal static void ValidateContains(ToolTaskExtension t, string lookFor, bool CommandLineBuilderExtension b = new CommandLineBuilderExtension(); if (useResponseFile) + { t.AddResponseFileCommands(b); + } else + { t.AddCommandLineCommands(b); + } string cl = b.ToString(); string msg = String.Format("Command-line = [{0}]\r\n", cl); @@ -226,9 +237,13 @@ internal static void ValidateDoesNotContain(ToolTaskExtension t, string lookFor, CommandLineBuilderExtension b = new CommandLineBuilderExtension(); if (useResponseFile) + { t.AddResponseFileCommands(b); + } else + { t.AddCommandLineCommands(b); + } string cl = b.ToString(); string msg = String.Format("Command-line = [{0}]\r\n", cl); @@ -253,9 +268,13 @@ internal static void ValidateEquals(ToolTaskExtension t, string lookFor, bool us CommandLineBuilderExtension b = new CommandLineBuilderExtension(); if (useResponseFile) + { t.AddResponseFileCommands(b); + } else + { t.AddCommandLineCommands(b); + } string cl = b.ToString(); string msg = String.Format("Command-line = [{0}]\r\n", cl); @@ -274,9 +293,13 @@ internal static string GetCommandLine(ToolTaskExtension t, bool useResponseFile) CommandLineBuilderExtension b = new CommandLineBuilderExtension(); if (useResponseFile) + { t.AddResponseFileCommands(b); + } else + { t.AddCommandLineCommands(b); + } return b.ToString(); } diff --git a/src/Tasks.UnitTests/ConvertToAbsolutePath_Tests.cs b/src/Tasks.UnitTests/ConvertToAbsolutePath_Tests.cs index e7f8b0ecf8f..73c43d16a92 100644 --- a/src/Tasks.UnitTests/ConvertToAbsolutePath_Tests.cs +++ b/src/Tasks.UnitTests/ConvertToAbsolutePath_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -12,7 +12,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class ConvertToAbsolutePath_Tests + public sealed class ConvertToAbsolutePath_Tests { /// /// Passing in a relative path (expecting an absolute back) diff --git a/src/Tasks.UnitTests/Copy_Tests.cs b/src/Tasks.UnitTests/Copy_Tests.cs index 4477c7e5432..49a635d1385 100644 --- a/src/Tasks.UnitTests/Copy_Tests.cs +++ b/src/Tasks.UnitTests/Copy_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -510,7 +510,9 @@ public void DoCopyOverDifferentFile() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destinationFile)) // HIGHCHAR: Test reads ASCII (not ANSI). + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file." @@ -575,8 +577,7 @@ public void DoCopyOverCopiedFile(bool skipUnchangedFiles) sourceFile, destinationFile, "SkipUnchangedFiles", - "true" - ); + "true"); } else { @@ -585,8 +586,7 @@ public void DoCopyOverCopiedFile(bool skipUnchangedFiles) sourceFile, destinationFile, "SkipUnchangedFiles", - "true" - ); + "true"); } // "Expected the destination file to contain the contents of source file." @@ -967,7 +967,9 @@ public void DoNotRetryCopyWhenDestinationFileIsFolder() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) // HIGHCHAR: Test writes in UTF8 without preamble. + { sw.Write("This is a destination temp file."); + } ITaskItem[] sourceFiles = { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = { new TaskItem(destinationFile) }; @@ -1329,7 +1331,9 @@ public void CopyToDestinationFolder() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destFile)) + { destinationFileContents = sr.ReadToEnd(); + } if (!UseHardLinks) { diff --git a/src/Tasks.UnitTests/CreateCSharpManifestResourceName_Tests.cs b/src/Tasks.UnitTests/CreateCSharpManifestResourceName_Tests.cs index d55cbe2087d..25daf87a34e 100644 --- a/src/Tasks.UnitTests/CreateCSharpManifestResourceName_Tests.cs +++ b/src/Tasks.UnitTests/CreateCSharpManifestResourceName_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -16,7 +16,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CreateCSharpManifestResourceName_Tests + public sealed class CreateCSharpManifestResourceName_Tests { private readonly ITestOutputHelper _testOutput; @@ -31,8 +31,7 @@ public CreateCSharpManifestResourceName_Tests(ITestOutputHelper output) public void Basic() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -40,8 +39,7 @@ public void Basic() dependentUponFileName: null, culture: null, binaryStream: StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"), - log: null - ); + log: null); Assert.Equal("MyStuff.Namespace.Class", result); } @@ -54,7 +52,7 @@ public void Basic() /// for different codepages. /// #if RUNTIME_TYPE_NETCORE - [Fact (Skip = "https://github.com/dotnet/msbuild/issues/295")] + [Fact(Skip = "https://github.com/dotnet/msbuild/issues/295")] #else [Fact] #endif @@ -71,8 +69,7 @@ public void Regress172107() sourcesStream.Seek(0, SeekOrigin.Begin); string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"irrelevant", linkFileName: null, prependCultureAsDirectory: true, @@ -80,8 +77,7 @@ public void Regress172107() dependentUponFileName: null, culture: null, binaryStream: sourcesStream, - log: null - ); + log: null); MemoryStream m = new MemoryStream(); m.Write(new byte[] { 0x64, 0xc3, 0x61, 0x2e, 0x43, 0x6c, 0x61, 0x73, 0x73 }, 0, 9); // dÃa.Class in ANSI @@ -102,7 +98,7 @@ public void Regress172107() /// /// #if RUNTIME_TYPE_NETCORE - [Fact (Skip = "https://github.com/dotnet/msbuild/issues/295")] + [Fact(Skip = "https://github.com/dotnet/msbuild/issues/295")] #else [Fact] #endif @@ -119,8 +115,7 @@ public void Regress249540() sourcesStream.Seek(0, SeekOrigin.Begin); string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"irrelevant", linkFileName: null, prependCultureAsDirectory: true, @@ -128,8 +123,7 @@ public void Regress249540() dependentUponFileName: null, culture: null, binaryStream: sourcesStream, - log: null - ); + log: null); Assert.Equal("d\u00C4a.Class", result); } @@ -141,8 +135,7 @@ public void Regress249540() public void RelativeDependentUpon() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -150,8 +143,7 @@ public void RelativeDependentUpon() dependentUponFileName: null, culture: null, binaryStream: StreamHelpers.StringToStream("namespace Namespace { class Class {} }"), - log: null - ); + log: null); Assert.Equal("Namespace.Class", result); } @@ -163,8 +155,7 @@ public void RelativeDependentUpon() public void AbsoluteDependentUpon() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -172,8 +163,7 @@ public void AbsoluteDependentUpon() dependentUponFileName: null, culture: null, binaryStream: StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"), - log: null - ); + log: null); Assert.Equal("MyStuff.Namespace.Class", result); } @@ -185,8 +175,7 @@ public void AbsoluteDependentUpon() public void DependentWithCulture() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.en-GB.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -194,8 +183,7 @@ public void DependentWithCulture() dependentUponFileName: null, culture: null, binaryStream: StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"), - log: null - ); + log: null); Assert.Equal("MyStuff.Namespace.Class.en-GB", result); } @@ -208,8 +196,7 @@ public void DependentWithCulture() public void DependentWithCultureMetadata() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -217,8 +204,7 @@ public void DependentWithCultureMetadata() dependentUponFileName: null, culture: "en-GB", binaryStream: StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"), - log: null - ); + log: null); Assert.Equal("MyStuff.Namespace.Class.en-GB", result); } @@ -230,8 +216,7 @@ public void DependentWithCultureMetadata() public void DependentWithEmbeddedCulture() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.fr-fr.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -239,8 +224,7 @@ public void DependentWithEmbeddedCulture() dependentUponFileName: null, culture: null, binaryStream: StreamHelpers.StringToStream("namespace MyStuff.Namespace { class Class {} }"), - log: null - ); + log: null); Assert.Equal("MyStuff.Namespace.Class.fr-fr", result); } @@ -253,8 +237,7 @@ public void DependentWithEmbeddedCulture() public void RootnamespaceWithCulture() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"SubFolder\MyForm.en-GB.ResX", linkFileName: null, prependCultureAsDirectory: true, @@ -262,8 +245,7 @@ public void RootnamespaceWithCulture() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal("RootNamespace.SubFolder.MyForm.en-GB", result); } @@ -275,8 +257,7 @@ public void RootnamespaceWithCulture() public void RootnamespaceWithCulture_RetainCultureInFileName() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"Subfolder\File.cs.cshtml", linkFileName: null, prependCultureAsDirectory: true, @@ -285,8 +266,7 @@ public void RootnamespaceWithCulture_RetainCultureInFileName() culture: null, binaryStream: null, log: null, - treatAsCultureNeutral: true // retain culture in name - ); + treatAsCultureNeutral: true); // retain culture in name result.ShouldBe("RootNamespace.Subfolder.File.cs.cshtml"); } @@ -298,8 +278,7 @@ public void RootnamespaceWithCulture_RetainCultureInFileName() public void Regress222308() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"..\..\XmlEditor\Setup\XmlEditor.rgs", linkFileName: @"XmlEditor.rgs", prependCultureAsDirectory: true, @@ -307,8 +286,7 @@ public void Regress222308() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal("RootNamespace.XmlEditor.rgs", result); } @@ -320,8 +298,7 @@ public void Regress222308() public void BitmapWithRootNamespace() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"SubFolder\SplashScreen.bmp", linkFileName: null, prependCultureAsDirectory: true, @@ -329,8 +306,7 @@ public void BitmapWithRootNamespace() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal("RootNamespace.SubFolder.SplashScreen.bmp", result); } @@ -342,8 +318,7 @@ public void BitmapWithRootNamespace() public void CulturedBitmapWithRootNamespace() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"SubFolder\SplashScreen.fr.bmp", linkFileName: null, prependCultureAsDirectory: true, @@ -351,8 +326,7 @@ public void CulturedBitmapWithRootNamespace() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(FileUtilities.FixFilePath(@"fr\RootNamespace.SubFolder.SplashScreen.bmp"), result); } @@ -364,8 +338,7 @@ public void CulturedBitmapWithRootNamespace() public void CulturedBitmapWithRootNamespaceNoDirectoryPrefix() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"SubFolder\SplashScreen.fr.bmp", linkFileName: null, // Link file name prependCultureAsDirectory: false, @@ -373,8 +346,7 @@ public void CulturedBitmapWithRootNamespaceNoDirectoryPrefix() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(@"RootNamespace.SubFolder.SplashScreen.bmp", result); } @@ -394,10 +366,8 @@ public void Regress188319() i.SetMetadata("DependentUpon", "SR1.strings"); // Normally, this would be a C# file. t.ResourceFiles = new ITaskItem[] { i }; t.RootNamespace = "CustomToolTest"; - bool success = t.Execute - ( - new Microsoft.Build.Tasks.CreateFileStream(CreateFileStream) - ); + bool success = t.Execute( + new Microsoft.Build.Tasks.CreateFileStream(CreateFileStream)); Assert.True(success); // "Expected the task to succeed." @@ -718,8 +688,7 @@ public void Regress311473() public void Regress419591() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: "MyForm.en-GB.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -727,8 +696,7 @@ public void Regress419591() dependentUponFileName: "MyForm.en-GB.cs", culture: null, binaryStream: StreamHelpers.StringToStream("namespace ClassLibrary1 { class MyForm {} }"), - log: null - ); + log: null); Assert.Equal("ClassLibrary1.MyForm", result); } @@ -747,8 +715,7 @@ public void Regress419591() public void Regress419591_EmptySource() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: "MyForm.en-GB.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -756,8 +723,7 @@ public void Regress419591_EmptySource() dependentUponFileName: "MyForm.en-GB.cs", culture: null, binaryStream: StreamHelpers.StringToStream(""), - log: null - ); + log: null); Assert.Equal("RootNamespace.MyForm.en-GB", result); } @@ -774,8 +740,7 @@ public void Regress459265() CreateCSharpManifestResourceName c = new CreateCSharpManifestResourceName(); c.BuildEngine = m; - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: "MyForm.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -796,15 +761,12 @@ namespace ClassLibrary3 class MyForm { } -}" - ), - log: c.Log - ); +}"), + log: c.Log); Assert.Contains( String.Format(AssemblyResources.GetString("CreateManifestResourceName.DefinitionFoundWithinConditionalDirective"), "MyForm.cs", "MyForm.resx"), - m.Log - ); + m.Log); } /// @@ -933,8 +895,7 @@ public void NoLogicalNameAddedForResx() public void CulturedResourcesFileWithRootNamespaceWithinSubfolder() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"SubFolder\MyResource.fr.resources", linkFileName: null, // Link file name prependCultureAsDirectory: false, @@ -942,8 +903,7 @@ public void CulturedResourcesFileWithRootNamespaceWithinSubfolder() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(@"RootNamespace.SubFolder.MyResource.fr.resources", result); } @@ -955,8 +915,7 @@ public void CulturedResourcesFileWithRootNamespaceWithinSubfolder() public void CulturedResourcesFileWithRootNamespace() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"MyResource.fr.resources", linkFileName: null, // Link file name prependCultureAsDirectory: false, @@ -964,8 +923,7 @@ public void CulturedResourcesFileWithRootNamespace() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(@"RootNamespace.MyResource.fr.resources", result); } @@ -977,8 +935,7 @@ public void CulturedResourcesFileWithRootNamespace() public void ResourcesFileWithRootNamespace() { string result = - CreateCSharpManifestResourceName.CreateManifestNameImpl - ( + CreateCSharpManifestResourceName.CreateManifestNameImpl( fileName: @"MyResource.resources", linkFileName: null, // Link file name prependCultureAsDirectory: false, @@ -986,8 +943,7 @@ public void ResourcesFileWithRootNamespace() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(@"RootNamespace.MyResource.resources", result); } diff --git a/src/Tasks.UnitTests/CreateItem_Tests.cs b/src/Tasks.UnitTests/CreateItem_Tests.cs index b82f1f4af7e..44ac891a76d 100644 --- a/src/Tasks.UnitTests/CreateItem_Tests.cs +++ b/src/Tasks.UnitTests/CreateItem_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Collections.Generic; @@ -18,7 +18,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CreateItem_Tests + public sealed class CreateItem_Tests { internal const string CreateItemWithInclude = @" diff --git a/src/Tasks.UnitTests/CreateProperty_Tests.cs b/src/Tasks.UnitTests/CreateProperty_Tests.cs index 0b05115ca4a..f20bc8c9f60 100644 --- a/src/Tasks.UnitTests/CreateProperty_Tests.cs +++ b/src/Tasks.UnitTests/CreateProperty_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System; @@ -9,7 +9,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CreateProperty_Tests : IDisposable + public sealed class CreateProperty_Tests : IDisposable { public CreateProperty_Tests() { diff --git a/src/Tasks.UnitTests/CreateVisualBasicManifestResourceName_Tests.cs b/src/Tasks.UnitTests/CreateVisualBasicManifestResourceName_Tests.cs index 4fffa6e0379..884509b1b86 100644 --- a/src/Tasks.UnitTests/CreateVisualBasicManifestResourceName_Tests.cs +++ b/src/Tasks.UnitTests/CreateVisualBasicManifestResourceName_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -16,7 +16,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class CreateVisualBasicManifestResourceName_Tests + public sealed class CreateVisualBasicManifestResourceName_Tests { private readonly ITestOutputHelper _testOutput; @@ -32,8 +32,7 @@ public CreateVisualBasicManifestResourceName_Tests(ITestOutputHelper output) public void Basic() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -47,8 +46,7 @@ Class TestClass End Class End Namespace "), - log: null - ); + log: null); Assert.Equal("Nested.TestNamespace.TestClass", result); } @@ -60,8 +58,7 @@ End Namespace public void RelativeDependentUpon() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -75,9 +72,7 @@ Class TestClass End Class End Namespace "), - log: null - - ); + log: null); Assert.Equal("TestNamespace.TestClass", result); } @@ -89,8 +84,7 @@ End Namespace public void AbsoluteDependentUpon() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -104,9 +98,7 @@ Class TestClass End Class End Namespace "), - log: null - - ); + log: null); Assert.Equal("Nested.TestNamespace.TestClass", result); } @@ -118,8 +110,7 @@ End Namespace public void DependentWithCulture() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.en-GB.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -133,9 +124,7 @@ Class TestClass End Class End Namespace "), - log: null - - ); + log: null); Assert.Equal("Nested.TestNamespace.TestClass.en-GB", result); } @@ -148,8 +137,7 @@ End Namespace public void DependentWithCultureMetadata() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -163,9 +151,7 @@ Class TestClass End Class End Namespace "), - log: null - - ); + log: null); Assert.Equal("Nested.TestNamespace.TestClass.en-GB", result); } @@ -177,8 +163,7 @@ End Namespace public void DependentWithCultureAndRootNamespace() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.en-GB.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -192,9 +177,7 @@ Class TestClass End Class End Namespace "), - log: null - - ); + log: null); Assert.Equal("RootNamespace.Nested.TestNamespace.TestClass.en-GB", result); } @@ -206,8 +189,7 @@ End Namespace public void DependentWithEmbeddedCulture() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"f:\myproject\SubFolder\MyForm.fr-fr.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -221,9 +203,7 @@ Class TestClass End Class End Namespace "), - log: null - - ); + log: null); Assert.Equal("RootNamespace.Nested.TestNamespace.TestClass.fr-fr", result); } @@ -259,8 +239,7 @@ public void RootnamespaceWithCulture() public void RootnamespaceWithCulture_RetainCultureInFileName() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"File.cs.vb", linkFileName: null, prependCultureAsDirectory: true, @@ -269,8 +248,7 @@ public void RootnamespaceWithCulture_RetainCultureInFileName() culture: null, binaryStream: null, log: null, - treatAsCultureNeutral: true // retain culture in name - ); + treatAsCultureNeutral: true); // retain culture in name // Visual basic does not carry subfolder. // See https://github.com/dotnet/msbuild/pull/5477 @@ -284,8 +262,7 @@ public void RootnamespaceWithCulture_RetainCultureInFileName() public void Regress222308() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"..\..\XmlEditor\Setup\XmlEditor.rgs", linkFileName: @"MyXmlEditor.rgs", prependCultureAsDirectory: true, @@ -293,9 +270,7 @@ public void Regress222308() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - - ); + log: null); Assert.Equal("RootNamespace.MyXmlEditor.rgs", result); } @@ -470,8 +445,7 @@ End Namespace public void Regress419591() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: "MyForm.ro.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -483,9 +457,7 @@ public void Regress419591() Class MyForm End Class "), - log: null - - ); + log: null); Assert.Equal("RootNamespace.MyForm", result); } @@ -503,8 +475,7 @@ public void Regress459265() c.BuildEngine = m; string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: "MyForm.resx", linkFileName: null, prependCultureAsDirectory: true, @@ -525,15 +496,12 @@ Namespace ClassLibrary3 Class MyForm End Class End Namespace -" - ), - log: c.Log - ); +"), + log: c.Log); Assert.Contains( String.Format(AssemblyResources.GetString("CreateManifestResourceName.DefinitionFoundWithinConditionalDirective"), "MyForm.vb", "MyForm.resx"), - m.Log - ); + m.Log); } /// @@ -665,8 +633,7 @@ public void CulturedResourcesFileWithRootNamespaceWithinSubfolder() public void CulturedResourcesFileWithRootNamespace() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"MyResource.fr.resources", linkFileName: null, // Link file name prependCultureAsDirectory: false, @@ -674,8 +641,7 @@ public void CulturedResourcesFileWithRootNamespace() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(@"RootNamespace.MyResource.fr.resources", result); } @@ -687,8 +653,7 @@ public void CulturedResourcesFileWithRootNamespace() public void ResourcesFileWithRootNamespace() { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: @"MyResource.resources", linkFileName: null, // Link file name prependCultureAsDirectory: false, @@ -696,8 +661,7 @@ public void ResourcesFileWithRootNamespace() dependentUponFileName: null, culture: null, binaryStream: null, - log: null - ); + log: null); Assert.Equal(@"RootNamespace.MyResource.resources", result); } @@ -705,8 +669,7 @@ public void ResourcesFileWithRootNamespace() private void AssertSimpleCase(string code, string expected) { string result = - CreateVisualBasicManifestResourceName.CreateManifestNameImpl - ( + CreateVisualBasicManifestResourceName.CreateManifestNameImpl( fileName: "MyForm.resx", linkFileName: null, // Link file name prependCultureAsDirectory: true, @@ -714,8 +677,7 @@ private void AssertSimpleCase(string code, string expected) dependentUponFileName: "MyForm.vb", culture: null, binaryStream: StreamHelpers.StringToStream(code), - log: null - ); + log: null); Assert.Equal(expected, result); } diff --git a/src/Tasks.UnitTests/Culture_Tests.cs b/src/Tasks.UnitTests/Culture_Tests.cs index 08383580b20..05c61b69af3 100644 --- a/src/Tasks.UnitTests/Culture_Tests.cs +++ b/src/Tasks.UnitTests/Culture_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Xunit; @@ -8,7 +8,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class Culture_Tests + public sealed class Culture_Tests { /* * Method: Basic diff --git a/src/Tasks.UnitTests/Delete_Tests.cs b/src/Tasks.UnitTests/Delete_Tests.cs index 14982f6d6b3..b752d309728 100644 --- a/src/Tasks.UnitTests/Delete_Tests.cs +++ b/src/Tasks.UnitTests/Delete_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using Microsoft.Build.Framework; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class Delete_Tests + public sealed class Delete_Tests { /* * Method: AttributeForwarding diff --git a/src/Tasks.UnitTests/DependentAssembly_Tests.cs b/src/Tasks.UnitTests/DependentAssembly_Tests.cs index 20eb679c3c1..c949a33d5dd 100644 --- a/src/Tasks.UnitTests/DependentAssembly_Tests.cs +++ b/src/Tasks.UnitTests/DependentAssembly_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; diff --git a/src/Tasks.UnitTests/DirectoryBuildProjectImportTestBase.cs b/src/Tasks.UnitTests/DirectoryBuildProjectImportTestBase.cs index e8f0784d223..ce9919c8aa5 100644 --- a/src/Tasks.UnitTests/DirectoryBuildProjectImportTestBase.cs +++ b/src/Tasks.UnitTests/DirectoryBuildProjectImportTestBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests /// /// A base class for testing the directory build project import functionality in Microsoft.Common.props and Microsoft.Common.targets. /// - abstract public class DirectoryBuildProjectImportTestBase : IDisposable + public abstract class DirectoryBuildProjectImportTestBase : IDisposable { private const string BasicDirectoryBuildProjectContents = @" diff --git a/src/Tasks.UnitTests/DirectoryBuildPropsImportTests.cs b/src/Tasks.UnitTests/DirectoryBuildPropsImportTests.cs index 762ce477248..8500db7000f 100644 --- a/src/Tasks.UnitTests/DirectoryBuildPropsImportTests.cs +++ b/src/Tasks.UnitTests/DirectoryBuildPropsImportTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -8,7 +8,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests that Microsoft.Common.props successfully imports a directory build project in the directory tree of the project being built. /// - sealed public class DirectoryBuildPropsImportTests : DirectoryBuildProjectImportTestBase + public sealed class DirectoryBuildPropsImportTests : DirectoryBuildProjectImportTestBase { protected override string CustomBuildProjectFile => "customBuild.props"; diff --git a/src/Tasks.UnitTests/DirectoryBuildTargetsImportTests.cs b/src/Tasks.UnitTests/DirectoryBuildTargetsImportTests.cs index 783538a0697..4538fed4a48 100644 --- a/src/Tasks.UnitTests/DirectoryBuildTargetsImportTests.cs +++ b/src/Tasks.UnitTests/DirectoryBuildTargetsImportTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable @@ -8,7 +8,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests that Microsoft.Common.targets successfully imports a directory build project in the directory tree of the project being built. /// - sealed public class DirectoryBuildTargetsImportTests : DirectoryBuildProjectImportTestBase + public sealed class DirectoryBuildTargetsImportTests : DirectoryBuildProjectImportTestBase { protected override string DirectoryBuildProjectFile => "Directory.Build.targets"; diff --git a/src/Tasks.UnitTests/DownloadFile_Tests.cs b/src/Tasks.UnitTests/DownloadFile_Tests.cs index 81a47c77412..6edc5512418 100644 --- a/src/Tasks.UnitTests/DownloadFile_Tests.cs +++ b/src/Tasks.UnitTests/DownloadFile_Tests.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.UnitTests; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; using Shouldly; using System; diff --git a/src/Tasks.UnitTests/ErrorWarningMessage_Tests.cs b/src/Tasks.UnitTests/ErrorWarningMessage_Tests.cs index f99a7e8bb4e..569192d3c57 100644 --- a/src/Tasks.UnitTests/ErrorWarningMessage_Tests.cs +++ b/src/Tasks.UnitTests/ErrorWarningMessage_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; @@ -10,7 +10,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class ErrorWarningMessage_Tests + public sealed class ErrorWarningMessage_Tests { /// /// Simple case @@ -164,7 +164,7 @@ public void EmptyError() // don't set text }; - + bool retval = err.Execute(); diff --git a/src/Tasks.UnitTests/Exec_Tests.cs b/src/Tasks.UnitTests/Exec_Tests.cs index c882200d44e..5c78ff468a7 100644 --- a/src/Tasks.UnitTests/Exec_Tests.cs +++ b/src/Tasks.UnitTests/Exec_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -23,7 +23,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests for the Exec task /// - sealed public class Exec_Tests + public sealed class Exec_Tests { private readonly ITestOutputHelper _output; @@ -316,7 +316,10 @@ public void TempPathContainsAmpersand1() finally { Environment.SetEnvironmentVariable("TMP", oldTmp); - if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + if (Directory.Exists(newTmp)) + { + FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + } } } @@ -351,7 +354,10 @@ public void TempPathContainsAmpersand2() finally { Environment.SetEnvironmentVariable("TMP", oldTmp); - if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + if (Directory.Exists(newTmp)) + { + FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + } } } @@ -385,7 +391,10 @@ public void TempPathContainsAmpersand3() finally { Environment.SetEnvironmentVariable("TMP", oldTmp); - if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + if (Directory.Exists(newTmp)) + { + FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + } } } @@ -419,7 +428,10 @@ public void TempPathContainsAmpersand4() finally { Environment.SetEnvironmentVariable("TMP", oldTmp); - if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + if (Directory.Exists(newTmp)) + { + FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + } } } @@ -552,7 +564,7 @@ private void RunExec(bool includeNonAnsiInCommand, string expectedEncoding, stri if (expectSuccess) { - ((MockEngine) exec.BuildEngine).AssertLogContains("[hello]"); + ((MockEngine)exec.BuildEngine).AssertLogContains("[hello]"); } Assert.Equal(expectedEncoding, exec.StdOutEncoding); @@ -561,7 +573,9 @@ private void RunExec(bool includeNonAnsiInCommand, string expectedEncoding, stri finally { if (Directory.Exists(folder)) + { FileUtilities.DeleteWithoutTrailingBackslash(folder, true); + } } return; @@ -596,9 +610,13 @@ public void BogusCustomRegexesCauseOneErrorEach() { Exec exec; if (NativeMethodsShared.IsWindows) + { exec = PrepareExec("echo Some output & echo Some output & echo Some output & echo Some output "); + } else + { exec = PrepareExec("echo Some output ; echo Some output ; echo Some output ; echo Some output "); + } exec.CustomErrorRegularExpression = "~!@#$%^_)(*&^%$#@@#XF &%^%T$REd((((([[[["; exec.CustomWarningRegularExpression = "*"; @@ -615,9 +633,14 @@ public void CustomErrorRegexSupplied() { string cmdLine; if (NativeMethodsShared.IsWindows) + { cmdLine = "echo Some output & echo ALERT:This is an error & echo Some more output"; + } else + { cmdLine = "echo Some output ; echo ALERT:This is an error ; echo Some more output"; + } + Exec exec = PrepareExec(cmdLine); bool result = exec.Execute(); @@ -641,9 +664,13 @@ public void CustomWarningRegexSupplied() { string cmdLine; if (NativeMethodsShared.IsWindows) + { cmdLine = "echo Some output & echo YOOHOO:This is a warning & echo Some more output"; + } else + { cmdLine = "echo Some output ; echo YOOHOO:This is a warning ; echo Some more output"; + } Exec exec = PrepareExec(cmdLine); bool result = exec.Execute(); diff --git a/src/Tasks.UnitTests/FileStateTests.cs b/src/Tasks.UnitTests/FileStateTests.cs index 623fd213391..da2d3ab4266 100644 --- a/src/Tasks.UnitTests/FileStateTests.cs +++ b/src/Tasks.UnitTests/FileStateTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -22,8 +22,7 @@ public void BadNoName() Assert.Throws(() => { new FileState(""); - } - ); + }); } [Fact] public void BadCharsCtorOK() @@ -402,8 +401,7 @@ public void DoesNotExistIsDirectory() string file = Guid.NewGuid().ToString("N"); // presumably doesn't exist var x = new FileState(file).IsDirectory; - } - ); + }); } [Fact] public void DoesNotExistDirectoryOrFileExists() diff --git a/src/Tasks.UnitTests/FindAppConfigFile_Tests.cs b/src/Tasks.UnitTests/FindAppConfigFile_Tests.cs index bdd9b209f10..b24510a83dd 100644 --- a/src/Tasks.UnitTests/FindAppConfigFile_Tests.cs +++ b/src/Tasks.UnitTests/FindAppConfigFile_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; using Microsoft.Build.Framework; diff --git a/src/Tasks.UnitTests/FindInList_Tests.cs b/src/Tasks.UnitTests/FindInList_Tests.cs index a1f0d76bf11..4f20967bda6 100644 --- a/src/Tasks.UnitTests/FindInList_Tests.cs +++ b/src/Tasks.UnitTests/FindInList_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Utilities; diff --git a/src/Tasks.UnitTests/FindInvalidProjectReferences_Tests.cs b/src/Tasks.UnitTests/FindInvalidProjectReferences_Tests.cs index a877437c79c..006ff88f7bf 100644 --- a/src/Tasks.UnitTests/FindInvalidProjectReferences_Tests.cs +++ b/src/Tasks.UnitTests/FindInvalidProjectReferences_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; using Microsoft.Build.Shared; @@ -11,7 +11,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class FindInvalidProjectReferences_Tests + public sealed class FindInvalidProjectReferences_Tests { /// /// Verify FindInvalidProjectReferences for several target platform monikers diff --git a/src/Tasks.UnitTests/FindUnderPath_Tests.cs b/src/Tasks.UnitTests/FindUnderPath_Tests.cs index ea2139737ec..62cba40c5fd 100644 --- a/src/Tasks.UnitTests/FindUnderPath_Tests.cs +++ b/src/Tasks.UnitTests/FindUnderPath_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -15,7 +15,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class FindUnderPath_Tests + public sealed class FindUnderPath_Tests { [Fact] public void BasicFilter() diff --git a/src/Tasks.UnitTests/FormatUrl_Tests.cs b/src/Tasks.UnitTests/FormatUrl_Tests.cs index 84d83915f6f..de622591d23 100644 --- a/src/Tasks.UnitTests/FormatUrl_Tests.cs +++ b/src/Tasks.UnitTests/FormatUrl_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -10,7 +10,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class FormatUrl_Tests + public sealed class FormatUrl_Tests { private readonly ITestOutputHelper _out; diff --git a/src/Tasks.UnitTests/GenerateBindingRedirects_Tests.cs b/src/Tasks.UnitTests/GenerateBindingRedirects_Tests.cs index 1b7826288e8..fc0e1104856 100644 --- a/src/Tasks.UnitTests/GenerateBindingRedirects_Tests.cs +++ b/src/Tasks.UnitTests/GenerateBindingRedirects_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -281,7 +281,7 @@ public void AppConfigFileNotSavedWhenIdentical() redirectResults.TargetAppConfigContent.ShouldContain("newVersion=\"40.0.0.0\""); var oldTimestamp = DateTime.Now.Subtract(TimeSpan.FromDays(30)); - + File.SetCreationTime(outputAppConfigFile, oldTimestamp); File.SetLastWriteTime(outputAppConfigFile, oldTimestamp); diff --git a/src/Tasks.UnitTests/GetCompatiblePlatform_Tests.cs b/src/Tasks.UnitTests/GetCompatiblePlatform_Tests.cs index d65901d9ccb..6c3861314bd 100644 --- a/src/Tasks.UnitTests/GetCompatiblePlatform_Tests.cs +++ b/src/Tasks.UnitTests/GetCompatiblePlatform_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; @@ -11,7 +11,7 @@ namespace Microsoft.Build.Tasks.UnitTests { - sealed public class GetCompatiblePlatform_Tests + public sealed class GetCompatiblePlatform_Tests { private readonly ITestOutputHelper _output; @@ -76,7 +76,7 @@ public void ResolvesViaAnyCPUDefault() { BuildEngine = new MockEngine(_output), CurrentProjectPlatform = "x86", - PlatformLookupTable = "AnyCPU=x64", + PlatformLookupTable = "AnyCPU=x64", AnnotatedProjects = new TaskItem[] { projectReference } }; @@ -84,7 +84,7 @@ public void ResolvesViaAnyCPUDefault() task.AssignedProjectsWithPlatform[0].GetMetadata("NearestPlatform").ShouldBe("AnyCPU"); } - + [Fact] public void ResolvesViaAnyCPUDefaultWithDefaultPlatformEnabled() { @@ -98,7 +98,7 @@ public void ResolvesViaAnyCPUDefaultWithDefaultPlatformEnabled() { BuildEngine = new MockEngine(_output), CurrentProjectPlatform = "x86", - PlatformLookupTable = "AnyCPU=x64", + PlatformLookupTable = "AnyCPU=x64", AnnotatedProjects = new TaskItem[] { projectReference } }; @@ -248,7 +248,7 @@ public void PlatformIsChosenAsDefault(string referencedPlatforms, string referen task.AssignedProjectsWithPlatform[0].GetMetadata("NearestPlatform").ShouldBe(string.Empty); task.Log.HasLoggedErrors.ShouldBeFalse(); } - + // When `Platform` is retrieved in "GetTargetFrameworks" and that platform matches what the task has decided the project should be built as // through negotiation. build that project _without_ a global property for Platform. [Fact] diff --git a/src/Tasks.UnitTests/GetFileHash_Tests.cs b/src/Tasks.UnitTests/GetFileHash_Tests.cs index 0452a1f0b52..6f1c7f7f524 100644 --- a/src/Tasks.UnitTests/GetFileHash_Tests.cs +++ b/src/Tasks.UnitTests/GetFileHash_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks.UnitTests/GetInstalledSDKLocations_Tests.cs b/src/Tasks.UnitTests/GetInstalledSDKLocations_Tests.cs index 020faf1e2fa..0763674cfd8 100644 --- a/src/Tasks.UnitTests/GetInstalledSDKLocations_Tests.cs +++ b/src/Tasks.UnitTests/GetInstalledSDKLocations_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // Licensed under the MIT license. See LICENSE file in the project root for full license information. @@ -174,8 +174,7 @@ public void NullTargetPlatformVersion() t.TargetPlatformIdentifier = "Hello"; t.TargetPlatformVersion = null; t.Execute(); - } - ); + }); } /// /// Make sure we get a ArgumentException if null is passed into the target platform version. @@ -189,8 +188,7 @@ public void NullTargetPlatformIdentifier() t.TargetPlatformIdentifier = null; t.TargetPlatformVersion = "1.0"; t.Execute(); - } - ); + }); } /// /// Make sure we get an error message if an empty platform identifier is passed in. diff --git a/src/Tasks.UnitTests/GetReferencePaths_Tests.cs b/src/Tasks.UnitTests/GetReferencePaths_Tests.cs index 3dc4eb161d2..880a4bfae09 100644 --- a/src/Tasks.UnitTests/GetReferencePaths_Tests.cs +++ b/src/Tasks.UnitTests/GetReferencePaths_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Tasks; @@ -17,7 +17,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests for the task which gets the reference assembly paths for a given target framework version / moniker /// - sealed public class GetReferenceAssmeblyPath_Tests + public sealed class GetReferenceAssmeblyPath_Tests { /// /// Test the case where there is a good target framework moniker passed in. diff --git a/src/Tasks.UnitTests/GetSDKReference_Tests.cs b/src/Tasks.UnitTests/GetSDKReference_Tests.cs index 0ab7c94a669..cd5316b3e03 100644 --- a/src/Tasks.UnitTests/GetSDKReference_Tests.cs +++ b/src/Tasks.UnitTests/GetSDKReference_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; diff --git a/src/Tasks.UnitTests/Hash_Tests.cs b/src/Tasks.UnitTests/Hash_Tests.cs index 23a45580e60..c335a54b6b3 100644 --- a/src/Tasks.UnitTests/Hash_Tests.cs +++ b/src/Tasks.UnitTests/Hash_Tests.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Framework; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; using Xunit; @@ -33,7 +36,7 @@ public void HashTaskTest() public void HashTaskEmptyInputTest() { // Hash should be valid for empty item - var emptyItemHash = ExecuteHashTask(new ITaskItem[] {new TaskItem("")}); + var emptyItemHash = ExecuteHashTask(new ITaskItem[] { new TaskItem("") }); Assert.False(string.IsNullOrWhiteSpace(emptyItemHash)); Assert.NotEmpty(emptyItemHash); diff --git a/src/Tasks.UnitTests/HintPathResolver_Tests.cs b/src/Tasks.UnitTests/HintPathResolver_Tests.cs index a3832398132..eb80da45cf8 100644 --- a/src/Tasks.UnitTests/HintPathResolver_Tests.cs +++ b/src/Tasks.UnitTests/HintPathResolver_Tests.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Shared; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Shared; using Microsoft.Build.UnitTests; using Shouldly; using System; diff --git a/src/Tasks.UnitTests/LC_Tests.cs b/src/Tasks.UnitTests/LC_Tests.cs index 3898d2de871..ab82c702fa2 100644 --- a/src/Tasks.UnitTests/LC_Tests.cs +++ b/src/Tasks.UnitTests/LC_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; diff --git a/src/Tasks.UnitTests/MSBuild_Tests.cs b/src/Tasks.UnitTests/MSBuild_Tests.cs index 96bad83b931..eb267ef08e7 100644 --- a/src/Tasks.UnitTests/MSBuild_Tests.cs +++ b/src/Tasks.UnitTests/MSBuild_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -19,7 +19,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class MSBuildTask_Tests : IDisposable + public sealed class MSBuildTask_Tests : IDisposable { private readonly ITestOutputHelper _testOutput; diff --git a/src/Tasks.UnitTests/MakeDir_Tests.cs b/src/Tasks.UnitTests/MakeDir_Tests.cs index 886d7a69aae..b05bd654604 100644 --- a/src/Tasks.UnitTests/MakeDir_Tests.cs +++ b/src/Tasks.UnitTests/MakeDir_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class MakeDir_Tests + public sealed class MakeDir_Tests { /// /// Make sure that attributes set on input items are forwarded to output items. @@ -43,8 +43,7 @@ public void AttributeForwarding() Assert.Equal(dir, t.DirectoriesCreated[0].ItemSpec); Assert.Contains( String.Format(AssemblyResources.GetString("MakeDir.Comment"), dir), - engine.Log - ); + engine.Log); Assert.Equal("en-GB", t.DirectoriesCreated[0].GetMetadata("Locale")); // Output ItemSpec should not be overwritten. @@ -105,11 +104,9 @@ public void SomeInputsFailToCreate() } Assert.Equal(dir, t.DirectoriesCreated[0].ItemSpec); - Assert.Contains - ( + Assert.Contains( String.Format(AssemblyResources.GetString("MakeDir.Comment"), dir), - engine.Log - ); + engine.Log); } finally { @@ -150,8 +147,7 @@ public void CreateNewDirectory() Assert.Equal(dir, t.DirectoriesCreated[0].ItemSpec); Assert.Contains( String.Format(AssemblyResources.GetString("MakeDir.Comment"), dir), - engine.Log - ); + engine.Log); engine.Log = ""; success = t.Execute(); diff --git a/src/Tasks.UnitTests/MockFaultInjectionHelper.cs b/src/Tasks.UnitTests/MockFaultInjectionHelper.cs index c56c2c69513..d35a9d3c6be 100644 --- a/src/Tasks.UnitTests/MockFaultInjectionHelper.cs +++ b/src/Tasks.UnitTests/MockFaultInjectionHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks.UnitTests/MockTypeInfo.cs b/src/Tasks.UnitTests/MockTypeInfo.cs index 4b79f6cac53..3cf5d11f108 100644 --- a/src/Tasks.UnitTests/MockTypeInfo.cs +++ b/src/Tasks.UnitTests/MockTypeInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -111,12 +111,12 @@ public FuncInfo(ICompositeTypeInfo[] parameters, ICompositeTypeInfo returnType) /// public class MockTypeInfo : ITypeInfo, ICompositeTypeInfo, IFixedTypeInfo { - static private int s_HREF_IMPLTYPES_OFFSET = 1000; - static private int s_HREF_VARS_OFFSET = 2000; - static private int s_HREF_FUNCSRET_OFFSET = 3000; - static private int s_HREF_FUNCSPARAM_OFFSET = 4000; - static private int s_HREF_FUNCSPARAM_OFFSET_PERFUNC = 100; - static private int s_HREF_RANGE = 999; + private static int s_HREF_IMPLTYPES_OFFSET = 1000; + private static int s_HREF_VARS_OFFSET = 2000; + private static int s_HREF_FUNCSRET_OFFSET = 3000; + private static int s_HREF_FUNCSPARAM_OFFSET = 4000; + private static int s_HREF_FUNCSPARAM_OFFSET_PERFUNC = 100; + private static int s_HREF_RANGE = 999; private MockTypeLib _containingTypeLib; diff --git a/src/Tasks.UnitTests/MockTypeLib.cs b/src/Tasks.UnitTests/MockTypeLib.cs index 6bfe64ac79e..889aa6f63a1 100644 --- a/src/Tasks.UnitTests/MockTypeLib.cs +++ b/src/Tasks.UnitTests/MockTypeLib.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks.UnitTests/MockUnmanagedMemoryHelper.cs b/src/Tasks.UnitTests/MockUnmanagedMemoryHelper.cs index 257eaff6403..e5ebcfc90ab 100644 --- a/src/Tasks.UnitTests/MockUnmanagedMemoryHelper.cs +++ b/src/Tasks.UnitTests/MockUnmanagedMemoryHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -67,8 +67,7 @@ public IntPtr AllocateHandle(int cb) public void FreeHandle(IntPtr handle) { Assert.True(_allocatedHandles.Exists(new Predicate( - delegate (IntPtr ptr) { return ptr == handle; } - ))); + delegate (IntPtr ptr) { return ptr == handle; }))); Marshal.FreeHGlobal(handle); _allocatedHandles.Remove(handle); diff --git a/src/Tasks.UnitTests/Move_Tests.cs b/src/Tasks.UnitTests/Move_Tests.cs index adf456748bc..d76e34bd350 100644 --- a/src/Tasks.UnitTests/Move_Tests.cs +++ b/src/Tasks.UnitTests/Move_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using Microsoft.Build.Framework; @@ -12,7 +12,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class Move_Tests + public sealed class Move_Tests { /// /// Basic case of moving a file @@ -26,7 +26,10 @@ public void BasicMove() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } + FileInfo file = new FileInfo(sourceFile); file.Attributes |= FileAttributes.ReadOnly; // mark read only @@ -68,7 +71,10 @@ public void BasicMoveOverwriteReadOnlyFilesTrue() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } + FileInfo file = new FileInfo(sourceFile); file.Attributes |= FileAttributes.ReadOnly; // mark read only @@ -119,7 +125,9 @@ public void NonexistentSource() { File.Delete(sourceFile); using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true)) + { sw.Write("This is a destination temp file."); + } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; @@ -139,7 +147,9 @@ public void NonexistentSource() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destinationFile)) + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a destination temp file.", destinationFileContents); // "Expected the destination file to still contain the contents of destination file." } @@ -196,10 +206,14 @@ public void MoveOverExistingFileReadOnlyNoOverwrite() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true)) + { sw.Write("This is a destination temp file."); + } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; @@ -218,7 +232,9 @@ public void MoveOverExistingFileReadOnlyNoOverwrite() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destinationFile)) + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a destination temp file.", destinationFileContents); // "Expected the destination file to be unchanged." @@ -245,10 +261,14 @@ public void MoveOverExistingFileDestinationWriteable() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true)) + { sw.Write("This is a destination temp file."); + } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; @@ -264,7 +284,9 @@ public void MoveOverExistingFileDestinationWriteable() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destinationFile)) + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file." } @@ -291,10 +313,14 @@ public void MoveOverExistingFileOverwriteReadOnly() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true)) + { sw.Write("This is a destination temp file."); + } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; @@ -314,7 +340,9 @@ public void MoveOverExistingFileOverwriteReadOnly() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destinationFile)) + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file." @@ -339,10 +367,14 @@ public void MoveOverExistingFileOverwriteReadOnlyOverWriteReadOnlyFilesTrue() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } using (StreamWriter sw = FileUtilities.OpenWrite(destinationFile, true)) + { sw.Write("This is a destination temp file."); + } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; @@ -362,7 +394,9 @@ public void MoveOverExistingFileOverwriteReadOnlyOverWriteReadOnlyFilesTrue() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destinationFile)) + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file." @@ -652,7 +686,9 @@ public void MoveToNonexistentDestinationFolder() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) + { sw.Write("This is a source temp file."); + } // Don't create the dest folder, let task do that @@ -671,7 +707,9 @@ public void MoveToNonexistentDestinationFolder() string destinationFileContents; using (StreamReader sr = FileUtilities.OpenRead(destFile)) + { destinationFileContents = sr.ReadToEnd(); + } Assert.Equal("This is a source temp file.", destinationFileContents); // "Expected the destination file to contain the contents of source file." @@ -753,7 +791,9 @@ public void Regress451057_ExitGracefullyIfPathNameIsTooLong() try { using (StreamWriter sw = FileUtilities.OpenWrite(sourceFile, true)) // HIGHCHAR: Test writes in UTF8 without preamble. + { sw.Write("This is a source temp file."); + } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; diff --git a/src/Tasks.UnitTests/NuGetPropsImportTests.cs b/src/Tasks.UnitTests/NuGetPropsImportTests.cs index 9dd6200a65d..96880608729 100644 --- a/src/Tasks.UnitTests/NuGetPropsImportTests.cs +++ b/src/Tasks.UnitTests/NuGetPropsImportTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System; diff --git a/src/Tasks.UnitTests/OutputPathTests.cs b/src/Tasks.UnitTests/OutputPathTests.cs index 0671c89356d..ddfd43951b7 100644 --- a/src/Tasks.UnitTests/OutputPathTests.cs +++ b/src/Tasks.UnitTests/OutputPathTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks.UnitTests/PortableTasks_Tests.cs b/src/Tasks.UnitTests/PortableTasks_Tests.cs index 20353efc583..38457261232 100644 --- a/src/Tasks.UnitTests/PortableTasks_Tests.cs +++ b/src/Tasks.UnitTests/PortableTasks_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Linq; diff --git a/src/Tasks.UnitTests/ProjectExtensionsImportTestBase.cs b/src/Tasks.UnitTests/ProjectExtensionsImportTestBase.cs index dae84ce4e97..5b4ad49085b 100644 --- a/src/Tasks.UnitTests/ProjectExtensionsImportTestBase.cs +++ b/src/Tasks.UnitTests/ProjectExtensionsImportTestBase.cs @@ -1,4 +1,5 @@ -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Evaluation; using System; diff --git a/src/Tasks.UnitTests/ProjectExtensionsPropsImportTest.cs b/src/Tasks.UnitTests/ProjectExtensionsPropsImportTest.cs index 567de6da99d..2bbc7bec17d 100644 --- a/src/Tasks.UnitTests/ProjectExtensionsPropsImportTest.cs +++ b/src/Tasks.UnitTests/ProjectExtensionsPropsImportTest.cs @@ -1,4 +1,5 @@ -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -9,7 +10,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests that Microsoft.Common.props successfully imports project extensions written by package management systems. /// - sealed public class ProjectExtensionsPropsImportTest : ProjectExtensionsImportTestBase + public sealed class ProjectExtensionsPropsImportTest : ProjectExtensionsImportTestBase { protected override string CustomImportProjectPath => Path.Combine(ObjectModelHelpers.TempProjectDir, "obj", $"{Path.GetFileName(_projectRelativePath)}.custom.props"); diff --git a/src/Tasks.UnitTests/ProjectExtensionsTargetsImportTest.cs b/src/Tasks.UnitTests/ProjectExtensionsTargetsImportTest.cs index 6ced7746b7d..b123b15d20c 100644 --- a/src/Tasks.UnitTests/ProjectExtensionsTargetsImportTest.cs +++ b/src/Tasks.UnitTests/ProjectExtensionsTargetsImportTest.cs @@ -1,4 +1,5 @@ -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -9,7 +10,7 @@ namespace Microsoft.Build.UnitTests /// /// Tests that Microsoft.Common.props successfully imports project extensions written by package management systems. /// - sealed public class ProjectExtensionsTargetsImportTest : ProjectExtensionsImportTestBase + public sealed class ProjectExtensionsTargetsImportTest : ProjectExtensionsImportTestBase { protected override string CustomImportProjectPath => Path.Combine(ObjectModelHelpers.TempProjectDir, "obj", $"{Path.GetFileName(_projectRelativePath)}.custom.targets"); diff --git a/src/Tasks.UnitTests/PropertyParser_Tests.cs b/src/Tasks.UnitTests/PropertyParser_Tests.cs index 4d3a741f005..fd1029e13d7 100644 --- a/src/Tasks.UnitTests/PropertyParser_Tests.cs +++ b/src/Tasks.UnitTests/PropertyParser_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Tasks; diff --git a/src/Tasks.UnitTests/RARPrecomputedCache_Tests.cs b/src/Tasks.UnitTests/RARPrecomputedCache_Tests.cs index 221f07a2bc9..a889879c079 100644 --- a/src/Tasks.UnitTests/RARPrecomputedCache_Tests.cs +++ b/src/Tasks.UnitTests/RARPrecomputedCache_Tests.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; diff --git a/src/Tasks.UnitTests/ReadLinesFromFile_Tests.cs b/src/Tasks.UnitTests/ReadLinesFromFile_Tests.cs index 29999daefa9..f7b76379327 100644 --- a/src/Tasks.UnitTests/ReadLinesFromFile_Tests.cs +++ b/src/Tasks.UnitTests/ReadLinesFromFile_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; #if FEATURE_SECURITY_PERMISSIONS diff --git a/src/Tasks.UnitTests/RegressionTests.cs b/src/Tasks.UnitTests/RegressionTests.cs index 1b0644ee629..6ca6b081557 100644 --- a/src/Tasks.UnitTests/RegressionTests.cs +++ b/src/Tasks.UnitTests/RegressionTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks.UnitTests/RemoveDir_Tests.cs b/src/Tasks.UnitTests/RemoveDir_Tests.cs index 2becb7a889d..08a081023ea 100644 --- a/src/Tasks.UnitTests/RemoveDir_Tests.cs +++ b/src/Tasks.UnitTests/RemoveDir_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; @@ -14,9 +14,9 @@ namespace Microsoft.Build.UnitTests { - sealed public class RemoveDir_Tests + public sealed class RemoveDir_Tests { - ITestOutputHelper _output; + private ITestOutputHelper _output; public RemoveDir_Tests(ITestOutputHelper output) { _output = output; @@ -82,21 +82,21 @@ public void DeleteEmptyDirectory_WarnsAndContinues() using (TestEnvironment env = TestEnvironment.Create(_output)) { - List list = new List(); + List list = new List(); for (int i = 0; i < 20; i++) - { + { list.Add(new TaskItem("")); - } + } - RemoveDir t = new RemoveDir(); - t.Directories = list.ToArray(); - t.BuildEngine = new MockEngine(_output); - t.Execute().ShouldBeTrue(); + RemoveDir t = new RemoveDir(); + t.Directories = list.ToArray(); + t.BuildEngine = new MockEngine(_output); + t.Execute().ShouldBeTrue(); t.RemovedDirectories.Length.ShouldBe(0); ((MockEngine)t.BuildEngine).Warnings.ShouldBe(20); - ((MockEngine)t.BuildEngine).AssertLogContains("MSB3232"); + ((MockEngine)t.BuildEngine).AssertLogContains("MSB3232"); } } } diff --git a/src/Tasks.UnitTests/RemoveDuplicates_Tests.cs b/src/Tasks.UnitTests/RemoveDuplicates_Tests.cs index 4e261b92771..1605c2d5370 100644 --- a/src/Tasks.UnitTests/RemoveDuplicates_Tests.cs +++ b/src/Tasks.UnitTests/RemoveDuplicates_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; @@ -9,7 +9,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class RemoveDuplicates_Tests + public sealed class RemoveDuplicates_Tests { /// /// Pass one item in, get the same item back. diff --git a/src/Tasks.UnitTests/ResolveCodeAnalysisRuleSet_Tests.cs b/src/Tasks.UnitTests/ResolveCodeAnalysisRuleSet_Tests.cs index 355e98dc8a8..367bc2660bf 100644 --- a/src/Tasks.UnitTests/ResolveCodeAnalysisRuleSet_Tests.cs +++ b/src/Tasks.UnitTests/ResolveCodeAnalysisRuleSet_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks.UnitTests/ResolveComReference_Tests.cs b/src/Tasks.UnitTests/ResolveComReference_Tests.cs index cb8bb5379f2..0768fb9ea36 100644 --- a/src/Tasks.UnitTests/ResolveComReference_Tests.cs +++ b/src/Tasks.UnitTests/ResolveComReference_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_APPDOMAIN @@ -22,7 +22,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class ResolveComReference_Tests + public sealed class ResolveComReference_Tests { /// /// Creates a valid task item that's modified later @@ -637,7 +637,7 @@ public void TestCheckForConflictingReferences() Assert.True(rcr.CheckForConflictingReferences()); Assert.Equal(3, rcr.allProjectRefs.Count); - + // duplicate refs should not be treated as conflicts ComReferenceInfo referenceInfo = new ComReferenceInfo(tlbRefInfo); rcr.allProjectRefs.Add(referenceInfo); @@ -807,20 +807,16 @@ private void CheckAxReferenceRCWTlbExists(RcwStyle rcwStyle, bool includeVersion var embedInteropTypes = tlbRefInfo.taskItem.GetMetadata(ItemMetadataNames.embedInteropTypes); Assert.Equal("false", embedInteropTypes); // "The tlb wrapper for the activex control should have EmbedInteropTypes=false not " + embedInteropTypes); Assert.True(ComReference.AreTypeLibAttrEqual(tlbRefInfo.attr, axRefInfo.attr)); // "reference information should be the same" - Assert.Equal(TlbReference.GetWrapperFileName - ( + Assert.Equal(TlbReference.GetWrapperFileName( axRefInfo.taskItem.GetMetadata(ComReferenceItemMetadataNames.tlbReferenceName), includeVersionInInteropName, axRefInfo.attr.wMajorVerNum, - axRefInfo.attr.wMinorVerNum - ), - TlbReference.GetWrapperFileName - ( + axRefInfo.attr.wMinorVerNum), + TlbReference.GetWrapperFileName( tlbRefInfo.typeLibName, includeVersionInInteropName, tlbRefInfo.attr.wMajorVerNum, - tlbRefInfo.attr.wMinorVerNum - )); // "Expected Ax reference's RCW name to match the new TLB" + tlbRefInfo.attr.wMinorVerNum)); // "Expected Ax reference's RCW name to match the new TLB" } } } diff --git a/src/Tasks.UnitTests/ResolveNonMSBuildProjectOutput_Tests.cs b/src/Tasks.UnitTests/ResolveNonMSBuildProjectOutput_Tests.cs index 49bed4e7b44..9948b29d469 100644 --- a/src/Tasks.UnitTests/ResolveNonMSBuildProjectOutput_Tests.cs +++ b/src/Tasks.UnitTests/ResolveNonMSBuildProjectOutput_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -14,7 +14,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class ResolveNonMSBuildProjectOutput_Tests + public sealed class ResolveNonMSBuildProjectOutput_Tests { private const string attributeProject = "Project"; @@ -25,16 +25,24 @@ public ResolveNonMSBuildProjectOutput_Tests(ITestOutputHelper output) _output = output; } - static internal ITaskItem CreateReferenceItem(string itemSpec, string projectGuid, string package, string name) + internal static ITaskItem CreateReferenceItem(string itemSpec, string projectGuid, string package, string name) { TaskItem reference = new TaskItem(itemSpec); if (projectGuid != null) + { reference.SetMetadata(attributeProject, projectGuid); + } + if (package != null) + { reference.SetMetadata("Package", package); + } + if (name != null) + { reference.SetMetadata("Name", name); + } return reference; } @@ -76,7 +84,7 @@ public void TestVerifyReferenceAttributes() false, "Project"); } - static internal string CreatePregeneratedPathDoc(IDictionary projectOutputs) + internal static string CreatePregeneratedPathDoc(IDictionary projectOutputs) { string xmlString = ""; diff --git a/src/Tasks.UnitTests/ResolveSDKReference_Tests.cs b/src/Tasks.UnitTests/ResolveSDKReference_Tests.cs index 0bcb3ac0fec..8fd537d5c4f 100644 --- a/src/Tasks.UnitTests/ResolveSDKReference_Tests.cs +++ b/src/Tasks.UnitTests/ResolveSDKReference_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -1443,8 +1443,7 @@ public void NullSDKReferences() ResolveSDKReference t = new ResolveSDKReference(); t.SDKReferences = null; bool succeeded = t.Execute(); - } - ); + }); } /// /// When a null is passed into the set of InstalledSDKS property make sure we get the correct exception out. @@ -1460,8 +1459,7 @@ public void NullInstalledSDKs() ResolveSDKReference t = new ResolveSDKReference(); t.InstalledSDKs = null; bool succeeded = t.Execute(); - } - ); + }); } /// diff --git a/src/Tasks.UnitTests/ResolveVCProjectOutput_Tests.cs b/src/Tasks.UnitTests/ResolveVCProjectOutput_Tests.cs index 1dd312a7790..4364e17ff36 100644 --- a/src/Tasks.UnitTests/ResolveVCProjectOutput_Tests.cs +++ b/src/Tasks.UnitTests/ResolveVCProjectOutput_Tests.cs @@ -1,4 +1,7 @@ -/* +// 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.Collections; using System.IO; diff --git a/src/Tasks.UnitTests/ResourceHandling/GenerateResourceOutOfProc_Tests.cs b/src/Tasks.UnitTests/ResourceHandling/GenerateResourceOutOfProc_Tests.cs index dc5742c039b..f2c6b9d0524 100644 --- a/src/Tasks.UnitTests/ResourceHandling/GenerateResourceOutOfProc_Tests.cs +++ b/src/Tasks.UnitTests/ResourceHandling/GenerateResourceOutOfProc_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -19,7 +19,7 @@ namespace Microsoft.Build.UnitTests.GenerateResource_Tests.OutOfProc { [Trait("Category", "mono-osx-failing")] [Trait("Category", "mono-windows-failing")] - sealed public class RequiredTransformations + public sealed class RequiredTransformations { private readonly ITestOutputHelper _output; @@ -107,7 +107,9 @@ public void OutputResourceMetadataPopulatedOnInputItems() File.Delete(resxFile2); File.Delete(resxFile3); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -176,8 +178,15 @@ public void ResX2ResourcesWithReferences() finally { File.Delete(systemDll); - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } @@ -219,7 +228,9 @@ public void BasicResources2ResX() File.Delete(t.OutputResources[0].ItemSpec); File.Delete(t2a.OutputResources[0].ItemSpec); foreach (ITaskItem item in t2b.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -245,7 +256,9 @@ public void BasicResources2Text() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -397,11 +410,30 @@ public void ForceSomeOutOfDate() } finally { - if (firstResx != null) File.Delete(firstResx); - if (secondResx != null) File.Delete(secondResx); - if (cache != null) File.Delete(cache); - if (firstResx != null) File.Delete(Path.ChangeExtension(firstResx, ".resources")); - if (secondResx != null) File.Delete(Path.ChangeExtension(secondResx, ".resources")); + if (firstResx != null) + { + File.Delete(firstResx); + } + + if (secondResx != null) + { + File.Delete(secondResx); + } + + if (cache != null) + { + File.Delete(cache); + } + + if (firstResx != null) + { + File.Delete(Path.ChangeExtension(firstResx, ".resources")); + } + + if (secondResx != null) + { + File.Delete(Path.ChangeExtension(secondResx, ".resources")); + } } } @@ -511,10 +543,25 @@ public void NothingOutOfDate() } finally { - if (resxFile != null) File.Delete(resxFile); - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile1 != null) File.Delete(resourcesFile1); - if (resourcesFile2 != null) File.Delete(resourcesFile2); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile1 != null) + { + File.Delete(resourcesFile1); + } + + if (resourcesFile2 != null) + { + File.Delete(resourcesFile2); + } } } @@ -574,10 +621,25 @@ public void NothingOutOfDateExceptReference() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (stateFile != null) File.Delete(stateFile); - if (localSystemDll != null) File.Delete(localSystemDll); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (stateFile != null) + { + File.Delete(stateFile); + } + + if (localSystemDll != null) + { + File.Delete(localSystemDll); + } } } @@ -625,10 +687,25 @@ public void NothingOutOfDateExceptAdditionalInput() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (additionalInputs?[0] != null && File.Exists(additionalInputs[0].ItemSpec)) File.Delete(additionalInputs[0].ItemSpec); - if (additionalInputs?[1] != null && File.Exists(additionalInputs[1].ItemSpec)) File.Delete(additionalInputs[1].ItemSpec); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (additionalInputs?[0] != null && File.Exists(additionalInputs[0].ItemSpec)) + { + File.Delete(additionalInputs[0].ItemSpec); + } + + if (additionalInputs?[1] != null && File.Exists(additionalInputs[1].ItemSpec)) + { + File.Delete(additionalInputs[1].ItemSpec); + } } } @@ -654,7 +731,9 @@ public void BasicText2ResX() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -698,7 +777,9 @@ public void ResX2ResX() File.Delete(t.OutputResources[0].ItemSpec); File.Delete(t2a.OutputResources[0].ItemSpec); foreach (ITaskItem item in t2b.FilesWritten) + { File.Delete(item.ItemSpec); + } } catch (Exception e) { @@ -740,10 +821,15 @@ public void Text2Text() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } + File.Delete(t2.Sources[0].ItemSpec); foreach (ITaskItem item in t2.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -777,9 +863,13 @@ public void StronglyTypedResources() string typeName = null; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; @@ -832,9 +922,13 @@ public void StronglyTypedResourcesUpToDate() string typeName = null; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; @@ -956,10 +1050,25 @@ public void StronglyTypedResourcesOutOfDate() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (strFile != null) File.Delete(strFile); - if (cacheFile != null) File.Delete(cacheFile); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (strFile != null) + { + File.Delete(strFile); + } + + if (cacheFile != null) + { + File.Delete(cacheFile); + } } } @@ -1009,9 +1118,20 @@ public void StronglyTypedResourcesWithFilename() } finally { - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (strFile != null) File.Delete(strFile); + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (strFile != null) + { + File.Delete(strFile); + } } } @@ -1044,9 +1164,13 @@ public void StronglyTypedResourcesVB() string typeName = null; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; @@ -1156,7 +1280,7 @@ public void STRWithResourcesNamespaceAndSTRNamespaceVB() } } - sealed public class TransformationErrors + public sealed class TransformationErrors { private readonly ITestOutputHelper _output; @@ -1207,7 +1331,9 @@ public void TextToResourcesBadFormat() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } // text file uses the strings token; since it's only a warning we have to have special asserts @@ -1224,7 +1350,9 @@ public void TextToResourcesBadFormat() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1273,10 +1401,25 @@ public void FailedResXReader() } finally { - if (resxFile1 != null) File.Delete(resxFile1); - if (resxFile2 != null) File.Delete(resxFile2); - if (resourcesFile1 != null) File.Delete(resourcesFile1); - if (resourcesFile2 != null) File.Delete(resourcesFile2); + if (resxFile1 != null) + { + File.Delete(resxFile1); + } + + if (resxFile2 != null) + { + File.Delete(resxFile2); + } + + if (resourcesFile1 != null) + { + File.Delete(resourcesFile1); + } + + if (resourcesFile2 != null) + { + File.Delete(resourcesFile2); + } } } @@ -1333,10 +1476,25 @@ public void FailedResXReaderWithAllOutputResourcesSpecified() } finally { - if (resxFile1 != null) File.Delete(resxFile1); - if (resxFile2 != null) File.Delete(resxFile2); - if (resourcesFile1 != null) File.Delete(resourcesFile1); - if (resourcesFile2 != null) File.Delete(resourcesFile2); + if (resxFile1 != null) + { + File.Delete(resxFile1); + } + + if (resxFile2 != null) + { + File.Delete(resxFile2); + } + + if (resourcesFile1 != null) + { + File.Delete(resourcesFile1); + } + + if (resourcesFile2 != null) + { + File.Delete(resourcesFile2); + } } } @@ -1361,7 +1519,9 @@ public void DuplicateResourceNames() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1390,7 +1550,9 @@ public void UnsupportedTextType() File.Delete(t.Sources[0].ItemSpec); File.Delete(bitmap); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1418,8 +1580,15 @@ public void InvalidStateFile() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } @@ -1452,7 +1621,9 @@ public void FailedResourceReader() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1483,7 +1654,9 @@ public void FailedSTRProperty() File.Delete(t.Sources[0].ItemSpec); File.Delete(t.StronglyTypedFileName); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1515,12 +1688,15 @@ public void InvalidReference() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } } - sealed public class PropertyHandling + public sealed class PropertyHandling { private readonly ITestOutputHelper _output; @@ -1567,7 +1743,9 @@ public void AttributeForwarding() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1595,7 +1773,9 @@ public void AttributeForwardingOnEmptyOutputs() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1607,9 +1787,9 @@ public void OutputFilesNotSpecified() GenerateResource t = Utilities.CreateTaskOutOfProc(_output); t.Sources = new ITaskItem[] { - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), new TaskItem( Utilities.WriteTestResX(false, null, null)), }; @@ -1624,9 +1804,14 @@ public void OutputFilesNotSpecified() // Done, so clean up. foreach (ITaskItem item in t.Sources) + { File.Delete(item.ItemSpec); + } + foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1640,9 +1825,9 @@ public void FilesWrittenSet() GenerateResource t = Utilities.CreateTaskOutOfProc(_output); t.Sources = new ITaskItem[] { - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), new TaskItem( Utilities.WriteTestResX(false, null, null)), }; @@ -1684,9 +1869,9 @@ public void OutputFilesPartialInputs() try { t.Sources = new ITaskItem[] { - new TaskItem( Utilities.WriteTestText(null, null) ), - new TaskItem( Utilities.WriteTestText(null, null) ), - new TaskItem( Utilities.WriteTestText("goober", null) ), + new TaskItem( Utilities.WriteTestText(null, null)), + new TaskItem( Utilities.WriteTestText(null, null)), + new TaskItem( Utilities.WriteTestText("goober", null)), new TaskItem( Utilities.WriteTestText(null, null)), }; foreach (ITaskItem taskItem in t.Sources) @@ -1826,7 +2011,7 @@ public void StronglyTypedFileName() } } - sealed public class PropertyErrors + public sealed class PropertyErrors { private readonly ITestOutputHelper _output; @@ -1854,7 +2039,9 @@ public void EmptySources() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -1921,8 +2108,15 @@ public void SourceItemMissing() } finally { - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile != null) File.Delete(resourcesFile); + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } @@ -1959,7 +2153,9 @@ public void StateFileUnwritable() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -1992,7 +2188,9 @@ public void InputFileExtension() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2024,7 +2222,9 @@ public void OutputFileExtension() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2054,7 +2254,9 @@ public void SourcesMatchesOutputResources() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2086,7 +2288,9 @@ public void UnknownStronglyTypedLanguage() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2119,10 +2323,25 @@ public void StronglyTypedResourceWithMoreThanOneInputResourceFile() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resxFile2 != null) File.Delete(resxFile2); - if (resxFile != null) File.Delete(Path.ChangeExtension(resxFile, ".resources")); - if (resxFile2 != null) File.Delete(Path.ChangeExtension(resxFile2, ".resources")); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resxFile2 != null) + { + File.Delete(resxFile2); + } + + if (resxFile != null) + { + File.Delete(Path.ChangeExtension(resxFile, ".resources")); + } + + if (resxFile2 != null) + { + File.Delete(Path.ChangeExtension(resxFile2, ".resources")); + } } } @@ -2165,7 +2384,10 @@ public void BadStronglyTypedFilename() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2199,7 +2421,10 @@ public void StronglyTypedResourceClassWithoutLanguage() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2233,7 +2458,10 @@ public void StronglyTypedResourceNamespaceWithoutLanguage() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2267,7 +2495,10 @@ public void StronglyTypedResourceFilenameWithoutLanguage() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2312,9 +2543,20 @@ public void StronglyTypedResourceFileIsExistingDirectory() } finally { - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (dir != null) FileUtilities.DeleteWithoutTrailingBackslash(dir); + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (dir != null) + { + FileUtilities.DeleteWithoutTrailingBackslash(dir); + } } } @@ -2340,7 +2582,10 @@ public void Regress25163_OutputResourcesContainsInvalidPathCharacters() } finally { - if (resourcesFile != null) File.Delete(resourcesFile); + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } } diff --git a/src/Tasks.UnitTests/ResourceHandling/GenerateResource_Tests.cs b/src/Tasks.UnitTests/ResourceHandling/GenerateResource_Tests.cs index aea579d8787..1a62accb608 100644 --- a/src/Tasks.UnitTests/ResourceHandling/GenerateResource_Tests.cs +++ b/src/Tasks.UnitTests/ResourceHandling/GenerateResource_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -76,7 +76,7 @@ public void BasicResX2Resources(bool resourceReadOnly) Assert.Equal(".resources", Path.GetExtension(resourcesFile)); resourcesFile = t.FilesWritten[0].ItemSpec; Assert.Equal(".resources", Path.GetExtension(resourcesFile)); - + Utilities.AssertStateFileWasWritten(t); Utilities.AssertLogContainsResource(t, "GenerateResource.ProcessingFile", resxFile, resourcesFile); @@ -137,7 +137,9 @@ public void OutputResourceMetadataPopulatedOnInputItems() File.Delete(resxFile2); File.Delete(resxFile3); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -162,7 +164,7 @@ public void BasicText2Resources() Assert.Equal(".resources", Path.GetExtension(resourcesFile)); resourcesFile = t.FilesWritten[0].ItemSpec; Assert.Equal(".resources", Path.GetExtension(resourcesFile)); - + Utilities.AssertStateFileWasWritten(t); Utilities.AssertLogContainsResource(t, "GenerateResource.ProcessingFile", textFile, resourcesFile); @@ -217,8 +219,15 @@ public void ResX2ResourcesWithReferences() finally { File.Delete(systemDll); - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } @@ -228,7 +237,7 @@ public void ResX2ResourcesWithReferences() #if FEATURE_RESXREADER_LIVEDESERIALIZATION [Fact] #else - [Fact (Skip = "ResGen.exe not supported on .NET Core MSBuild")] + [Fact(Skip = "ResGen.exe not supported on .NET Core MSBuild")] #endif public void BasicResources2ResX() { @@ -266,7 +275,9 @@ public void BasicResources2ResX() File.Delete(t.OutputResources[0].ItemSpec); File.Delete(t2a.OutputResources[0].ItemSpec); foreach (ITaskItem item in t2b.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -298,7 +309,9 @@ public void BasicResources2Text() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -314,7 +327,7 @@ public void ForceOutOfDate() GenerateResource t = Utilities.CreateTask(_output); t.StateFile = new TaskItem(_env.GetTempFile(".cache").Path); - t.Sources = new ITaskItem[] {new TaskItem(resxFileInput)}; + t.Sources = new ITaskItem[] { new TaskItem(resxFileInput) }; Utilities.ExecuteTask(t); @@ -323,13 +336,24 @@ public void ForceOutOfDate() Path.GetExtension(resourceOutput).ShouldBe(".resources"); Path.GetExtension(t.FilesWritten[0].ItemSpec).ShouldBe(".resources"); + + /* Unmerged change from project 'Microsoft.Build.Tasks.UnitTests (net7.0)' + Before: Utilities.AssertLogContainsResource(t, "GenerateResource.OutputDoesntExist", t.OutputResources[0].ItemSpec); + Utilities.AssertStateFileWasWritten(t); + After: + Utilities.AssertLogContainsResource(t, "GenerateResource.OutputDoesntExist", t.OutputResources[0].ItemSpec); + + Utilities.AssertStateFileWasWritten(t); + */ + Utilities.AssertLogContainsResource(t, "GenerateResource.OutputDoesntExist", t.OutputResources[0].ItemSpec); + Utilities.AssertStateFileWasWritten(t); GenerateResource t2 = Utilities.CreateTask(_output); t2.StateFile = new TaskItem(t.StateFile); - t2.Sources = new ITaskItem[] {new TaskItem(resxFileInput)}; + t2.Sources = new ITaskItem[] { new TaskItem(resxFileInput) }; // Execute the task again when the input (5m ago) is newer than the previous outputs (10m ago) File.SetLastWriteTime(resxFileInput, DateTime.Now.Subtract(TimeSpan.FromMinutes(5))); @@ -446,7 +470,7 @@ public void WritingNonString_WithoutProperyOrSystemResourcesExtensions_FailsUnle usePreserialized, _env, useSystemResourcesExtensions); - + try { t.Sources = new ITaskItem[] { new TaskItem(resxFile) }; @@ -604,7 +628,7 @@ public void ForceSomeOutOfDate() GenerateResource createResources = Utilities.CreateTask(_output); createResources.StateFile = new TaskItem(cache); - createResources.Sources = new ITaskItem[] {new TaskItem(firstResx), new TaskItem(secondResx)}; + createResources.Sources = new ITaskItem[] { new TaskItem(firstResx), new TaskItem(secondResx) }; _output.WriteLine("Transform both"); Utilities.ExecuteTask(createResources); @@ -616,7 +640,7 @@ public void ForceSomeOutOfDate() _output.WriteLine("Create a new task to transform them again"); GenerateResource t2 = Utilities.CreateTask(_output); t2.StateFile = new TaskItem(createResources.StateFile.ItemSpec); - t2.Sources = new ITaskItem[] {new TaskItem(firstResx), new TaskItem(secondResx)}; + t2.Sources = new ITaskItem[] { new TaskItem(firstResx), new TaskItem(secondResx) }; System.Threading.Thread.Sleep(200); if (!NativeMethodsShared.IsWindows) @@ -730,7 +754,7 @@ public void NothingOutOfDate() Assert.Equal(t.FilesWritten[0].ItemSpec, resourcesFile1); Assert.Equal(t.OutputResources[1].ItemSpec, resourcesFile2); Assert.Equal(t.FilesWritten[1].ItemSpec, resourcesFile2); - + Utilities.AssertStateFileWasWritten(t); // Repeat, and it should do nothing as they are up to date @@ -749,7 +773,7 @@ public void NothingOutOfDate() Assert.Equal(t2.FilesWritten[0].ItemSpec, resourcesFile1); Assert.Equal(t2.OutputResources[1].ItemSpec, resourcesFile2); Assert.Equal(t2.FilesWritten[1].ItemSpec, resourcesFile2); - + Utilities.AssertStateFileWasWritten(t2); Assert.True(time.Equals(File.GetLastWriteTime(t2.OutputResources[0].ItemSpec))); @@ -757,10 +781,25 @@ public void NothingOutOfDate() } finally { - if (resxFile != null) File.Delete(resxFile); - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile1 != null) File.Delete(resourcesFile1); - if (resourcesFile2 != null) File.Delete(resourcesFile2); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile1 != null) + { + File.Delete(resourcesFile1); + } + + if (resourcesFile2 != null) + { + File.Delete(resourcesFile2); + } } } @@ -831,10 +870,25 @@ public void NothingOutOfDateExceptReference() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (stateFile != null) File.Delete(stateFile); - if (localSystemDll != null) File.Delete(localSystemDll); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (stateFile != null) + { + File.Delete(stateFile); + } + + if (localSystemDll != null) + { + File.Delete(localSystemDll); + } } } @@ -889,10 +943,25 @@ public void NothingOutOfDateExceptAdditionalInput() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (additionalInputs?[0] != null && File.Exists(additionalInputs[0].ItemSpec)) File.Delete(additionalInputs[0].ItemSpec); - if (additionalInputs?[1] != null && File.Exists(additionalInputs[1].ItemSpec)) File.Delete(additionalInputs[1].ItemSpec); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (additionalInputs?[0] != null && File.Exists(additionalInputs[0].ItemSpec)) + { + File.Delete(additionalInputs[0].ItemSpec); + } + + if (additionalInputs?[1] != null && File.Exists(additionalInputs[1].ItemSpec)) + { + File.Delete(additionalInputs[1].ItemSpec); + } } } @@ -925,7 +994,9 @@ public void BasicText2ResX() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -971,7 +1042,9 @@ public void ResX2ResX() File.Delete(t.OutputResources[0].ItemSpec); File.Delete(t2a.OutputResources[0].ItemSpec); foreach (ITaskItem item in t2b.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1012,10 +1085,15 @@ public void Text2Text() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } + File.Delete(t2.Sources[0].ItemSpec); foreach (ITaskItem item in t2.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1052,9 +1130,13 @@ public void StronglyTypedResources() string typeName = null; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; @@ -1112,9 +1194,13 @@ public void StronglyTypedResourcesUpToDate() string typeName = null; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; @@ -1235,9 +1321,20 @@ public void StronglyTypedResourcesOutOfDate() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (strFile != null) File.Delete(strFile); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (strFile != null) + { + File.Delete(strFile); + } } } @@ -1290,9 +1387,20 @@ public void StronglyTypedResourcesWithFilename() } finally { - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (strFile != null) File.Delete(strFile); + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (strFile != null) + { + File.Delete(strFile); + } } } @@ -1329,9 +1437,13 @@ public void StronglyTypedResourcesVB() string typeName = null; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; @@ -1506,7 +1618,7 @@ public void STRWithResourcesNamespaceAndSTRNamespaceVB() } } - sealed public class TransformationErrors + public sealed class TransformationErrors { private readonly ITestOutputHelper _output; @@ -1554,7 +1666,9 @@ public void TextToResourcesBadFormat() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } // text file uses the strings token; since it's only a warning we have to have special asserts @@ -1571,7 +1685,9 @@ public void TextToResourcesBadFormat() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1601,8 +1717,19 @@ public void FailedResXReader() File.Delete(resourcesFile2); bool success = t.Execute(); // Task should have failed + + /* Unmerged change from project 'Microsoft.Build.Tasks.UnitTests (net7.0)' + Before: Assert.False(success); + Utilities.AssertStateFileWasWritten(t); + After: + Assert.False(success); + + Utilities.AssertStateFileWasWritten(t); + */ + Assert.False(success); + Utilities.AssertStateFileWasWritten(t); // Should not have created an output for the invalid resx @@ -1618,10 +1745,25 @@ public void FailedResXReader() } finally { - if (resxFile1 != null) File.Delete(resxFile1); - if (resxFile2 != null) File.Delete(resxFile2); - if (resourcesFile1 != null) File.Delete(resourcesFile1); - if (resourcesFile2 != null) File.Delete(resourcesFile2); + if (resxFile1 != null) + { + File.Delete(resxFile1); + } + + if (resxFile2 != null) + { + File.Delete(resxFile2); + } + + if (resourcesFile1 != null) + { + File.Delete(resourcesFile1); + } + + if (resourcesFile2 != null) + { + File.Delete(resourcesFile2); + } } } @@ -1654,8 +1796,19 @@ public void FailedResXReaderWithAllOutputResourcesSpecified() bool success = t.Execute(); // Task should have failed + + /* Unmerged change from project 'Microsoft.Build.Tasks.UnitTests (net7.0)' + Before: Assert.False(success); + Utilities.AssertStateFileWasWritten(t); + After: + Assert.False(success); + + Utilities.AssertStateFileWasWritten(t); + */ + Assert.False(success); + Utilities.AssertStateFileWasWritten(t); // Should not have created an output for the invalid resx @@ -1675,10 +1828,25 @@ public void FailedResXReaderWithAllOutputResourcesSpecified() } finally { - if (resxFile1 != null) File.Delete(resxFile1); - if (resxFile2 != null) File.Delete(resxFile2); - if (resourcesFile1 != null) File.Delete(resourcesFile1); - if (resourcesFile2 != null) File.Delete(resourcesFile2); + if (resxFile1 != null) + { + File.Delete(resxFile1); + } + + if (resxFile2 != null) + { + File.Delete(resxFile2); + } + + if (resourcesFile1 != null) + { + File.Delete(resourcesFile1); + } + + if (resourcesFile2 != null) + { + File.Delete(resourcesFile2); + } } } @@ -1702,7 +1870,9 @@ public void DuplicateResourceNames() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1728,7 +1898,9 @@ public void UnsupportedTextType() File.Delete(t.Sources[0].ItemSpec); File.Delete(bitmap); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1759,8 +1931,15 @@ public void InvalidStateFile() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resourcesFile != null) File.Delete(resourcesFile); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } @@ -1792,7 +1971,9 @@ public void FailedResourceReader() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } [Theory] @@ -1848,7 +2029,9 @@ public void FailedSTRProperty() File.Delete(t.Sources[0].ItemSpec); File.Delete(t.StronglyTypedFileName); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1882,12 +2065,15 @@ public void InvalidReference() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } } - sealed public class PropertyHandling + public sealed class PropertyHandling { private readonly ITestOutputHelper _output; @@ -1934,7 +2120,9 @@ public void AttributeForwarding() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1962,7 +2150,9 @@ public void AttributeForwardingOnEmptyOutputs() // Done, so clean up. File.Delete(t.Sources[0].ItemSpec); foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -1974,9 +2164,9 @@ public void OutputFilesNotSpecified() GenerateResource t = Utilities.CreateTask(_output); t.Sources = new ITaskItem[] { - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), new TaskItem( Utilities.WriteTestResX(false, null, null)), }; @@ -1991,9 +2181,14 @@ public void OutputFilesNotSpecified() // Done, so clean up. foreach (ITaskItem item in t.Sources) + { File.Delete(item.ItemSpec); + } + foreach (ITaskItem item in t.FilesWritten) + { File.Delete(item.ItemSpec); + } } /// @@ -2005,9 +2200,9 @@ public void FilesWrittenSet() GenerateResource t = Utilities.CreateTask(_output); t.Sources = new ITaskItem[] { - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), - new TaskItem( Utilities.WriteTestResX(false, null, null) ), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), + new TaskItem( Utilities.WriteTestResX(false, null, null)), new TaskItem( Utilities.WriteTestResX(false, null, null)), }; @@ -2023,7 +2218,7 @@ public void FilesWrittenSet() Assert.Equal(t.FilesWritten[i].ItemSpec, t.OutputResources[i].ItemSpec); Assert.True(File.Exists(t.FilesWritten[i].ItemSpec)); } - + Utilities.AssertStateFileWasWritten(t); // Done, so clean up. @@ -2049,9 +2244,9 @@ public void OutputFilesPartialInputs() try { t.Sources = new ITaskItem[] { - new TaskItem( Utilities.WriteTestText(null, null) ), - new TaskItem( Utilities.WriteTestText(null, null) ), - new TaskItem( Utilities.WriteTestText("goober", null) ), + new TaskItem( Utilities.WriteTestText(null, null)), + new TaskItem( Utilities.WriteTestText(null, null)), + new TaskItem( Utilities.WriteTestText("goober", null)), new TaskItem( Utilities.WriteTestText(null, null)), }; @@ -2083,8 +2278,19 @@ public void OutputFilesPartialInputs() // FilesWritten should contain only the 3 successfully output .resources and the cache Assert.Equal(t.FilesWritten[0].ItemSpec, Path.ChangeExtension(t.Sources[0].ItemSpec, ".resources")); Assert.Equal(t.FilesWritten[1].ItemSpec, Path.ChangeExtension(t.Sources[1].ItemSpec, ".resources")); + + /* Unmerged change from project 'Microsoft.Build.Tasks.UnitTests (net7.0)' + Before: Assert.Equal(t.FilesWritten[2].ItemSpec, Path.ChangeExtension(t.Sources[3].ItemSpec, ".resources")); + Utilities.AssertStateFileWasWritten(t); + After: + Assert.Equal(t.FilesWritten[2].ItemSpec, Path.ChangeExtension(t.Sources[3].ItemSpec, ".resources")); + + Utilities.AssertStateFileWasWritten(t); + */ + Assert.Equal(t.FilesWritten[2].ItemSpec, Path.ChangeExtension(t.Sources[3].ItemSpec, ".resources")); + Utilities.AssertStateFileWasWritten(t); // Make sure there was an error on the second resource @@ -2205,7 +2411,7 @@ public void StronglyTypedFileName() } } - sealed public class PropertyErrors + public sealed class PropertyErrors { private readonly ITestOutputHelper _output; @@ -2233,7 +2439,9 @@ public void EmptySources() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2297,8 +2505,15 @@ public void SourceItemMissing() } finally { - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile != null) File.Delete(resourcesFile); + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } @@ -2333,7 +2548,9 @@ public void StateFileUnwritable() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2365,7 +2582,9 @@ public void InputFileExtension() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2395,7 +2614,9 @@ public void OutputFileExtension() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2425,7 +2646,9 @@ public void SourcesMatchesOutputResources() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2456,7 +2679,9 @@ public void UnknownStronglyTypedLanguage() foreach (ITaskItem item in t.FilesWritten) { if (item.ItemSpec != null) + { File.Delete(item.ItemSpec); + } } } } @@ -2489,10 +2714,25 @@ public void StronglyTypedResourceWithMoreThanOneInputResourceFile() } finally { - if (resxFile != null) File.Delete(resxFile); - if (resxFile2 != null) File.Delete(resxFile2); - if (resxFile != null) File.Delete(Path.ChangeExtension(resxFile, ".resources")); - if (resxFile2 != null) File.Delete(Path.ChangeExtension(resxFile2, ".resources")); + if (resxFile != null) + { + File.Delete(resxFile); + } + + if (resxFile2 != null) + { + File.Delete(resxFile2); + } + + if (resxFile != null) + { + File.Delete(Path.ChangeExtension(resxFile, ".resources")); + } + + if (resxFile2 != null) + { + File.Delete(Path.ChangeExtension(resxFile2, ".resources")); + } } } @@ -2529,7 +2769,10 @@ public void BadStronglyTypedFilename() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2563,7 +2806,10 @@ public void StronglyTypedResourceClassWithoutLanguage() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2597,7 +2843,10 @@ public void StronglyTypedResourceNamespaceWithoutLanguage() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2631,7 +2880,10 @@ public void StronglyTypedResourceFilenameWithoutLanguage() } finally { - if (txtFile != null) File.Delete(txtFile); + if (txtFile != null) + { + File.Delete(txtFile); + } } } @@ -2673,9 +2925,20 @@ public void StronglyTypedResourceFileIsExistingDirectory() } finally { - if (txtFile != null) File.Delete(txtFile); - if (resourcesFile != null) File.Delete(resourcesFile); - if (dir != null) FileUtilities.DeleteWithoutTrailingBackslash(dir); + if (txtFile != null) + { + File.Delete(txtFile); + } + + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } + + if (dir != null) + { + FileUtilities.DeleteWithoutTrailingBackslash(dir); + } } } @@ -2692,7 +2955,7 @@ public void Regress25163_OutputResourcesContainsInvalidPathCharacters() resourcesFile = Utilities.WriteTestResX(false, null, null); t.Sources = new ITaskItem[] { new TaskItem(resourcesFile) }; - t.OutputResources = new ITaskItem[] { new TaskItem( "||" ) }; + t.OutputResources = new ITaskItem[] { new TaskItem("||") }; bool success = t.Execute(); @@ -2702,7 +2965,10 @@ public void Regress25163_OutputResourcesContainsInvalidPathCharacters() } finally { - if (resourcesFile != null) File.Delete(resourcesFile); + if (resourcesFile != null) + { + File.Delete(resourcesFile); + } } } } @@ -3398,8 +3664,7 @@ public static void AssertLogContainsResource(GenerateResource t, string messageI { Assert.Contains( String.Format(AssemblyResources.GetString(messageID), replacements), - ((MockEngine) t.BuildEngine).Log - ); + ((MockEngine)t.BuildEngine).Log); } /// @@ -3493,9 +3758,13 @@ public static string CreateBasicResourcesFile(bool useResX, ITestOutputHelper ou string sourceFile; if (useResX) + { sourceFile = WriteTestResX(false, null, null); + } else + { sourceFile = WriteTestText(null, null); + } t.Sources = new ITaskItem[] { new TaskItem(sourceFile) }; @@ -3671,18 +3940,18 @@ public static string GetTestResXContent(bool useType, string linkedBitmap, strin + " \xd\xa" + " \xd\xa" + " System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\xd\xa" - + " \xd\xa" - ); + + " \xd\xa"); resgenFileContents.Append( // A plain old string value. " \xd\xa" + " MyValue\xd\xa" - + " \xd\xa" - ); + + " \xd\xa"); if (extraToken != null) + { resgenFileContents.Append(extraToken); + } if (useType) { @@ -3690,8 +3959,7 @@ public static string GetTestResXContent(bool useType, string linkedBitmap, strin resgenFileContents.Append( " \xd\xa" + " Assembly\xd\xa" - + " \xd\xa" - ); + + " \xd\xa"); } if (useInvalidType) @@ -3700,8 +3968,7 @@ public static string GetTestResXContent(bool useType, string linkedBitmap, strin resgenFileContents.Append( " \xd\xa" + " 1\xd\xa" - + " \xd\xa" - ); + + " \xd\xa"); } if (linkedBitmap != null) @@ -3709,8 +3976,7 @@ public static string GetTestResXContent(bool useType, string linkedBitmap, strin // A linked-in bitmap. resgenFileContents.Append( " \xd\xa" - + " " - ); + + " "); // The linked file may have a different case than reported by the filesystem // simulate this by lower-casing our file before writing it into the resx. @@ -3721,8 +3987,7 @@ public static string GetTestResXContent(bool useType, string linkedBitmap, strin resgenFileContents.Append( ";System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\xd\xa" - + " \xd\xa" - ); + + " \xd\xa"); } resgenFileContents.Append("\xd\xa"); @@ -3757,7 +4022,7 @@ public static string WriteTestResX(bool useType, string linkedBitmap, string ext { if (string.IsNullOrEmpty(resgenFile)) { - resgenFile = GetTempFileName(".resx"); + resgenFile = GetTempFileName(".resx"); } File.WriteAllText(resgenFile, contents); @@ -3865,9 +4130,13 @@ public static void STRNamespaceTestHelper(string strLanguage, string resourcesNa string codeFileExtension = null; if (strLanguage == "CSharp") + { codeFileExtension = ".cs"; + } else if (strLanguage == "VB") + { codeFileExtension = ".vb"; + } // Execute task Utilities.ExecuteTask(t); @@ -3918,9 +4187,13 @@ public static void STRNamespaceTestHelper(string strLanguage, string resourcesNa string typeName; if (t.StronglyTypedNamespace != null) + { typeName = t.StronglyTypedNamespace + "."; + } else + { typeName = ""; + } typeName += t.StronglyTypedClassName; // Verify that the type is generated correctly diff --git a/src/Tasks.UnitTests/ResourceHandling/MSBuildResXReader_Tests.cs b/src/Tasks.UnitTests/ResourceHandling/MSBuildResXReader_Tests.cs index ed712777dd1..d1c0b84fdc0 100644 --- a/src/Tasks.UnitTests/ResourceHandling/MSBuildResXReader_Tests.cs +++ b/src/Tasks.UnitTests/ResourceHandling/MSBuildResXReader_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/src/Tasks.UnitTests/ResourceHandling/ResGenDependencies_Tests.cs b/src/Tasks.UnitTests/ResourceHandling/ResGenDependencies_Tests.cs index 1cd7d218fa3..042d17b9e16 100644 --- a/src/Tasks.UnitTests/ResourceHandling/ResGenDependencies_Tests.cs +++ b/src/Tasks.UnitTests/ResourceHandling/ResGenDependencies_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Reflection; @@ -13,7 +13,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class ResGenDependencies_Tests + public sealed class ResGenDependencies_Tests { [Theory] [MemberData(nameof(GenerateResource_Tests.Utilities.UsePreserializedResourceStates), MemberType = typeof(GenerateResource_Tests.Utilities))] diff --git a/src/Tasks.UnitTests/ResourceHandling/ResGen_Tests.cs b/src/Tasks.UnitTests/ResourceHandling/ResGen_Tests.cs index b4ac8290ae1..35138733840 100644 --- a/src/Tasks.UnitTests/ResourceHandling/ResGen_Tests.cs +++ b/src/Tasks.UnitTests/ResourceHandling/ResGen_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -104,15 +104,13 @@ public void OutputFiles() Assert.Equal(differentLengthInput, t.InputFiles); // "New InputFiles value should be set" Assert.Equal(differentLengthOutput, t.OutputFiles); // "New OutputFiles value should be set" - ExecuteTaskAndVerifyLogContainsErrorFromResource - ( + ExecuteTaskAndVerifyLogContainsErrorFromResource( t, "General.TwoVectorsMustHaveSameLength", differentLengthInput.Length, differentLengthOutput.Length, "InputFiles", - "OutputFiles" - ); + "OutputFiles"); // If only OutputFiles is set, then the task should return -- as far as // it's concerned, no work needs to be done. @@ -292,13 +290,11 @@ public void References() int commandLineLength = CommandLine.GetCommandLine(t, false).Length; Assert.Equal(commandLineLength, maxCommandLineLength); - ExecuteTaskAndVerifyLogDoesNotContainResource - ( + ExecuteTaskAndVerifyLogDoesNotContainResource( t, false, "ResGen.CommandTooLong", - CommandLine.GetCommandLine(t, false).Length - ); + CommandLine.GetCommandLine(t, false).Length); VerifyLogDoesNotContainResource((MockEngine)t.BuildEngine, GetPrivateLog(t), "ToolTask.CommandTooLong", typeof(ResGen).Name); @@ -318,12 +314,10 @@ public void References() commandLineLength = CommandLine.GetCommandLine(t, false).Length; Assert.Equal(commandLineLength, maxCommandLineLength + 1); - ExecuteTaskAndVerifyLogContainsErrorFromResource - ( + ExecuteTaskAndVerifyLogContainsErrorFromResource( t, "ResGen.CommandTooLong", - CommandLine.GetCommandLine(t, false).Length - ); + CommandLine.GetCommandLine(t, false).Length); VerifyLogDoesNotContainResource((MockEngine)t.BuildEngine, GetPrivateLog(t), "ToolTask.CommandTooLong", typeof(ResGen).Name); } @@ -580,7 +574,7 @@ private void VerifyLogDoesNotContainResource(MockEngine e, TaskLoggingHelper log /// LogPrivate is a private property. /// /// - static private TaskLoggingHelper GetPrivateLog(ToolTask task) + private static TaskLoggingHelper GetPrivateLog(ToolTask task) { PropertyInfo logPrivateProperty = typeof(ToolTask).GetProperty("LogPrivate", BindingFlags.Instance | BindingFlags.NonPublic); return (TaskLoggingHelper)logPrivateProperty.GetValue(task, null); diff --git a/src/Tasks.UnitTests/ResourceHandling/ResXHelper.cs b/src/Tasks.UnitTests/ResourceHandling/ResXHelper.cs index 67636e61e25..d54509f6b94 100644 --- a/src/Tasks.UnitTests/ResourceHandling/ResXHelper.cs +++ b/src/Tasks.UnitTests/ResourceHandling/ResXHelper.cs @@ -1,11 +1,11 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable namespace Microsoft.Build.Tasks.UnitTests.ResourceHandling { - static class ResXHelper + internal static class ResXHelper { public static string SurroundWithBoilerplate(string input) { diff --git a/src/Tasks.UnitTests/ResourceManagement_Tests.cs b/src/Tasks.UnitTests/ResourceManagement_Tests.cs index d3c607678e1..330331071d2 100644 --- a/src/Tasks.UnitTests/ResourceManagement_Tests.cs +++ b/src/Tasks.UnitTests/ResourceManagement_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; diff --git a/src/Tasks.UnitTests/RoslynCodeTaskFactory_Tests.cs b/src/Tasks.UnitTests/RoslynCodeTaskFactory_Tests.cs index c55eca63dda..91692fb8aa7 100644 --- a/src/Tasks.UnitTests/RoslynCodeTaskFactory_Tests.cs +++ b/src/Tasks.UnitTests/RoslynCodeTaskFactory_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks.UnitTests/SGen_Tests.cs b/src/Tasks.UnitTests/SGen_Tests.cs index 22c5a5ea821..ac7c6847ec5 100644 --- a/src/Tasks.UnitTests/SGen_Tests.cs +++ b/src/Tasks.UnitTests/SGen_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Tasks; @@ -153,8 +153,7 @@ public void TestInputChecks3() // This should result in a quoted parameter... sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk"; string commandLine = sgen.CommandLine(); - } - ); + }); } [Fact] @@ -173,8 +172,7 @@ public void TestInputChecks4() sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk"; string commandLine = sgen.CommandLine(); - } - ); + }); } [Fact] public void TestInputPlatform() @@ -268,12 +266,12 @@ public void TestReferencesCommandLine() sgen.ShouldGenerateSerializer = true; sgen.UseProxyTypes = false; sgen.UseKeep = false; - sgen.References = new string[]{ "C:\\SomeFolder\\reference1.dll", "C:\\SomeFolder\\reference2.dll" }; + sgen.References = new string[] { "C:\\SomeFolder\\reference1.dll", "C:\\SomeFolder\\reference2.dll" }; string commandLine = sgen.CommandLine(); string targetCommandLine = "/assembly:\"" + sgen.BuildAssemblyPath + Path.DirectorySeparatorChar + "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" /reference:\"C:\\SomeFolder\\reference1.dll,C:\\SomeFolder\\reference2.dll\""; - + Assert.Equal(targetCommandLine, commandLine); } #endif diff --git a/src/Tasks.UnitTests/SdkToolsPathUtility_Tests.cs b/src/Tasks.UnitTests/SdkToolsPathUtility_Tests.cs index 454e37ac408..a381e987783 100644 --- a/src/Tasks.UnitTests/SdkToolsPathUtility_Tests.cs +++ b/src/Tasks.UnitTests/SdkToolsPathUtility_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; @@ -12,7 +12,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class SdkToolsPathUtility_Tests + public sealed class SdkToolsPathUtility_Tests { private string _defaultSdkToolsPath = NativeMethodsShared.IsWindows ? "C:\\ProgramFiles\\WIndowsSDK\\bin" : "/ProgramFiles/WindowsSDK/bin"; private TaskLoggingHelper _log = null; diff --git a/src/Tasks.UnitTests/StreamHelpers.cs b/src/Tasks.UnitTests/StreamHelpers.cs index adcafcd19a7..ca3b5410d1a 100644 --- a/src/Tasks.UnitTests/StreamHelpers.cs +++ b/src/Tasks.UnitTests/StreamHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; @@ -7,7 +7,7 @@ namespace Microsoft.Build.UnitTests { - sealed internal class StreamHelpers + internal sealed class StreamHelpers { /* * Method: StringToStream (overload) @@ -15,7 +15,7 @@ sealed internal class StreamHelpers * Take a string and convert it into a Stream. * Use the default encoding which means this machine's ANSI codepage. */ - static internal Stream StringToStream(string value) + internal static Stream StringToStream(string value) { #if FEATURE_ENCODING_DEFAULT return StringToStream(value, System.Text.Encoding.Default); // We want this to be Default which is ANSI @@ -30,7 +30,7 @@ static internal Stream StringToStream(string value) * Take a string and convert it into a Stream. * Takes an alternate encoding type */ - static internal Stream StringToStream(string value, System.Text.Encoding encoding) + internal static Stream StringToStream(string value, System.Text.Encoding encoding) { MemoryStream m = new MemoryStream(); TextWriter w = new StreamWriter(m, encoding); // HIGHCHAR: StringToStream helper accepts encoding from caller. diff --git a/src/Tasks.UnitTests/StreamMappedString_Tests.cs b/src/Tasks.UnitTests/StreamMappedString_Tests.cs index 544c7eed446..8ad8e952a43 100644 --- a/src/Tasks.UnitTests/StreamMappedString_Tests.cs +++ b/src/Tasks.UnitTests/StreamMappedString_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -10,7 +10,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class StreamMappedString_Tests + public sealed class StreamMappedString_Tests { /// /// Test for a string that has ANSI but non-ascii characters. @@ -138,8 +138,7 @@ public void Regress_Mutation_SubstringReadPastEndThrowsException() StreamMappedString s = new StreamMappedString(stream, false); Assert.Equal(String.Empty, s.Substring(1, 30)); - } - ); + }); } [Fact] public void Regress_Mutation_SubstringOnLastPageWorks() @@ -226,8 +225,7 @@ public void Regress_Codereview_RequestPageWellPastEnd() // Read something way past the end. This should result in a range exception. s.GetAt(1000000); - } - ); + }); } [Fact] @@ -239,8 +237,7 @@ public void Regress_Mutation_FirstCharacterOnPagePastEndDoesntExist() StreamMappedString s = new StreamMappedString(stream, false, 256); s.GetAt(256); - } - ); + }); } [Fact] @@ -253,8 +250,7 @@ public void Regress_Mutation_RequestPageWellPastEnd() // Read something way past the end. This should result in a range exception. s.GetAt(1000000); - } - ); + }); } diff --git a/src/Tasks.UnitTests/TelemetryTaskTests.cs b/src/Tasks.UnitTests/TelemetryTaskTests.cs index 49acad1db73..db374f1757d 100644 --- a/src/Tasks.UnitTests/TelemetryTaskTests.cs +++ b/src/Tasks.UnitTests/TelemetryTaskTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.UnitTests; using Xunit; @@ -92,7 +92,7 @@ public void TelemetryTaskDuplicateEventDataProperty() // Should not contain the first value // Assert.DoesNotContain("EE2493A167D24F00996DE7C8E769EAE6", engine.Log); - + // Should contain the second value // Assert.Contains("4ADE3D2622CA400B8B95A039DF540037", engine.Log); diff --git a/src/Tasks.UnitTests/TestResources/TestBinary.cs b/src/Tasks.UnitTests/TestResources/TestBinary.cs index 51a5008f431..411637d381e 100644 --- a/src/Tasks.UnitTests/TestResources/TestBinary.cs +++ b/src/Tasks.UnitTests/TestResources/TestBinary.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks.UnitTests/TlbImp_Tests.cs b/src/Tasks.UnitTests/TlbImp_Tests.cs index 83a624554c6..da394bbb651 100644 --- a/src/Tasks.UnitTests/TlbImp_Tests.cs +++ b/src/Tasks.UnitTests/TlbImp_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -10,7 +10,7 @@ namespace Microsoft.Build.UnitTests.AxTlbImp_Tests { - sealed public class TlbImp_Tests + public sealed class TlbImp_Tests { /// /// Tests that /machine flag will be set. diff --git a/src/Tasks.UnitTests/ToolTaskExtension_Tests.cs b/src/Tasks.UnitTests/ToolTaskExtension_Tests.cs index 569f290286d..17a383f03b9 100644 --- a/src/Tasks.UnitTests/ToolTaskExtension_Tests.cs +++ b/src/Tasks.UnitTests/ToolTaskExtension_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -62,8 +62,7 @@ public void ResourceAccessSanityCheck() t.BuildEngine = engine; t.Log.LogErrorFromResources("Beyond Good and Evil"); - } - ); + }); } /// /// Retrieve a non-existent value but ask for a default. @@ -111,7 +110,7 @@ public void UseNewLineSeparatorseInResponseFile() }; MyToolTaskExtension t = new MyToolTaskExtension(useNewLineSeparators: true, addResponseFileCommands: addResponseFileCommands); - + string[] actual = t.GetResponseFileCommands().Split(MSBuildConstants.EnvironmentNewLine, StringSplitOptions.None); string[] expected = { diff --git a/src/Tasks.UnitTests/Touch_Tests.cs b/src/Tasks.UnitTests/Touch_Tests.cs index 5ebc57b915e..d87d2e5a65d 100644 --- a/src/Tasks.UnitTests/Touch_Tests.cs +++ b/src/Tasks.UnitTests/Touch_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -14,7 +14,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class Touch_Tests + public sealed class Touch_Tests { internal static Microsoft.Build.Shared.FileExists fileExists = new Microsoft.Build.Shared.FileExists(FileExists); internal static Microsoft.Build.Shared.FileCreate fileCreate = new Microsoft.Build.Shared.FileCreate(FileCreate); @@ -30,15 +30,13 @@ sealed public class Touch_Tests private bool Execute(Touch t) { - return t.ExecuteImpl - ( + return t.ExecuteImpl( fileExists, fileCreate, fileGetAttributes, fileSetAttributes, setLastAccessTime, - setLastWriteTime - ); + setLastWriteTime); } /// @@ -203,8 +201,7 @@ public void TouchExisting() Assert.Contains( String.Format(AssemblyResources.GetString("Touch.Touching"), myexisting_txt), - engine.Log - ); + engine.Log); } [Fact] @@ -226,8 +223,7 @@ public void TouchNonExisting() Assert.Contains( String.Format(AssemblyResources.GetString("Touch.FileDoesNotExist"), mynonexisting_txt), - engine.Log - ); + engine.Log); } [Fact] @@ -250,8 +246,7 @@ public void TouchNonExistingAlwaysCreate() Assert.Contains( String.Format(AssemblyResources.GetString("Touch.CreatingFile"), mynonexisting_txt, "AlwaysCreate"), - engine.Log - ); + engine.Log); } [Fact] diff --git a/src/Tasks.UnitTests/Unzip_Tests.cs b/src/Tasks.UnitTests/Unzip_Tests.cs index c954e8d3415..3e74d5ef77c 100644 --- a/src/Tasks.UnitTests/Unzip_Tests.cs +++ b/src/Tasks.UnitTests/Unzip_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -171,7 +171,7 @@ public void LogsErrorIfReadOnlyFileCannotBeOverwitten() unzip.Execute().ShouldBeFalse(() => _mockEngine.Log); - _mockEngine.Log.ShouldContain($"D6DFD219DACE48F8B86EFCDF98433333.txt{ (NativeMethodsShared.IsMono ? "\"" : "'") } is denied", () => _mockEngine.Log); + _mockEngine.Log.ShouldContain($"D6DFD219DACE48F8B86EFCDF98433333.txt{(NativeMethodsShared.IsMono ? "\"" : "'")} is denied", () => _mockEngine.Log); } } @@ -230,14 +230,14 @@ public void CanUnzip_WithIncludeFilter() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Include = "BE78A17D30144B549D21F71D5C633F7D.txt" - }; + { + BuildEngine = _mockEngine, + DestinationFolder = new TaskItem(destination.Path), + OverwriteReadOnlyFiles = true, + SkipUnchangedFiles = false, + SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, + Include = "BE78A17D30144B549D21F71D5C633F7D.txt" + }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); @@ -259,14 +259,14 @@ public void CanUnzip_WithExcludeFilter() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Exclude = "BE78A17D30144B549D21F71D5C633F7D.txt" - }; + { + BuildEngine = _mockEngine, + DestinationFolder = new TaskItem(destination.Path), + OverwriteReadOnlyFiles = true, + SkipUnchangedFiles = false, + SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, + Exclude = "BE78A17D30144B549D21F71D5C633F7D.txt" + }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); @@ -292,15 +292,15 @@ public void CanUnzip_WithIncludeAndExcludeFilter() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Include = "*.js", - Exclude = "*.js.map;sub\\*.js" - }; + { + BuildEngine = _mockEngine, + DestinationFolder = new TaskItem(destination.Path), + OverwriteReadOnlyFiles = true, + SkipUnchangedFiles = false, + SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, + Include = "*.js", + Exclude = "*.js.map;sub\\*.js" + }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); @@ -325,14 +325,14 @@ public void LogsErrorIfIncludeContainsInvalidPathCharacters() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Include = " _mockEngine.Log); @@ -353,14 +353,14 @@ public void LogsErrorIfIncludeContainsPropertyReferences() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Include = "$(Include)" - }; + { + BuildEngine = _mockEngine, + DestinationFolder = new TaskItem(destination.Path), + OverwriteReadOnlyFiles = true, + SkipUnchangedFiles = false, + SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, + Include = "$(Include)" + }; unzip.Execute().ShouldBeFalse(() => _mockEngine.Log); @@ -381,14 +381,14 @@ public void LogsErrorIfExcludeContainsInvalidPathCharacters() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Exclude = " _mockEngine.Log); @@ -409,14 +409,14 @@ public void LogsErrorIfExcludeContainsPropertyReferences() TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip - { - BuildEngine = _mockEngine, - DestinationFolder = new TaskItem(destination.Path), - OverwriteReadOnlyFiles = true, - SkipUnchangedFiles = false, - SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, - Exclude = "$(Include)" - }; + { + BuildEngine = _mockEngine, + DestinationFolder = new TaskItem(destination.Path), + OverwriteReadOnlyFiles = true, + SkipUnchangedFiles = false, + SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, + Exclude = "$(Include)" + }; unzip.Execute().ShouldBeFalse(() => _mockEngine.Log); diff --git a/src/Tasks.UnitTests/VerifyFileHash_Tests.cs b/src/Tasks.UnitTests/VerifyFileHash_Tests.cs index 7000862a422..47ce06858a0 100644 --- a/src/Tasks.UnitTests/VerifyFileHash_Tests.cs +++ b/src/Tasks.UnitTests/VerifyFileHash_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks.UnitTests/VisualBasicParserUtilitites_Tests.cs b/src/Tasks.UnitTests/VisualBasicParserUtilitites_Tests.cs index 8b4f52d62dc..e87890fb8ff 100644 --- a/src/Tasks.UnitTests/VisualBasicParserUtilitites_Tests.cs +++ b/src/Tasks.UnitTests/VisualBasicParserUtilitites_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Xunit; @@ -8,7 +8,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class VisualBasicParserUtilititesTests + public sealed class VisualBasicParserUtilititesTests { // Try just and empty file [Fact] @@ -21,8 +21,7 @@ public void EmptyFile() [Fact] public void SimpleForm() { - AssertParse - ( + AssertParse( @" rem This is my class Public ClAsS Form1 @@ -35,8 +34,7 @@ End Class [Fact] public void Namespace() { - AssertParse - ( + AssertParse( @" ' This is my Namespace NamEspacE Goofy.Mickey @@ -52,8 +50,7 @@ End Namespace [Fact] public void NestedNamespace() { - AssertParse - ( + AssertParse( @" Namespace Goofy Namespace Mickey @@ -66,8 +63,7 @@ Namespace Mickey [Fact] public void NestedAndEndedNamespace() { - AssertParse - ( + AssertParse( @" Namespace Goofy Namespace Mickey @@ -87,8 +83,7 @@ Namespace Mickey [Fact] public void NamespaceElementBeginsWithRem() { - AssertParse -( + AssertParse( @" ' This is my Namespace NamEspacE Artist.Painter.Rembrandt @@ -110,10 +105,8 @@ private static void AssertParse(string source, string expectedClassName) { source = source.Replace("&qt", "\""); - ExtractedClassName className = VisualBasicParserUtilities.GetFirstClassNameFullyQualified - ( - StreamHelpers.StringToStream(source) - ); + ExtractedClassName className = VisualBasicParserUtilities.GetFirstClassNameFullyQualified( + StreamHelpers.StringToStream(source)); Assert.Equal(expectedClassName, className.Name); } diff --git a/src/Tasks.UnitTests/VisualBasicTokenizer_Tests.cs b/src/Tasks.UnitTests/VisualBasicTokenizer_Tests.cs index 61d39ccfee6..31bd707bd57 100644 --- a/src/Tasks.UnitTests/VisualBasicTokenizer_Tests.cs +++ b/src/Tasks.UnitTests/VisualBasicTokenizer_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -10,7 +10,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class VisualBasicTokenizer_Tests + public sealed class VisualBasicTokenizer_Tests { [Fact] public void Empty() { AssertTokenize("", "", "", 0); } @@ -73,11 +73,9 @@ sealed public class VisualBasicTokenizer_Tests [Fact] public void LoneUnderscore() { - AssertTokenize - ( + AssertTokenize( "Sub Foo(ByVal _ As Int16)\xd", - "Keyword(Sub).Identifier(Foo)Separator(()Keyword(ByVal).ExpectedIdentifier(_)" - ); + "Keyword(Sub).Identifier(Foo)Separator(()Keyword(ByVal).ExpectedIdentifier(_)"); } // Boolean literals @@ -166,22 +164,18 @@ public void LoneUnderscore() [Fact] public void CheckAllOperators() { - AssertTokenize - ( + AssertTokenize( "a=1 & 2*3+4-5/6\\7^8<9=10>11\xd", - @"Identifier(a)Operator(=)DecimalIntegerLiteral(1).Operator(&).DecimalIntegerLiteral(2)Operator(*)DecimalIntegerLiteral(3)Operator(+)DecimalIntegerLiteral(4)Operator(-)DecimalIntegerLiteral(5)Operator(/)DecimalIntegerLiteral(6)Operator(\)DecimalIntegerLiteral(7)Operator(^)DecimalIntegerLiteral(8)Operator(<)DecimalIntegerLiteral(9)Operator(=)DecimalIntegerLiteral(10)Operator(>)DecimalIntegerLiteral(11)eol" - ); + @"Identifier(a)Operator(=)DecimalIntegerLiteral(1).Operator(&).DecimalIntegerLiteral(2)Operator(*)DecimalIntegerLiteral(3)Operator(+)DecimalIntegerLiteral(4)Operator(-)DecimalIntegerLiteral(5)Operator(/)DecimalIntegerLiteral(6)Operator(\)DecimalIntegerLiteral(7)Operator(^)DecimalIntegerLiteral(8)Operator(<)DecimalIntegerLiteral(9)Operator(=)DecimalIntegerLiteral(10)Operator(>)DecimalIntegerLiteral(11)eol"); } // Inplace arrays [Fact] public void InplaceArray() { - AssertTokenize - ( + AssertTokenize( "Me.Controls.AddRange(New Control() {Me.lblCodebase, Me.lblCopyright})\xd", - "Keyword(Me)Separator(.)Identifier(Controls)Separator(.)Identifier(AddRange)Separator(()Keyword(New).Identifier(Control)Separator(()Separator()).Separator({)Keyword(Me)Separator(.)Identifier(lblCodebase)Separator(,).Keyword(Me)Separator(.)Identifier(lblCopyright)Separator(})Separator())eol" - ); + "Keyword(Me)Separator(.)Identifier(Controls)Separator(.)Identifier(AddRange)Separator(()Keyword(New).Identifier(Control)Separator(()Separator()).Separator({)Keyword(Me)Separator(.)Identifier(lblCodebase)Separator(,).Keyword(Me)Separator(.)Identifier(lblCopyright)Separator(})Separator())eol"); } // Keywords @@ -192,20 +186,16 @@ public void InplaceArray() [Fact] public void WackyBrackettedClassName() { - AssertTokenize - ( + AssertTokenize( "Public Class [!output SAFE_ITEM_NAME]\xd", - "Keyword(Public).Keyword(Class).ExpectedIdentifier([)" - ); + "Keyword(Public).Keyword(Class).ExpectedIdentifier([)"); } [Fact] public void MyClassIsAKeyword() { - AssertTokenize - ( + AssertTokenize( "Class MyClass\xd", - "Keyword(Class).Keyword(MyClass)eol" - ); + "Keyword(Class).Keyword(MyClass)eol"); } @@ -222,7 +212,7 @@ public void Regress_Mutation_x0dx0aIsASingleLine() * Also, the source must be regenerated exactly when the tokens are concatenated * back together, */ - static private void AssertTokenize(string source, string expectedTokenKey) + private static void AssertTokenize(string source, string expectedTokenKey) { // Most of the time, we expect the rebuilt source to be the same as the input source. AssertTokenize(source, source, expectedTokenKey, 1); @@ -235,19 +225,15 @@ static private void AssertTokenize(string source, string expectedTokenKey) * Also compare the source that is regenerated by concatenating all of the tokens * to 'expectedSource'. */ - static private void AssertTokenize - ( + private static void AssertTokenize( string source, string expectedSource, string expectedTokenKey, - int expectedLastLineNumber - ) + int expectedLastLineNumber) { - VisualBasicTokenizer tokens = new VisualBasicTokenizer - ( + VisualBasicTokenizer tokens = new VisualBasicTokenizer( StreamHelpers.StringToStream(source), - false - ); + false); string results = ""; string tokenKey = ""; int lastLine = 0; diff --git a/src/Tasks.UnitTests/WinMDExp_Tests.cs b/src/Tasks.UnitTests/WinMDExp_Tests.cs index 437c7704471..6382f489296 100644 --- a/src/Tasks.UnitTests/WinMDExp_Tests.cs +++ b/src/Tasks.UnitTests/WinMDExp_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -12,7 +12,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class WinMDExpTests + public sealed class WinMDExpTests { /// /// Tests the "References" parameter on the winmdexp task, and confirms that it sets diff --git a/src/Tasks.UnitTests/WriteCodeFragment_Tests.cs b/src/Tasks.UnitTests/WriteCodeFragment_Tests.cs index b1cf9ff948b..962dd1ec0a4 100644 --- a/src/Tasks.UnitTests/WriteCodeFragment_Tests.cs +++ b/src/Tasks.UnitTests/WriteCodeFragment_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -496,7 +496,7 @@ public void MultilineAttributeCSharp() [Trait("Category", "mono-osx-failing")] public void MultilineAttributeVB() { - var lines = new []{ "line 1", "line 2", "line 3" }; + var lines = new[] { "line 1", "line 2", "line 3" }; var multilineString = String.Join(Environment.NewLine, lines); WriteCodeFragment task = new WriteCodeFragment(); @@ -670,8 +670,7 @@ public void DeclaredTypeForPositionalParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: CLSCompliantAttribute(true)]" - ); + @"[assembly: CLSCompliantAttribute(true)]"); } /// @@ -689,8 +688,7 @@ public void DeclaredTypeForNamedParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: TestAttribute(Int32Argument=42, BoolArgument=false)]" - ); + @"[assembly: TestAttribute(Int32Argument=42, BoolArgument=false)]"); } /// @@ -707,8 +705,7 @@ public void DeclaredTypedWithoutCorrespondingNamedParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: TestAttribute(Int32Argument_TypeName=""System.Int32"", BoolArgument=false)]" - ); + @"[assembly: TestAttribute(Int32Argument_TypeName=""System.Int32"", BoolArgument=false)]"); } /// @@ -723,8 +720,7 @@ public void DeclaredTypeIsUnknown() ExecuteAndVerifyFailure( CreateTask("c#", attribute), - "MSB3715" - ); + "MSB3715"); } /// @@ -739,8 +735,7 @@ public void DeclaredTypeCausesConversionFailure() ExecuteAndVerifyFailure( CreateTask("c#", attribute), - "MSB3716" - ); + "MSB3716"); } /// @@ -755,8 +750,7 @@ public void DeclaredTypeCausesOverflow() ExecuteAndVerifyFailure( CreateTask("c#", attribute), - "MSB3716" - ); + "MSB3716"); } /// @@ -771,8 +765,7 @@ public void DeclaredTypeIsEnum() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: TestAttribute(System.DateTimeKind.Local)]" - ); + @"[assembly: TestAttribute(System.DateTimeKind.Local)]"); } /// @@ -787,8 +780,7 @@ public void DeclaredTypeIsTypeInCSharp() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: TestAttribute(typeof(System.Console))]" - ); + @"[assembly: TestAttribute(typeof(System.Console))]"); } /// @@ -803,8 +795,7 @@ public void DeclaredTypeIsTypeInVB() ExecuteAndVerifySuccess( CreateTask("visualbasic", attribute), - @"" - ); + @""); } /// @@ -820,8 +811,7 @@ public void DeclaredTypeOfArrayIsNotSupported() ExecuteAndVerifyFailure( CreateTask("c#", attribute), - "MSB3716" - ); + "MSB3716"); } /// @@ -837,8 +827,7 @@ public void LiteralPositionalParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: TestAttribute(42 /* A comment */)]" - ); + @"[assembly: TestAttribute(42 /* A comment */)]"); } /// @@ -854,8 +843,7 @@ public void LiteralNamedParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: TestAttribute(TestParameter=42 /* A comment */)]" - ); + @"[assembly: TestAttribute(TestParameter=42 /* A comment */)]"); } /// @@ -870,8 +858,7 @@ public void InferredTypeForPositionalParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: CLSCompliantAttribute(true)]" - ); + @"[assembly: CLSCompliantAttribute(true)]"); } /// @@ -887,8 +874,7 @@ public void InferredTypeForNamedParameter() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute(""MyAssembly"", AllInternalsVisible=true)]" - ); + @"[assembly: System.Runtime.CompilerServices.InternalsVisibleToAttribute(""MyAssembly"", AllInternalsVisible=true)]"); } /// @@ -914,8 +900,7 @@ public void InferredTypePrefersStringWhenMultipleConstructorsAreFound() // all strings should be preferred over all other constructors. ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.Diagnostics.Contracts.ContractOptionAttribute(""a"", ""b"", ""false"")]" - ); + @"[assembly: System.Diagnostics.Contracts.ContractOptionAttribute(""a"", ""b"", ""false"")]"); } /// @@ -940,8 +925,7 @@ public void InferredTypeWithMultipleAttributeConstructorsIsDeterministic() // is alphabetically before any of the other types. ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.Reflection.AssemblyFlagsAttribute(2)]" - ); + @"[assembly: System.Reflection.AssemblyFlagsAttribute(2)]"); // To prove that it's treating the argument as an int, // we can specify an enum value which should fail type @@ -949,8 +933,7 @@ public void InferredTypeWithMultipleAttributeConstructorsIsDeterministic() attribute.SetMetadata("_Parameter1", "PublicKey"); ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.Reflection.AssemblyFlagsAttribute(""PublicKey"")]" - ); + @"[assembly: System.Reflection.AssemblyFlagsAttribute(""PublicKey"")]"); } /// @@ -967,8 +950,7 @@ public void InferredTypeFallsBackToStringWhenTypeCannotBeInferred() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.ComponentModel.TypeConverterAttribute(""false"")]" - ); + @"[assembly: System.ComponentModel.TypeConverterAttribute(""false"")]"); } /// @@ -984,8 +966,7 @@ public void InferredTypeFallsBackToStringWhenTypeConversionFails() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.Diagnostics.DebuggableAttribute(true, ""42"")]" - ); + @"[assembly: System.Diagnostics.DebuggableAttribute(true, ""42"")]"); } /// @@ -1003,8 +984,7 @@ public void UsingInferredDeclaredTypesAndLiteralsInSameAttribute() ExecuteAndVerifySuccess( CreateTask("c#", attribute), - @"[assembly: System.Diagnostics.Contracts.ContractOptionAttribute(""foo"", ""bar"" /* setting */, false)]" - ); + @"[assembly: System.Diagnostics.Contracts.ContractOptionAttribute(""foo"", ""bar"" /* setting */, false)]"); } private WriteCodeFragment CreateTask(string language, params TaskItem[] attributes) diff --git a/src/Tasks.UnitTests/WriteLinesToFile_Tests.cs b/src/Tasks.UnitTests/WriteLinesToFile_Tests.cs index 1d2e9bdd942..fa30f5f0f26 100644 --- a/src/Tasks.UnitTests/WriteLinesToFile_Tests.cs +++ b/src/Tasks.UnitTests/WriteLinesToFile_Tests.cs @@ -1,4 +1,7 @@ -using System; +// 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.IO; using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Tasks.UnitTests/XamlDataDrivenToolTask_Tests.cs b/src/Tasks.UnitTests/XamlDataDrivenToolTask_Tests.cs index 80b0140226a..c8f2f37161a 100644 --- a/src/Tasks.UnitTests/XamlDataDrivenToolTask_Tests.cs +++ b/src/Tasks.UnitTests/XamlDataDrivenToolTask_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -187,8 +187,7 @@ public void TestComplexIntegerLessThanMin() { object fakeTaskInstance = CreateFakeTask(); XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 2); - } - ); + }); } [Fact] @@ -201,8 +200,7 @@ public void TestComplexIntegerGreaterThanMax() XamlTestHelpers.SetProperty(fakeTaskInstance, "ComplexInteger", 256); string expectedResult = "/always /Ci256 /Cr:CT"; CheckCommandLine(expectedResult, XamlTestHelpers.GenerateCommandLine(fakeTaskInstance)); - } - ); + }); } [Fact] [Trait("Category", "mono-osx-failing")] @@ -295,7 +293,10 @@ public void CommandLineErrorsReportFullCommandlineAmpersandTemp() { Environment.SetEnvironmentVariable("TMP", oldTmp); ObjectModelHelpers.DeleteDirectory(newTmp); - if (Directory.Exists(newTmp)) FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + if (Directory.Exists(newTmp)) + { + FileUtilities.DeleteWithoutTrailingBackslash(newTmp); + } } } diff --git a/src/Tasks.UnitTests/XamlTaskFactory_Tests.cs b/src/Tasks.UnitTests/XamlTaskFactory_Tests.cs index 050975f0c98..a2ae014d062 100644 --- a/src/Tasks.UnitTests/XamlTaskFactory_Tests.cs +++ b/src/Tasks.UnitTests/XamlTaskFactory_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks.UnitTests/XamlTestHelpers.cs b/src/Tasks.UnitTests/XamlTestHelpers.cs index c5174dd8d6d..3fd447fbe62 100644 --- a/src/Tasks.UnitTests/XamlTestHelpers.cs +++ b/src/Tasks.UnitTests/XamlTestHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.CSharp; using Microsoft.Build.Tasks.Xaml; diff --git a/src/Tasks.UnitTests/XmlPeek_Tests.cs b/src/Tasks.UnitTests/XmlPeek_Tests.cs index 6bb0e046a8f..d7c5e18531d 100644 --- a/src/Tasks.UnitTests/XmlPeek_Tests.cs +++ b/src/Tasks.UnitTests/XmlPeek_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; @@ -11,7 +11,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class XmlPeek_Tests + public sealed class XmlPeek_Tests { private string _xmlFileWithNs = @" diff --git a/src/Tasks.UnitTests/XmlPoke_Tests.cs b/src/Tasks.UnitTests/XmlPoke_Tests.cs index 88caa456fad..fba347fb692 100644 --- a/src/Tasks.UnitTests/XmlPoke_Tests.cs +++ b/src/Tasks.UnitTests/XmlPoke_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -15,7 +15,7 @@ namespace Microsoft.Build.UnitTests { - sealed public class XmlPoke_Tests + public sealed class XmlPoke_Tests { private const string XmlNamespaceUsedByTests = "http://nsurl"; diff --git a/src/Tasks.UnitTests/XslTransformation_Tests.cs b/src/Tasks.UnitTests/XslTransformation_Tests.cs index 8241951081a..bb4697a60ce 100644 --- a/src/Tasks.UnitTests/XslTransformation_Tests.cs +++ b/src/Tasks.UnitTests/XslTransformation_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Tasks; using Microsoft.Build.Utilities; @@ -45,7 +45,7 @@ namespace Microsoft.Build.UnitTests /// 20. XslDocument that throws runtime exception. /// 21. Passing a dll that has two types to XsltCompiledDll parameter without specifying a type. /// - sealed public class XslTransformation_Tests + public sealed class XslTransformation_Tests { /// /// The "surround" regex. @@ -629,8 +629,7 @@ public void MissingOutputFile() } CleanUp(dir); - } - ); + }); } /// /// Missing XmlFile file. @@ -872,7 +871,7 @@ public void XsltPreserveWhitespace() // load transformed xsl and assert it is well formatted { XslTransformation t = new XslTransformation(); - + t.BuildEngine = engine; t.XslInputPath = xslPath; t.XmlInputPaths = xmlPaths; diff --git a/src/Tasks.UnitTests/ZipDirectory_Tests.cs b/src/Tasks.UnitTests/ZipDirectory_Tests.cs index 31b4d547332..931229c1a29 100644 --- a/src/Tasks.UnitTests/ZipDirectory_Tests.cs +++ b/src/Tasks.UnitTests/ZipDirectory_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; diff --git a/src/Tasks/Al.cs b/src/Tasks/Al.cs index 9ff2c53b1a6..7d9ad8fa1a8 100644 --- a/src/Tasks/Al.cs +++ b/src/Tasks/Al.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -309,7 +309,7 @@ protected override string GenerateFullPathToTool() { // The bitness of al.exe should match the platform being built // Yoda condition prevents null reference exception if Platform is null. - string archToLookFor = "x86".Equals(Platform, StringComparison.OrdinalIgnoreCase) ? Platform : + string archToLookFor = "x86".Equals(Platform, StringComparison.OrdinalIgnoreCase) ? Platform : "x64".Equals(Platform, StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.AMD64 : // x64 maps to AMD64 in GeneratePathToTool ProcessorArchitecture.CurrentProcessArchitecture; @@ -353,19 +353,15 @@ protected internal override void AddResponseFileCommands(CommandLineBuilderExten commandLine.AppendSwitchIfNotNull("", SourceModules, new[] { "TargetFile" }); - commandLine.AppendSwitchIfNotNull - ( + commandLine.AppendSwitchIfNotNull( "/embed:", EmbedResources, - new[] { "LogicalName", "Access" } - ); + new[] { "LogicalName", "Access" }); - commandLine.AppendSwitchIfNotNull - ( + commandLine.AppendSwitchIfNotNull( "/link:", LinkResources, - new[] { "LogicalName", "TargetFile", "Access" } - ); + new[] { "LogicalName", "TargetFile", "Access" }); // It's a good idea for the response file to be the very last switch passed, just // from a predictability perspective. This is also consistent with the compiler diff --git a/src/Tasks/AppConfig/AppConfig.cs b/src/Tasks/AppConfig/AppConfig.cs index 3fed4aab5cd..018a2ee5932 100644 --- a/src/Tasks/AppConfig/AppConfig.cs +++ b/src/Tasks/AppConfig/AppConfig.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Tasks/AppConfig/AppConfigException.cs b/src/Tasks/AppConfig/AppConfigException.cs index c58ee3011ed..82caefb8fc0 100644 --- a/src/Tasks/AppConfig/AppConfigException.cs +++ b/src/Tasks/AppConfig/AppConfigException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/AppConfig/BindingRedirect.cs b/src/Tasks/AppConfig/BindingRedirect.cs index 9788fdf513f..8be7d2413c7 100644 --- a/src/Tasks/AppConfig/BindingRedirect.cs +++ b/src/Tasks/AppConfig/BindingRedirect.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; diff --git a/src/Tasks/AppConfig/DependentAssembly.cs b/src/Tasks/AppConfig/DependentAssembly.cs index 07a58ffc375..f1e0bd4e4a9 100644 --- a/src/Tasks/AppConfig/DependentAssembly.cs +++ b/src/Tasks/AppConfig/DependentAssembly.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -82,14 +82,12 @@ internal void Read(XmlReader reader) } } - string assemblyName = String.Format - ( + string assemblyName = String.Format( CultureInfo.InvariantCulture, "{0}, Version=0.0.0.0, Culture={1}, PublicKeyToken={2}", name, culture, - publicKeyToken - ); + publicKeyToken); try { diff --git a/src/Tasks/AppConfig/RuntimeSection.cs b/src/Tasks/AppConfig/RuntimeSection.cs index 1ce5dda8ada..8867f62dfb8 100644 --- a/src/Tasks/AppConfig/RuntimeSection.cs +++ b/src/Tasks/AppConfig/RuntimeSection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Collections.Generic; diff --git a/src/Tasks/AppDomainIsolatedTaskExtension.cs b/src/Tasks/AppDomainIsolatedTaskExtension.cs index 94382a8b002..3ac6be4f21a 100644 --- a/src/Tasks/AppDomainIsolatedTaskExtension.cs +++ b/src/Tasks/AppDomainIsolatedTaskExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_APPDOMAIN diff --git a/src/Tasks/AspNetCompiler.cs b/src/Tasks/AspNetCompiler.cs index 855bd8b7790..1e1d3b4b2be 100644 --- a/src/Tasks/AspNetCompiler.cs +++ b/src/Tasks/AspNetCompiler.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; diff --git a/src/Tasks/AssemblyDependency/AssemblyFoldersExResolver.cs b/src/Tasks/AssemblyDependency/AssemblyFoldersExResolver.cs index af687d163b0..7aabd28ea93 100644 --- a/src/Tasks/AssemblyDependency/AssemblyFoldersExResolver.cs +++ b/src/Tasks/AssemblyDependency/AssemblyFoldersExResolver.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #if FEATURE_WIN32_REGISTRY using System; @@ -25,13 +26,10 @@ internal class AssemblyFoldersExResolver : Resolver /// Regex for breaking up the searchpath pieces. /// private static readonly Lazy s_crackAssemblyFoldersExSentinel = new Lazy( - () => new Regex - ( + () => new Regex( AssemblyResolutionConstants.assemblyFoldersExSentinel + "(?[^,]*),(?[^,]*),(?[^,]*)([,]*)(?.*)}", - RegexOptions.IgnoreCase | RegexOptions.Compiled - ) - ); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); /// /// Delegate. @@ -200,8 +198,7 @@ private void LazyInitialize() /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -212,8 +209,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigCache.cs b/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigCache.cs index 1cc90184eac..1453e8ab6d8 100644 --- a/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigCache.cs +++ b/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigCache.cs @@ -1,3 +1,6 @@ +// 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.Collections.Immutable; using System.IO; diff --git a/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigResolver.cs b/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigResolver.cs index a5a8fe5a9f8..87fc5b6d16c 100644 --- a/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigResolver.cs +++ b/src/Tasks/AssemblyDependency/AssemblyFoldersFromConfig/AssemblyFoldersFromConfigResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -24,13 +24,10 @@ internal class AssemblyFoldersFromConfigResolver : Resolver /// Regex for breaking up the search path pieces. /// private static readonly Lazy s_crackAssemblyFoldersFromConfigSentinel = new Lazy( - () => new Regex - ( + () => new Regex( AssemblyResolutionConstants.assemblyFoldersFromConfigSentinel + "(?[^,]*),(?[^,]*)}", - RegexOptions.IgnoreCase | RegexOptions.Compiled - ) - ); + RegexOptions.IgnoreCase | RegexOptions.Compiled)); /// /// Whether or not the search path could be cracked. @@ -93,7 +90,9 @@ public AssemblyFoldersFromConfigResolver(string searchPathElement, GetAssemblyNa private void LazyInitialize() { if (_isInitialized) + { return; + } _isInitialized = true; @@ -118,7 +117,7 @@ private void LazyInitialize() bool useCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEASSEMBLYFOLDERSEXCACHE") == null; string key = "6f7de854-47fe-4ae2-9cfe-9b33682abd91" + searchPathElement; - + if (useCache && _buildEngine != null) { _assemblyFoldersCache = _buildEngine.GetRegisteredTaskObject(key, RegisteredTaskObjectLifetime.Build) as AssemblyFoldersFromConfigCache; @@ -167,8 +166,7 @@ private void LazyInitialize() /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -179,8 +177,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; @@ -212,7 +209,7 @@ out bool userRequestedSpecificFile foundPath = candidatePath; return true; } - + // Lets see if the processor architecture matches, note this this method will cache the result when it was first called. AssemblyNameExtension foundAssembly = getAssemblyName(candidatePath); diff --git a/src/Tasks/AssemblyDependency/AssemblyFoldersResolver.cs b/src/Tasks/AssemblyDependency/AssemblyFoldersResolver.cs index 53f7f0cfcd5..998e8abf552 100644 --- a/src/Tasks/AssemblyDependency/AssemblyFoldersResolver.cs +++ b/src/Tasks/AssemblyDependency/AssemblyFoldersResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -42,8 +42,7 @@ public AssemblyFoldersResolver(string searchPathElement, GetAssemblyName getAsse /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -55,8 +54,7 @@ public override bool Resolve List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/AssemblyDependency/AssemblyInformation.cs b/src/Tasks/AssemblyDependency/AssemblyInformation.cs index 5e5f39a1656..a77c9b03360 100644 --- a/src/Tasks/AssemblyDependency/AssemblyInformation.cs +++ b/src/Tasks/AssemblyDependency/AssemblyInformation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -201,14 +201,12 @@ public FrameworkName FrameworkNameAttribute /// Receives the list of dependencies. /// Receives the list of associated scatter files. /// Gets the assembly name. - internal static void GetAssemblyMetadata - ( + internal static void GetAssemblyMetadata( string path, ConcurrentDictionary assemblyMetadataCache, out AssemblyNameExtension[] dependencies, out string[] scatterFiles, - out FrameworkName frameworkName - ) + out FrameworkName frameworkName) { var import = assemblyMetadataCache?.GetOrAdd(path, p => new AssemblyMetadata(p)) ?? new AssemblyMetadata(path); @@ -274,10 +272,10 @@ internal static bool IsWinMDFile( /// private FrameworkName GetFrameworkName() { -// Disabling use of System.Reflection in case of MONO, because -// Assembly.GetCustomAttributes* for an attribute which belongs -// to an assembly that mono cannot find, causes a crash! -// Instead, opt for using PEReader and friends to get that info + // Disabling use of System.Reflection in case of MONO, because + // Assembly.GetCustomAttributes* for an attribute which belongs + // to an assembly that mono cannot find, causes a crash! + // Instead, opt for using PEReader and friends to get that info #if !FEATURE_ASSEMBLYLOADCONTEXT && !MONO if (!NativeMethodsShared.IsWindows) { @@ -352,11 +350,17 @@ private FrameworkName GetFrameworkName() /// private void CorePopulateMetadata() { - if (_metadataRead) return; + if (_metadataRead) + { + return; + } lock (this) { - if (_metadataRead) return; + if (_metadataRead) + { + return; + } using (var stream = File.OpenRead(_sourceFile)) using (var peFile = new PEReader(stream)) @@ -404,13 +408,13 @@ private void CorePopulateMetadata() continue; } - var container = metadataReader.GetMemberReference((MemberReferenceHandle) ctorHandle).Parent; + var container = metadataReader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent; if (container.Kind != HandleKind.TypeReference) { continue; } - var name = metadataReader.GetTypeReference((TypeReferenceHandle) container).Name; + var name = metadataReader.GetTypeReference((TypeReferenceHandle)container).Name; if (!string.Equals(metadataReader.GetString(name), "TargetFrameworkAttribute")) { continue; @@ -476,8 +480,8 @@ private static AssemblyName GetAssemblyName(MetadataReader metadataReader, Assem } #endif -// Enabling this for MONO, because it's required by GetFrameworkName. -// More details are in the comment for that method + // Enabling this for MONO, because it's required by GetFrameworkName. + // More details are in the comment for that method #if FEATURE_ASSEMBLYLOADCONTEXT || MONO // This method copied from DNX source: https://github.com/aspnet/dnx/blob/e0726f769aead073af2d8cd9db47b89e1745d574/src/Microsoft.Dnx.Tooling/Utils/LockFileUtils.cs#L385 // System.Reflection.Metadata 1.1 is expected to have an API that helps with this. @@ -598,14 +602,14 @@ internal static string GetRuntimeVersion(string path) } return hresult == NativeMethodsShared.S_OK ? new string(runtimeVersion, 0, dwLength - 1) : string.Empty; - } + } } else { return ManagedRuntimeVersionReader.GetRuntimeVersion(path); } #else - return ManagedRuntimeVersionReader.GetRuntimeVersion(path); + return ManagedRuntimeVersionReader.GetRuntimeVersion(path); #endif } @@ -1093,7 +1097,9 @@ private static uint RvaToOffset(HeaderInfo[] sections, uint rva) foreach (var s in sections) { if (rva >= s.VirtualAddress && rva < s.VirtualAddress + s.Size) + { return s.FileOffset + (rva - s.VirtualAddress); + } } return 0; } diff --git a/src/Tasks/AssemblyDependency/AssemblyMetadata.cs b/src/Tasks/AssemblyDependency/AssemblyMetadata.cs index 7144c1d80d9..19bc5b4779c 100644 --- a/src/Tasks/AssemblyDependency/AssemblyMetadata.cs +++ b/src/Tasks/AssemblyDependency/AssemblyMetadata.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.Versioning; using Microsoft.Build.Shared; @@ -15,7 +15,7 @@ namespace Microsoft.Build.Tasks.AssemblyDependency /// After initial construction, this object is readonly and data-only, /// allowing it to be safely cached. /// - class AssemblyMetadata + internal class AssemblyMetadata { public readonly AssemblyNameExtension[] Dependencies; public readonly FrameworkName FrameworkName; diff --git a/src/Tasks/AssemblyDependency/AssemblyNameReference.cs b/src/Tasks/AssemblyDependency/AssemblyNameReference.cs index bbb0004ecd3..91f87bd654e 100644 --- a/src/Tasks/AssemblyDependency/AssemblyNameReference.cs +++ b/src/Tasks/AssemblyDependency/AssemblyNameReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; diff --git a/src/Tasks/AssemblyDependency/AssemblyNameReferenceAscendingVersionComparer.cs b/src/Tasks/AssemblyDependency/AssemblyNameReferenceAscendingVersionComparer.cs index fd6fe842ce8..d1537bd9ffe 100644 --- a/src/Tasks/AssemblyDependency/AssemblyNameReferenceAscendingVersionComparer.cs +++ b/src/Tasks/AssemblyDependency/AssemblyNameReferenceAscendingVersionComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/AssemblyDependency/AssemblyResolution.cs b/src/Tasks/AssemblyDependency/AssemblyResolution.cs index 178c57101a5..d3064f2b7ff 100644 --- a/src/Tasks/AssemblyDependency/AssemblyResolution.cs +++ b/src/Tasks/AssemblyDependency/AssemblyResolution.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -42,8 +42,7 @@ internal static class AssemblyResolution /// Receives the searchPath that the reference was resolved at. Empty if not resolved. /// This will be true if the user requested a specific file. /// The resolved path - internal static string ResolveReference - ( + internal static string ResolveReference( IEnumerable jaggedResolvers, AssemblyNameExtension assemblyName, string sdkName, @@ -55,8 +54,7 @@ internal static string ResolveReference string assemblyFolderKey, List assembliesConsideredAndRejected, out string resolvedSearchPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { // Initialize outs. userRequestedSpecificFile = false; @@ -76,8 +74,7 @@ out bool userRequestedSpecificFile { if ( - resolver.Resolve - ( + resolver.Resolve( assemblyName, sdkName, rawFileNameCandidate, @@ -88,9 +85,7 @@ out bool userRequestedSpecificFile assemblyFolderKey, assembliesConsideredAndRejected, out string fileLocation, - out userRequestedSpecificFile - ) - ) + out userRequestedSpecificFile)) { resolvedSearchPath = resolver.SearchPath; return fileLocation; @@ -139,8 +134,7 @@ out userRequestedSpecificFile /// /// #endif - public static Resolver[] CompileSearchPaths - ( + public static Resolver[] CompileSearchPaths( IBuildEngine buildEngine, string[] searchPaths, string[] candidateAssemblyFiles, @@ -157,8 +151,7 @@ public static Resolver[] CompileSearchPaths GetAssemblyRuntimeVersion getRuntimeVersion, Version targetedRuntimeVersion, GetAssemblyPathInGac getAssemblyPathInGac, - TaskLoggingHelper log - ) + TaskLoggingHelper log) { var resolvers = new Resolver[searchPaths.Length]; @@ -216,14 +209,12 @@ TaskLoggingHelper log /// /// Build a resolver array from a set of directories to resolve directly from. /// - internal static Resolver[] CompileDirectories - ( + internal static Resolver[] CompileDirectories( List directories, FileExists fileExists, GetAssemblyName getAssemblyName, GetAssemblyRuntimeVersion getRuntimeVersion, - Version targetedRuntimeVersion - ) + Version targetedRuntimeVersion) { var resolvers = new Resolver[directories.Count]; for (int i = 0; i < directories.Count; i++) diff --git a/src/Tasks/AssemblyDependency/AssemblyResolutionConstants.cs b/src/Tasks/AssemblyDependency/AssemblyResolutionConstants.cs index 2f38c3b83f6..08b6e6f6df5 100644 --- a/src/Tasks/AssemblyDependency/AssemblyResolutionConstants.cs +++ b/src/Tasks/AssemblyDependency/AssemblyResolutionConstants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/AssemblyDependency/BadImageReferenceException.cs b/src/Tasks/AssemblyDependency/BadImageReferenceException.cs index ded433fe021..8a9cadcc29a 100644 --- a/src/Tasks/AssemblyDependency/BadImageReferenceException.cs +++ b/src/Tasks/AssemblyDependency/BadImageReferenceException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/AssemblyDependency/CandidateAssemblyFilesResolver.cs b/src/Tasks/AssemblyDependency/CandidateAssemblyFilesResolver.cs index 35c170ed419..77695308943 100644 --- a/src/Tasks/AssemblyDependency/CandidateAssemblyFilesResolver.cs +++ b/src/Tasks/AssemblyDependency/CandidateAssemblyFilesResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -51,8 +51,7 @@ public CandidateAssemblyFilesResolver(string[] candidateAssemblyFiles, string se /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -63,8 +62,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/AssemblyDependency/ConflictLossReason.cs b/src/Tasks/AssemblyDependency/ConflictLossReason.cs index 4ef779f4554..b54e87f56de 100644 --- a/src/Tasks/AssemblyDependency/ConflictLossReason.cs +++ b/src/Tasks/AssemblyDependency/ConflictLossReason.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/AssemblyDependency/CopyLocalState.cs b/src/Tasks/AssemblyDependency/CopyLocalState.cs index e1768f2bd0d..1a4670806eb 100644 --- a/src/Tasks/AssemblyDependency/CopyLocalState.cs +++ b/src/Tasks/AssemblyDependency/CopyLocalState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; diff --git a/src/Tasks/AssemblyDependency/DependencyResolutionException.cs b/src/Tasks/AssemblyDependency/DependencyResolutionException.cs index 1266dceb45f..402e4999988 100644 --- a/src/Tasks/AssemblyDependency/DependencyResolutionException.cs +++ b/src/Tasks/AssemblyDependency/DependencyResolutionException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/AssemblyDependency/DirectoryResolver.cs b/src/Tasks/AssemblyDependency/DirectoryResolver.cs index ccfcde1e11b..be0fe39554d 100644 --- a/src/Tasks/AssemblyDependency/DirectoryResolver.cs +++ b/src/Tasks/AssemblyDependency/DirectoryResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -37,8 +37,7 @@ public DirectoryResolver(string searchPathElement, GetAssemblyName getAssemblyNa /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -49,8 +48,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; @@ -62,7 +60,7 @@ out bool userRequestedSpecificFile foundPath = resolvedPath; return true; } - + return false; } } diff --git a/src/Tasks/AssemblyDependency/DisposableBase.cs b/src/Tasks/AssemblyDependency/DisposableBase.cs index 1cdac14aec1..264ebe75d59 100644 --- a/src/Tasks/AssemblyDependency/DisposableBase.cs +++ b/src/Tasks/AssemblyDependency/DisposableBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/AssemblyDependency/FrameworkPathResolver.cs b/src/Tasks/AssemblyDependency/FrameworkPathResolver.cs index 6312220d3f2..d51805918d3 100644 --- a/src/Tasks/AssemblyDependency/FrameworkPathResolver.cs +++ b/src/Tasks/AssemblyDependency/FrameworkPathResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -45,8 +45,7 @@ public FrameworkPathResolver(string[] frameworkPaths, InstalledAssemblies instal /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -57,8 +56,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/AssemblyDependency/GacResolver.cs b/src/Tasks/AssemblyDependency/GacResolver.cs index 40b3c26eadc..ac47511c1dc 100644 --- a/src/Tasks/AssemblyDependency/GacResolver.cs +++ b/src/Tasks/AssemblyDependency/GacResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -50,8 +50,7 @@ public GacResolver(System.Reflection.ProcessorArchitecture targetProcessorArchit /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -62,8 +61,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/AssemblyDependency/GenerateBindingRedirects.cs b/src/Tasks/AssemblyDependency/GenerateBindingRedirects.cs index 41007129e72..aaf3cadfe52 100644 --- a/src/Tasks/AssemblyDependency/GenerateBindingRedirects.cs +++ b/src/Tasks/AssemblyDependency/GenerateBindingRedirects.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -115,7 +115,7 @@ public override bool Execute() writeOutput = false; } } - catch(System.Xml.XmlException) + catch (System.Xml.XmlException) { writeOutput = true; } diff --git a/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs b/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs index afeaeb68a3e..66f9de8bfe1 100644 --- a/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs +++ b/src/Tasks/AssemblyDependency/GlobalAssemblyCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -188,11 +188,14 @@ internal static string RetrievePathFromFusionName(string strongName) ErrorUtilities.VerifyThrow(hr == NativeMethodsShared.S_OK, "CreateAssemblyCache failed, hr {0}", hr); - var assemblyInfo = new ASSEMBLY_INFO { cbAssemblyInfo = (uint) Marshal.SizeOf() }; + var assemblyInfo = new ASSEMBLY_INFO { cbAssemblyInfo = (uint)Marshal.SizeOf() }; assemblyCache.QueryAssemblyInfo(0, strongName, ref assemblyInfo); - if (assemblyInfo.cbAssemblyInfo == 0) return null; + if (assemblyInfo.cbAssemblyInfo == 0) + { + return null; + } assemblyInfo.pszCurrentAssemblyPathBuf = new string(new char[assemblyInfo.cchBuf]); @@ -236,8 +239,7 @@ private static string CheckForFullFusionNameInGac(AssemblyNameExtension assembly /// Delegate to get the enumerator which will enumerate over the GAC. /// Whether to check for a specific version. /// The path to the assembly. Empty if none exists. - internal static string GetLocation - ( + internal static string GetLocation( AssemblyNameExtension strongName, ProcessorArchitecture targetProcessorArchitecture, GetAssemblyRuntimeVersion getRuntimeVersion, @@ -246,8 +248,7 @@ internal static string GetLocation FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, - bool specificVersion - ) + bool specificVersion) { return GetLocation(null, strongName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fullFusionName, fileExists, getPathFromFusionName, getGacEnumerator, specificVersion); } @@ -266,8 +267,7 @@ bool specificVersion /// Delegate to get the enumerator which will enumerate over the GAC. /// Whether to check for a specific version. /// The path to the assembly. Empty if none exists. - internal static string GetLocation - ( + internal static string GetLocation( IBuildEngine4 buildEngine, AssemblyNameExtension strongName, ProcessorArchitecture targetProcessorArchitecture, @@ -277,8 +277,7 @@ internal static string GetLocation FileExists fileExists, GetPathFromFusionName getPathFromFusionName, GetGacEnumerator getGacEnumerator, - bool specificVersion - ) + bool specificVersion) { ConcurrentDictionary fusionNameToResolvedPath = null; bool useGacRarCache = Environment.GetEnvironmentVariable("MSBUILDDISABLEGACRARCACHE") == null; diff --git a/src/Tasks/AssemblyDependency/HintPathResolver.cs b/src/Tasks/AssemblyDependency/HintPathResolver.cs index 381e7d3d60e..1ae57169ce7 100644 --- a/src/Tasks/AssemblyDependency/HintPathResolver.cs +++ b/src/Tasks/AssemblyDependency/HintPathResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -38,8 +38,7 @@ public HintPathResolver(string searchPathElement, GetAssemblyName getAssemblyNam /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -50,8 +49,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { // If there is newline or white space `FileUtilities.NormalizePath` will get garbage result(throw on fullframework). // Adding FileUtilities.NormalizePath (https://github.com/dotnet/msbuild/pull/4414) caused https://github.com/dotnet/msbuild/issues/4593 diff --git a/src/Tasks/AssemblyDependency/InstalledAssemblies.cs b/src/Tasks/AssemblyDependency/InstalledAssemblies.cs index cf35873ca38..0ab3a0a47f3 100644 --- a/src/Tasks/AssemblyDependency/InstalledAssemblies.cs +++ b/src/Tasks/AssemblyDependency/InstalledAssemblies.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -33,14 +33,12 @@ internal InstalledAssemblies(RedistList redistList) /// Whether this assembly will be available on target machines. /// May be true, false or null. Null means there was no IsRedistRoot in the redist list. /// Name of the corresponding Resist specified in the redist list. - internal void GetInfo - ( + internal void GetInfo( AssemblyNameExtension assemblyName, out Version unifiedVersion, out bool isPrerequisite, out bool? isRedistRoot, - out string redistName - ) + out string redistName) { unifiedVersion = assemblyName.Version; isPrerequisite = false; diff --git a/src/Tasks/AssemblyDependency/InvalidReferenceAssemblyNameException.cs b/src/Tasks/AssemblyDependency/InvalidReferenceAssemblyNameException.cs index 297d8b6a386..42838f8dc21 100644 --- a/src/Tasks/AssemblyDependency/InvalidReferenceAssemblyNameException.cs +++ b/src/Tasks/AssemblyDependency/InvalidReferenceAssemblyNameException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/AssemblyDependency/NoMatchReason.cs b/src/Tasks/AssemblyDependency/NoMatchReason.cs index cf31797ebba..3ac36b9b12e 100644 --- a/src/Tasks/AssemblyDependency/NoMatchReason.cs +++ b/src/Tasks/AssemblyDependency/NoMatchReason.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/AssemblyDependency/RawFilenameResolver.cs b/src/Tasks/AssemblyDependency/RawFilenameResolver.cs index 8b7a26432e2..5273445e3f8 100644 --- a/src/Tasks/AssemblyDependency/RawFilenameResolver.cs +++ b/src/Tasks/AssemblyDependency/RawFilenameResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -38,8 +38,7 @@ public RawFilenameResolver(string searchPathElement, GetAssemblyName getAssembly /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -50,8 +49,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/AssemblyDependency/Reference.cs b/src/Tasks/AssemblyDependency/Reference.cs index 9ad4a1f1bdb..8718bb29c40 100644 --- a/src/Tasks/AssemblyDependency/Reference.cs +++ b/src/Tasks/AssemblyDependency/Reference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -17,7 +17,7 @@ namespace Microsoft.Build.Tasks /// /// A reference to an assembly along with information about resolution. /// - sealed internal class Reference + internal sealed class Reference { /// /// dictionary where ITaskItem.ItemSpec (a string) is the key and ITaskItem is the value. @@ -421,7 +421,7 @@ internal List GetErrors() internal void AddRelatedFileExtension(string filenameExtension) { #if DEBUG - Debug.Assert(filenameExtension[0]=='.', "Expected extension to start with '.'"); + Debug.Assert(filenameExtension[0] == '.', "Expected extension to start with '.'"); #endif _relatedFileExtensions.Add(filenameExtension); } @@ -877,12 +877,10 @@ internal void MakeDependentAssemblyReference(Reference sourceReference) /// The source item. /// Whether the version needs to match exactly or loosely. /// The filename extension that the resulting assembly must have. - internal void MakePrimaryAssemblyReference - ( + internal void MakePrimaryAssemblyReference( ITaskItem sourceItem, bool wantSpecificVersionValue, - string executableExtension - ) + string executableExtension) { CopyLocal = CopyLocalState.Undecided; @@ -926,14 +924,11 @@ internal static bool IsFrameworkFile(string fullPath, string[] frameworkPaths) { if ( - String.Compare - ( + String.Compare( frameworkPath, 0, fullPath, 0, frameworkPath.Length, - StringComparison.OrdinalIgnoreCase - ) == 0 - ) + StringComparison.OrdinalIgnoreCase) == 0) { return true; } @@ -955,8 +950,7 @@ internal static bool IsFrameworkFile(string fullPath, string[] frameworkPaths) /// if set to true, copy local dependencies when only parent reference in gac. /// If set to true, do not copy local a reference that exists in the GAC (legacy behavior). /// The reference table. - internal void SetFinalCopyLocalState - ( + internal void SetFinalCopyLocalState( AssemblyNameExtension assemblyName, string[] frameworkPaths, ProcessorArchitecture targetProcessorArchitecture, @@ -966,8 +960,7 @@ internal void SetFinalCopyLocalState GetAssemblyPathInGac getAssemblyPathInGac, bool copyLocalDependenciesWhenParentReferenceInGac, bool doNotCopyLocalIfInGac, - ReferenceTable referenceTable - ) + ReferenceTable referenceTable) { if (IsBadImage) { @@ -999,12 +992,10 @@ ReferenceTable referenceTable if (IsPrimary) { bool found; - bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool - ( + bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool( PrimarySourceItem, ItemMetadataNames.privateMetadata, - out found - ); + out found); if (found) { @@ -1023,12 +1014,10 @@ out found foreach (ITaskItem item in _sourceItems.Values) { bool found; - bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool - ( + bool result = MetadataConversionUtilities.TryConvertItemMetadataToBool( item, ItemMetadataNames.privateMetadata, - out found - ); + out found); if (found) { diff --git a/src/Tasks/AssemblyDependency/ReferenceResolutionException.cs b/src/Tasks/AssemblyDependency/ReferenceResolutionException.cs index 2b9a6d24ce9..621d8834891 100644 --- a/src/Tasks/AssemblyDependency/ReferenceResolutionException.cs +++ b/src/Tasks/AssemblyDependency/ReferenceResolutionException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/AssemblyDependency/ReferenceTable.cs b/src/Tasks/AssemblyDependency/ReferenceTable.cs index 8408c19de17..00e9c2c6103 100644 --- a/src/Tasks/AssemblyDependency/ReferenceTable.cs +++ b/src/Tasks/AssemblyDependency/ReferenceTable.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -240,8 +240,7 @@ internal sealed class ReferenceTable /// /// #endif - internal ReferenceTable - ( + internal ReferenceTable( IBuildEngine buildEngine, bool findDependencies, bool findSatellites, @@ -335,8 +334,7 @@ internal ReferenceTable } // Compile searchpaths into fast resolver array. - Resolvers = AssemblyResolution.CompileSearchPaths - ( + Resolvers = AssemblyResolution.CompileSearchPaths( buildEngine, searchPaths, candidateAssemblyFiles, @@ -353,8 +351,7 @@ internal ReferenceTable getRuntimeVersion, targetedRuntimeVersion, getAssemblyPathInGac, - log - ); + log); } /// @@ -436,11 +433,9 @@ internal Reference GetReference(AssemblyNameExtension assemblyName) /// The reference to work on /// The path to the assembly file. /// The AssemblyName of assemblyFileName - private AssemblyNameExtension NameAssemblyFileReference - ( + private AssemblyNameExtension NameAssemblyFileReference( Reference reference, - string assemblyFileName - ) + string assemblyFileName) { AssemblyNameExtension assemblyName = null; @@ -467,23 +462,17 @@ string assemblyFileName { assemblyName = new AssemblyNameExtension("*directory*"); - reference.AddError - ( - new ReferenceResolutionException - ( + reference.AddError( + new ReferenceResolutionException( ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.ExpectedFileGotDirectory", reference.FullPath), - null - ) - ); + null)); reference.FullPath = String.Empty; } if (assemblyName == null) { - reference.AddError - ( - new DependencyResolutionException(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.ExpectedFileMissing", reference.FullPath), null) - ); + reference.AddError( + new DependencyResolutionException(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.ExpectedFileMissing", reference.FullPath), null)); } } catch (BadImageFormatException e) @@ -513,12 +502,10 @@ string assemblyFileName /// The task items which contain file names to add. /// The task items which contain fusion names to add. /// Exceptions encountered while setting primary items. Exceptions are logged, but it doesn't stop the resolution process. - private void SetPrimaryItems - ( + private void SetPrimaryItems( ITaskItem[] referenceAssemblyFiles, ITaskItem[] referenceAssemblyNames, - List exceptions - ) + List exceptions) { // Loop over the referenceAssemblyFiles provided and add each one that doesn't exist. // Set the primary flag to 'true'. @@ -551,10 +538,8 @@ List exceptions /// /// The task item which contain fusion names to add. /// Resulting exception containing resolution failure details, if any: too costly to throw it. - private Exception SetPrimaryAssemblyReferenceItem - ( - ITaskItem referenceAssemblyName - ) + private Exception SetPrimaryAssemblyReferenceItem( + ITaskItem referenceAssemblyName) { // Get the desired executable extension. string executableExtension = referenceAssemblyName.GetMetadata(ItemMetadataNames.executableExtension); @@ -591,10 +576,8 @@ ITaskItem referenceAssemblyName // 2) We have found the metadata and it is specifically set to false if (assemblyName != null && (isSimpleName || (foundSpecificVersionMetadata && !wantSpecificVersion))) { - assemblyName = new AssemblyNameExtension - ( - AssemblyNameExtension.EscapeDisplayNameCharacters(assemblyName.Name) - ); + assemblyName = new AssemblyNameExtension( + AssemblyNameExtension.EscapeDisplayNameCharacters(assemblyName.Name)); isSimpleName = assemblyName.IsSimpleName; } @@ -630,11 +613,9 @@ ITaskItem referenceAssemblyName // So, we just ignore this setting on down-level platforms if (_projectTargetFramework != null && _projectTargetFramework >= s_targetFrameworkVersion_40) { - reference.EmbedInteropTypes = MetadataConversionUtilities.TryConvertItemMetadataToBool - ( + reference.EmbedInteropTypes = MetadataConversionUtilities.TryConvertItemMetadataToBool( referenceAssemblyName, - ItemMetadataNames.embedInteropTypes - ); + ItemMetadataNames.embedInteropTypes); } // Set the AssemblyFolderKey if there is one. @@ -700,10 +681,8 @@ ITaskItem referenceAssemblyName return new InvalidReferenceAssemblyNameException(referenceAssemblyName.ItemSpec); } - assemblyName = new AssemblyNameExtension - ( - AssemblyNameExtension.EscapeDisplayNameCharacters(reference.FileNameWithoutExtension) - ); + assemblyName = new AssemblyNameExtension( + AssemblyNameExtension.EscapeDisplayNameCharacters(reference.FileNameWithoutExtension)); } // Check to see if this is a prereq assembly. @@ -713,14 +692,12 @@ ITaskItem referenceAssemblyName } else { - _installedAssemblies.GetInfo - ( + _installedAssemblies.GetInfo( assemblyName, out _, out bool isPrerequisite, out bool? isRedistRoot, - out string redistName - ); + out string redistName); reference.IsPrerequisite = isPrerequisite; reference.IsRedistRoot = isRedistRoot; @@ -858,28 +835,22 @@ private void SetPrimaryFileItem(ITaskItem referenceAssemblyFile) string itemSpec = referenceAssemblyFile.ItemSpec; bool hasSpecificVersionMetadata = MetadataConversionUtilities.TryConvertItemMetadataToBool(referenceAssemblyFile, ItemMetadataNames.specificVersion); - reference.MakePrimaryAssemblyReference - ( + reference.MakePrimaryAssemblyReference( referenceAssemblyFile, hasSpecificVersionMetadata, - Path.GetExtension(itemSpec) - ); + Path.GetExtension(itemSpec)); - AssemblyNameExtension assemblyName = NameAssemblyFileReference - ( + AssemblyNameExtension assemblyName = NameAssemblyFileReference( reference, - itemSpec // Contains the assembly file name. - ); + itemSpec); // Contains the assembly file name. // Embed Interop Types aka "NOPIAs" support is not available for Fx < 4.0 // So, we just ignore this setting on down-level platforms if (_projectTargetFramework >= s_targetFrameworkVersion_40) { - reference.EmbedInteropTypes = MetadataConversionUtilities.TryConvertItemMetadataToBool - ( + reference.EmbedInteropTypes = MetadataConversionUtilities.TryConvertItemMetadataToBool( referenceAssemblyFile, - ItemMetadataNames.embedInteropTypes - ); + ItemMetadataNames.embedInteropTypes); } AddReference(assemblyName, reference); @@ -899,10 +870,8 @@ private void SetPrimaryFileItem(ITaskItem referenceAssemblyFile) /// Find related files like .pdbs and .xmls /// /// The reference to the parent assembly. - private void FindRelatedFiles - ( - Reference reference - ) + private void FindRelatedFiles( + Reference reference) { string baseName = reference.FullPathWithoutExtension; @@ -946,10 +915,8 @@ Reference reference /// Find satellite assemblies. /// /// The reference to the parent assembly. - private void FindSatellites - ( - Reference reference - ) + private void FindSatellites( + Reference reference) { try { @@ -993,10 +960,8 @@ Reference reference /// Find serialization assemblies. /// /// The reference to the parent assembly. - private void FindSerializationAssemblies - ( - Reference reference - ) + private void FindSerializationAssemblies( + Reference reference) { string serializationAssemblyFilename = reference.FileNameWithoutExtension + ".XmlSerializers.dll"; string serializationAssemblyPath = Path.Combine(reference.DirectoryName, serializationAssemblyFilename); @@ -1010,12 +975,10 @@ Reference reference /// /// Get unified dependencies and scatter files for a reference. /// - private void GetUnifiedAssemblyMetadata - ( + private void GetUnifiedAssemblyMetadata( Reference reference, out IEnumerable unifiedDependencies, - out string[] scatterFiles - ) + out string[] scatterFiles) { // Shortcut if this is a prereq file--don't find dependencies. // We also don't want to look for dependencies if we already know @@ -1027,14 +990,12 @@ out string[] scatterFiles return; } - _getAssemblyMetadata - ( + _getAssemblyMetadata( reference.FullPath, _assemblyMetadataCache, out AssemblyNameExtension[] dependentAssemblies, out scatterFiles, - out FrameworkName frameworkName - ); + out FrameworkName frameworkName); reference.FrameworkNameAttribute = frameworkName; @@ -1083,10 +1044,8 @@ out FrameworkName frameworkName /// Given an enumerator of pre-unified assembly names, return an enumerator of unified /// assembly names. /// - private IEnumerable GetUnifiedAssemblyNames - ( - IEnumerable preUnificationAssemblyNames - ) + private IEnumerable GetUnifiedAssemblyNames( + IEnumerable preUnificationAssemblyNames) { foreach (AssemblyNameExtension preUnificationAssemblyName in preUnificationAssemblyNames) { @@ -1106,21 +1065,17 @@ IEnumerable preUnificationAssemblyNames /// /// The reference to the parent assembly. /// New references are added to this list. - private void FindDependenciesAndScatterFiles - ( + private void FindDependenciesAndScatterFiles( Reference reference, - List> newEntries - ) + List> newEntries) { // Before checking for dependencies check to see if the reference itself exists. // Even though to get to this point the reference must be resolved // the reference may not exist on disk if the reference is a project to project reference. if (!_fileExists(reference.FullPath)) { - reference.AddError - ( - new DependencyResolutionException(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.ExpectedFileMissing", reference.FullPath), null) - ); + reference.AddError( + new DependencyResolutionException(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.ExpectedFileMissing", reference.FullPath), null)); return; } @@ -1265,12 +1220,10 @@ internal static void CalculateParentAssemblyDirectories(List parentRefer /// The fusion name for this reference. /// The file name to match if {RawFileName} is seen. (May be null). /// The reference object. - private void ResolveReference - ( + private void ResolveReference( AssemblyNameExtension assemblyName, string rawFileNameCandidate, - Reference reference - ) + Reference reference) { // Now, resolve this reference. string resolvedPath = null; @@ -1313,8 +1266,7 @@ Reference reference // Resolve try { - resolvedPath = AssemblyResolution.ResolveReference - ( + resolvedPath = AssemblyResolution.ResolveReference( jaggedResolvers, assemblyName, reference.SDKName, @@ -1326,8 +1278,7 @@ Reference reference reference.AssemblyFolderKey, assembliesConsideredAndRejected, out resolvedSearchPath, - out userRequestedSpecificFile - ); + out userRequestedSpecificFile); } catch (BadImageFormatException e) { @@ -1348,14 +1299,10 @@ out userRequestedSpecificFile { if (assemblyName != null) { - reference.AddError - ( - new ReferenceResolutionException - ( + reference.AddError( + new ReferenceResolutionException( ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.CouldNotLocateAssembly", assemblyName.FullName), - null - ) - ); + null)); } } } @@ -1613,13 +1560,11 @@ private static void RemoveDependencies(Reference removedReference, DictionaryThe task items which contain file names to add. /// The task items which contain fusion names to add. /// Errors encountered while computing closure. - internal void ComputeClosure - ( + internal void ComputeClosure( IEnumerable remappedAssembliesValue, ITaskItem[] referenceAssemblyFiles, ITaskItem[] referenceAssemblyNames, - List exceptions - ) + List exceptions) { MSBuildEventSource.Log.RarComputeClosureStart(); { @@ -1822,11 +1767,9 @@ private void ResolveConflictsBetweenReferences(List assem while (comparisonIndex < assemblyReferences.Count) { - bool isLeftVictim = ResolveAssemblyNameConflict - ( + bool isLeftVictim = ResolveAssemblyNameConflict( assemblyReferences[currentWinnerIndex], - assemblyReferences[comparisonIndex] - ) == 0; + assemblyReferences[comparisonIndex]) == 0; if (isLeftVictim) { @@ -1841,11 +1784,9 @@ private void ResolveConflictsBetweenReferences(List assem /// Based on the closure, get a table of ideal remappings needed to /// produce zero conflicts. /// - internal void ResolveConflicts - ( + internal void ResolveConflicts( out List idealRemappings, - out List conflictingReferences - ) + out List conflictingReferences) { idealRemappings = null; conflictingReferences = null; @@ -2209,10 +2150,8 @@ private Dictionary> BuildSimpleNameTable() return baseNameToReferences; } - private static void RemoveReferencesWithoutConflicts - ( - Dictionary> baseNameToReferences - ) + private static void RemoveReferencesWithoutConflicts( + Dictionary> baseNameToReferences) { string[] baseNames = new string[baseNameToReferences.Count]; baseNameToReferences.Keys.CopyTo(baseNames, 0); @@ -2381,13 +2320,11 @@ private static int ResolveAssemblyNameConflict(AssemblyNameReference assemblyRef bool rightConflictLegacyUnified = !isNonUnified && assemblyReference1.reference.IsPrimary; // This is ok here because even if the method says two versions are equivalent the algorithm below will still pick the highest version. - bool equivalent = AreAssembliesEquivalent - ( + bool equivalent = AreAssembliesEquivalent( leftConflictFusionName, leftConflictLegacyUnified, rightConflictFusionName, - rightConflictLegacyUnified - ); + rightConflictLegacyUnified); Version leftConflictVersion = assemblyReference0.assemblyName.Version; Version rightConflictVersion = assemblyReference1.assemblyName.Version; @@ -2397,8 +2334,7 @@ private static int ResolveAssemblyNameConflict(AssemblyNameReference assemblyRef // Version comparison only if there are two versions to compare. // Null versions can occur when simply-named assemblies are unresolved. leftConflictVersion != null && rightConflictVersion != null - && leftConflictVersion > rightConflictVersion - ) + && leftConflictVersion > rightConflictVersion) { // Choose the higher version victim = 1; @@ -2412,8 +2348,7 @@ private static int ResolveAssemblyNameConflict(AssemblyNameReference assemblyRef // Version comparison only if there are two versions to compare. // Null versions can occur when simply-named assemblies are unresolved. leftConflictVersion != null && rightConflictVersion != null - && leftConflictVersion < rightConflictVersion - ) + && leftConflictVersion < rightConflictVersion) { // Choose the higher version victim = 0; @@ -2483,15 +2418,13 @@ private static bool IsAssemblyRemovedFromDotNetFramework(AssemblyNameExtension a /// May be true, false or null. Null means there was no IsRedistRoot in the redist list. /// Name of the corresponding Resist specified in the redist list. /// True if there was a unification. - private bool UnifyAssemblyNameVersions - ( + private bool UnifyAssemblyNameVersions( AssemblyNameExtension assemblyName, out Version unifiedVersion, out UnificationReason unificationReason, out bool isPrerequisite, out bool? isRedistRoot, - out string redistName - ) + out string redistName) { unifiedVersion = assemblyName.Version; isPrerequisite = false; @@ -2534,14 +2467,12 @@ out string redistName // Try for an installed assemblies unification. if (_installedAssemblies != null) { - _installedAssemblies.GetInfo - ( + _installedAssemblies.GetInfo( assemblyName, out unifiedVersion, out isPrerequisite, out isRedistRoot, - out redistName - ); + out redistName); // Was there a unification? if (unifiedVersion != assemblyName.Version) @@ -2595,16 +2526,14 @@ private bool CompareAssembliesIgnoringVersion(AssemblyName a, AssemblyName b) /// Serialization assembly files. /// Receives the list of associated scatter files. /// All copy-local files out of primaryFiles+dependencyFiles+relatedFiles+satelliteFiles. - internal void GetReferenceItems - ( + internal void GetReferenceItems( out ITaskItem[] primaryFiles, out ITaskItem[] dependencyFiles, out ITaskItem[] relatedFiles, out ITaskItem[] satelliteFiles, out ITaskItem[] serializationAssemblyFiles, out ITaskItem[] scatterFiles, - out ITaskItem[] copyLocalFiles - ) + out ITaskItem[] copyLocalFiles) { var primaryItems = new List(); var dependencyItems = new List(); @@ -2619,8 +2548,7 @@ out ITaskItem[] copyLocalFiles AssemblyNameExtension assemblyName = kvp.Key; Reference reference = kvp.Value; - reference.SetFinalCopyLocalState - ( + reference.SetFinalCopyLocalState( assemblyName, _frameworkPaths, _targetProcessorArchitecture, @@ -2630,8 +2558,7 @@ out ITaskItem[] copyLocalFiles _getAssemblyPathInGac, _copyLocalDependenciesWhenParentReferenceInGac, _doNotCopyLocalIfInGac, - this - ); + this); // Conflict victims and badimages are filtered out. if (reference.IsBadImage) @@ -2674,7 +2601,7 @@ out ITaskItem[] copyLocalFiles serializationAssemblyFiles = serializationAssemblyItems.ToArray(); scatterFiles = scatterItems.ToArray(); - // Sort for stable outputs. (These came from a dictionary, which has undefined enumeration order.) + // Sort for stable outputs. (These came from a dictionary, which has undefined enumeration order.) Array.Sort(primaryFiles, TaskItemSpecFilenameComparer.GenericComparer); // Find the copy-local items. @@ -2932,7 +2859,7 @@ private bool VerifyArchitectureOfImplementationDll(string dllPath, string winmdF dllArchitecture = SystemProcessorArchitecture.Arm; break; case NativeMethods.IMAGE_FILE_MACHINE_ARM64: - dllArchitecture = (SystemProcessorArchitecture) 6; // There's no entry for ARM64 in SystemProcessorArchitecture, use the next available constant + dllArchitecture = (SystemProcessorArchitecture)6; // There's no entry for ARM64 in SystemProcessorArchitecture, use the next available constant break; case NativeMethods.IMAGE_FILE_MACHINE_I386: dllArchitecture = SystemProcessorArchitecture.X86; @@ -3063,12 +2990,10 @@ private static void FindCopyLocalItems(ITaskItem[] items, List copyLo { foreach (ITaskItem i in items) { - bool copyLocal = MetadataConversionUtilities.TryConvertItemMetadataToBool - ( + bool copyLocal = MetadataConversionUtilities.TryConvertItemMetadataToBool( i, ItemMetadataNames.copyLocal, - out bool found - ); + out bool found); if (found && copyLocal) { diff --git a/src/Tasks/AssemblyDependency/ResolutionSearchLocation.cs b/src/Tasks/AssemblyDependency/ResolutionSearchLocation.cs index 31a62ba6e88..e79d68ce21a 100644 --- a/src/Tasks/AssemblyDependency/ResolutionSearchLocation.cs +++ b/src/Tasks/AssemblyDependency/ResolutionSearchLocation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; diff --git a/src/Tasks/AssemblyDependency/ResolveAssemblyReference.cs b/src/Tasks/AssemblyDependency/ResolveAssemblyReference.cs index 9dc674cb6ac..9e21604d2d6 100644 --- a/src/Tasks/AssemblyDependency/ResolveAssemblyReference.cs +++ b/src/Tasks/AssemblyDependency/ResolveAssemblyReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -1050,13 +1050,11 @@ public String DependsOnNETStandard /// Array of identities of ideal assembly remappings. /// List of exceptions that were not attributable to a particular fusion name. /// - private bool LogResults - ( + private bool LogResults( ReferenceTable dependencyTable, List idealAssemblyRemappings, List idealAssemblyRemappingsIdentities, - List generalResolutionExceptions - ) + List generalResolutionExceptions) { bool success = true; MSBuildEventSource.Log.RarLogResultsStart(); @@ -1180,16 +1178,14 @@ quiet at the engine level. Reference victimReference = dependencyTable.GetReference(conflictVictim); var newVerStr = idealRemapping.BindingRedirects[j].NewVersion.ToString(); - Log.LogMessageFromResources - ( + Log.LogMessageFromResources( MessageImportance.High, "ResolveAssemblyReference.ConflictRedirectSuggestion", idealRemappingPartialAssemblyName, conflictVictim.Version, victimReference.FullPath, newVerStr, - reference.FullPath - ); + reference.FullPath); if (!SupportsBindingRedirectGeneration && !AutoUnify) { @@ -1304,7 +1300,9 @@ internal static string ByteArrayToString(byte[] a) var buffer = new StringBuilder(a.Length * 2); for (int i = 0; i < a.Length; ++i) + { buffer.Append(a[i].ToString("x2", CultureInfo.InvariantCulture)); + } return buffer.ToString(); } @@ -1770,8 +1768,7 @@ private void LogAssembliesConsideredAndRejected(Reference reference, string fusi } if ((messageImportance == MessageImportance.Low && (importance == MessageImportance.Normal || importance == MessageImportance.High)) || - (messageImportance == MessageImportance.Normal && importance == MessageImportance.High) - ) + (messageImportance == MessageImportance.Normal && importance == MessageImportance.High)) { _showAssemblyFoldersExLocations[location.SearchPath] = importance; } @@ -2113,8 +2110,7 @@ private List GetAssemblyRemappingsFromAppConfig() /// Delegate use to read machine type from PE Header /// True if there was success. #endif - internal bool Execute - ( + internal bool Execute( FileExists fileExists, DirectoryExists directoryExists, GetDirectories getDirectories, @@ -2131,8 +2127,7 @@ internal bool Execute #endif GetAssemblyPathInGac getAssemblyPathInGac, IsWinMDFile isWinMDFile, - ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader - ) + ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader) { bool success = true; MSBuildEventSource.Log.RarOverallStart(); @@ -2324,8 +2319,7 @@ ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader : null; // Start the table of dependencies with all of the primary references. - ReferenceTable dependencyTable = new ReferenceTable - ( + ReferenceTable dependencyTable = new ReferenceTable( BuildEngine, _findDependencies, _findSatellites, @@ -2364,8 +2358,7 @@ ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader _warnOrErrorOnTargetArchitectureMismatch, _ignoreTargetFrameworkAttributeVersionMismatch, _unresolveFrameworkAssembliesFromHigherFrameworks, - assemblyMetadataCache - ); + assemblyMetadataCache); dependencyTable.FindDependenciesOfExternallyResolvedReferences = FindDependenciesOfExternallyResolvedReferences; @@ -2380,15 +2373,13 @@ ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader if (AutoUnify && FindDependencies) { // Compute all dependencies. - dependencyTable.ComputeClosure - ( + dependencyTable.ComputeClosure( // Use any app.config specified binding redirects so that later when we output suggested redirects // for the GenerateBindingRedirects target, we don't suggest ones that the user already wrote appConfigRemappedAssemblies, _assemblyFiles, _assemblyNames, - generalResolutionExceptions - ); + generalResolutionExceptions); try { @@ -2411,17 +2402,15 @@ ReadMachineTypeFromPEHeader readMachineTypeFromPEHeader // Based on the closure, get a table of ideal remappings needed to // produce zero conflicts. - dependencyTable.ResolveConflicts - ( + dependencyTable.ResolveConflicts( out autoUnifiedRemappedAssemblies, - out autoUnifiedRemappedAssemblyReferences - ); + out autoUnifiedRemappedAssemblyReferences); } IReadOnlyCollection allRemappedAssemblies = CombineRemappedAssemblies(appConfigRemappedAssemblies, autoUnifiedRemappedAssemblies); List idealAssemblyRemappings = autoUnifiedRemappedAssemblies; List idealAssemblyRemappingsIdentities = autoUnifiedRemappedAssemblyReferences; - bool shouldRerunClosure = autoUnifiedRemappedAssemblies?.Count > 0 || excludedReferencesExist; + bool shouldRerunClosure = autoUnifiedRemappedAssemblies?.Count > 0 || excludedReferencesExist; if (!AutoUnify || !FindDependencies || shouldRerunClosure) { @@ -2448,24 +2437,20 @@ out autoUnifiedRemappedAssemblyReferences } // Resolve any conflicts. - dependencyTable.ResolveConflicts - ( + dependencyTable.ResolveConflicts( out idealAssemblyRemappings, - out idealAssemblyRemappingsIdentities - ); + out idealAssemblyRemappingsIdentities); } // Build the output tables. - dependencyTable.GetReferenceItems - ( + dependencyTable.GetReferenceItems( out _resolvedFiles, out _resolvedDependencyFiles, out _relatedFiles, out _satelliteFiles, out _serializationAssemblyFiles, out _scatterFiles, - out _copyLocalFiles - ); + out _copyLocalFiles); // If we're not finding dependencies, then don't suggest redirects (they're only about dependencies). if (FindDependencies) @@ -2664,10 +2649,14 @@ private AssemblyNameExtension[] GetDependencies(Reference resolvedReference, Fil private static IReadOnlyCollection CombineRemappedAssemblies(IReadOnlyCollection first, IReadOnlyCollection second) { if (first == null) + { return second; + } if (second == null) + { return first; + } var combined = new List(first.Count + second.Count); combined.AddRange(first); @@ -3162,8 +3151,7 @@ private string GetAssemblyPathInGac(AssemblyNameExtension assemblyName, SystemPr /// True if there was success. public override bool Execute() { - return Execute - ( + return Execute( p => FileUtilities.FileExistsNoThrow(p), p => FileUtilities.DirectoryExistsNoThrow(p), (p, searchPattern) => Directory.GetDirectories(p, searchPattern), @@ -3183,8 +3171,7 @@ public override bool Execute() => GetAssemblyPathInGac(assemblyName, targetProcessorArchitecture, getRuntimeVersion, targetedRuntimeVersion, fileExists, fullFusionName, specificVersion), (string fullPath, GetAssemblyRuntimeVersion getAssemblyRuntimeVersion, FileExists fileExists, out string imageRuntimeVersion, out bool isManagedWinmd) => AssemblyInformation.IsWinMDFile(fullPath, getAssemblyRuntimeVersion, fileExists, out imageRuntimeVersion, out isManagedWinmd), - p => ReferenceTable.ReadMachineTypeFromPEHeader(p) - ); + p => ReferenceTable.ReadMachineTypeFromPEHeader(p)); } #endregion diff --git a/src/Tasks/AssemblyDependency/Resolver.cs b/src/Tasks/AssemblyDependency/Resolver.cs index 66fddca12ab..527902d5370 100644 --- a/src/Tasks/AssemblyDependency/Resolver.cs +++ b/src/Tasks/AssemblyDependency/Resolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -80,8 +80,7 @@ protected Resolver(string searchPathElement, GetAssemblyName getAssemblyName, Fi /// The path where the file was found. /// Whether or not the user wanted a specific file (for example, HintPath is a request for a specific file) /// True if the file was resolved. - public abstract bool Resolve - ( + public abstract bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -92,8 +91,7 @@ public abstract bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ); + out bool userRequestedSpecificFile); /// /// The search path element that this resolver is based on. @@ -104,15 +102,13 @@ out bool userRequestedSpecificFile /// Resolve a single file. /// /// True if the file was a match, false otherwise. - protected bool ResolveAsFile - ( + protected bool ResolveAsFile( string fullPath, AssemblyNameExtension assemblyName, bool isPrimaryProjectReference, bool wantSpecificVersion, bool allowMismatchBetweenFusionNameAndFileName, - List assembliesConsideredAndRejected - ) + List assembliesConsideredAndRejected) { ResolutionSearchLocation considered = null; if (assembliesConsideredAndRejected != null) @@ -144,15 +140,13 @@ List assembliesConsideredAndRejected /// Whether to allow naming mismatch. /// Path to a possible file. /// Information about why the candidate file didn't match - protected bool FileMatchesAssemblyName - ( + protected bool FileMatchesAssemblyName( AssemblyNameExtension assemblyName, bool isPrimaryProjectReference, bool wantSpecificVersion, bool allowMismatchBetweenFusionNameAndFileName, string pathToCandidateAssembly, - ResolutionSearchLocation searchLocation - ) + ResolutionSearchLocation searchLocation) { if (searchLocation != null) { @@ -241,8 +235,7 @@ ResolutionSearchLocation searchLocation if ( targetAssemblyName.AssemblyName.ProcessorArchitecture != targetProcessorArchitecture && /* The target and assembly architectures do not match*/ (targetProcessorArchitecture != ProcessorArchitecture.None && targetAssemblyName.AssemblyName.ProcessorArchitecture != ProcessorArchitecture.None) /*The assembly is not none*/ - && (targetProcessorArchitecture != ProcessorArchitecture.MSIL && targetAssemblyName.AssemblyName.ProcessorArchitecture != ProcessorArchitecture.MSIL) /*The assembly is not MSIL*/ - ) + && (targetProcessorArchitecture != ProcessorArchitecture.MSIL && targetAssemblyName.AssemblyName.ProcessorArchitecture != ProcessorArchitecture.MSIL)) /*The assembly is not MSIL*/ { if (searchLocation != null) { @@ -300,15 +293,13 @@ ResolutionSearchLocation searchLocation /// the directory to look in /// Receives the list of locations that this function tried to find the assembly. May be "null". /// 'null' if the assembly wasn't found. - protected string ResolveFromDirectory - ( + protected string ResolveFromDirectory( AssemblyNameExtension assemblyName, bool isPrimaryProjectReference, bool wantSpecificVersion, string[] executableExtensions, string directory, - List assembliesConsideredAndRejected - ) + List assembliesConsideredAndRejected) { if (assemblyName == null) { diff --git a/src/Tasks/AssemblyDependency/TaskItemSpecFilenameComparer.cs b/src/Tasks/AssemblyDependency/TaskItemSpecFilenameComparer.cs index ad9ffac0441..e0a53390a7b 100644 --- a/src/Tasks/AssemblyDependency/TaskItemSpecFilenameComparer.cs +++ b/src/Tasks/AssemblyDependency/TaskItemSpecFilenameComparer.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/AssemblyDependency/UnificationReason.cs b/src/Tasks/AssemblyDependency/UnificationReason.cs index 8223183a0ad..12c9216820b 100644 --- a/src/Tasks/AssemblyDependency/UnificationReason.cs +++ b/src/Tasks/AssemblyDependency/UnificationReason.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/AssemblyDependency/UnificationVersion.cs b/src/Tasks/AssemblyDependency/UnificationVersion.cs index bcd31a39ef8..021d17d702b 100644 --- a/src/Tasks/AssemblyDependency/UnificationVersion.cs +++ b/src/Tasks/AssemblyDependency/UnificationVersion.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/AssemblyDependency/UnifiedAssemblyName.cs b/src/Tasks/AssemblyDependency/UnifiedAssemblyName.cs index 34b0ff9143c..60491219832 100644 --- a/src/Tasks/AssemblyDependency/UnifiedAssemblyName.cs +++ b/src/Tasks/AssemblyDependency/UnifiedAssemblyName.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; diff --git a/src/Tasks/AssemblyDependency/WarnOrErrorOnTargetArchitectureMismatchBehavior.cs b/src/Tasks/AssemblyDependency/WarnOrErrorOnTargetArchitectureMismatchBehavior.cs index 13ef6555e76..9d2a2284f10 100644 --- a/src/Tasks/AssemblyDependency/WarnOrErrorOnTargetArchitectureMismatchBehavior.cs +++ b/src/Tasks/AssemblyDependency/WarnOrErrorOnTargetArchitectureMismatchBehavior.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/AssemblyFolder.cs b/src/Tasks/AssemblyFolder.cs index d8cafc0a6d6..3d9bf146499 100644 --- a/src/Tasks/AssemblyFolder.cs +++ b/src/Tasks/AssemblyFolder.cs @@ -1,5 +1,6 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + #if FEATURE_WIN32_REGISTRY using System; @@ -34,12 +35,10 @@ internal static class AssemblyFolder /// Like 'hklm' or 'hkcu' /// The registry key to examine /// The object to populate - private static void AddFoldersFromRegistryKey - ( + private static void AddFoldersFromRegistryKey( RegistryKey hive, string key, - Dictionary directories - ) + Dictionary directories) { using (RegistryKey baseKey = hive.OpenSubKey(key)) { @@ -84,24 +83,19 @@ Dictionary directories /// private static void AddFoldersFromRegistryKey( string key, - Dictionary directories - ) + Dictionary directories) { // First add the current user. - AddFoldersFromRegistryKey - ( + AddFoldersFromRegistryKey( Registry.CurrentUser, key, - directories - ); + directories); // Then add the local machine. - AddFoldersFromRegistryKey - ( + AddFoldersFromRegistryKey( Registry.LocalMachine, key, - directories - ); + directories); } /// @@ -114,17 +108,13 @@ private static void CreateAssemblyFolders() if (NativeMethodsShared.IsWindows) { // Populate the table of assembly folders. - AddFoldersFromRegistryKey - ( + AddFoldersFromRegistryKey( @"SOFTWARE\Microsoft\.NETFramework\AssemblyFolders", - s_assemblyFolders - ); + s_assemblyFolders); - AddFoldersFromRegistryKey - ( + AddFoldersFromRegistryKey( @"SOFTWARE\Microsoft\VisualStudio\8.0\AssemblyFolders", - s_assemblyFolders - ); + s_assemblyFolders); } } diff --git a/src/Tasks/AssemblyInfo.cs b/src/Tasks/AssemblyInfo.cs index 02ca0d38cf8..f86d61efe2b 100644 --- a/src/Tasks/AssemblyInfo.cs +++ b/src/Tasks/AssemblyInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Tasks/AssemblyRegistrationCache.cs b/src/Tasks/AssemblyRegistrationCache.cs index ba5beaa4b82..8ac4f9ff065 100644 --- a/src/Tasks/AssemblyRegistrationCache.cs +++ b/src/Tasks/AssemblyRegistrationCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/AssemblyRemapping.cs b/src/Tasks/AssemblyRemapping.cs index ac09c0fcb63..3e70c3e14bd 100644 --- a/src/Tasks/AssemblyRemapping.cs +++ b/src/Tasks/AssemblyRemapping.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; diff --git a/src/Tasks/AssemblyResources.cs b/src/Tasks/AssemblyResources.cs index 2d8cfcdf7f3..f8d24b76557 100644 --- a/src/Tasks/AssemblyResources.cs +++ b/src/Tasks/AssemblyResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Reflection; diff --git a/src/Tasks/AssignCulture.cs b/src/Tasks/AssignCulture.cs index f7c09a4c3d4..343eabff36d 100644 --- a/src/Tasks/AssignCulture.cs +++ b/src/Tasks/AssignCulture.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -113,7 +113,7 @@ public class AssignCulture : TaskExtension #endregion #region ITask Members - + /// /// Execute. /// @@ -134,14 +134,12 @@ public override bool Execute() AssignedFiles[i] = new TaskItem(Files[i]); string dependentUpon = AssignedFiles[i].GetMetadata(ItemMetadataNames.dependentUpon); - Culture.ItemCultureInfo info = Culture.GetItemCultureInfo - ( + Culture.ItemCultureInfo info = Culture.GetItemCultureInfo( AssignedFiles[i].ItemSpec, dependentUpon, // If 'WithCulture' is explicitly set to false, treat as 'culture-neutral' and keep the original name of the resource. // https://github.com/dotnet/msbuild/issues/3064 - AssignedFiles[i].GetMetadata("WithCulture").Equals("false", StringComparison.OrdinalIgnoreCase) - ); + AssignedFiles[i].GetMetadata("WithCulture").Equals("false", StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(info.culture)) { @@ -158,13 +156,11 @@ public override bool Execute() CultureNeutralAssignedFiles[i] = new TaskItem(AssignedFiles[i]) { ItemSpec = info.cultureNeutralFilename }; - Log.LogMessageFromResources - ( + Log.LogMessageFromResources( MessageImportance.Low, "AssignCulture.Comment", AssignedFiles[i].GetMetadata("Culture"), - AssignedFiles[i].ItemSpec - ); + AssignedFiles[i].ItemSpec); } catch (ArgumentException e) { @@ -174,8 +170,8 @@ public override bool Execute() #if DEBUG catch (Exception e) { - Debug.Assert(false, "Unexpected exception in AssignCulture.Execute. " + - "Please log a MSBuild bug specifying the steps to reproduce the problem. " + + Debug.Assert(false, "Unexpected exception in AssignCulture.Execute. " + + "Please log a MSBuild bug specifying the steps to reproduce the problem. " + e); throw; } diff --git a/src/Tasks/AssignLinkMetadata.cs b/src/Tasks/AssignLinkMetadata.cs index 3e4c0c62633..768149a9fc8 100644 --- a/src/Tasks/AssignLinkMetadata.cs +++ b/src/Tasks/AssignLinkMetadata.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -51,8 +51,7 @@ public override bool Execute() if ( String.IsNullOrEmpty(item.GetMetadata("Link")) && !String.IsNullOrEmpty(definingProject) - && fullPath.StartsWith(definingProjectDirectory, StringComparison.OrdinalIgnoreCase) - ) + && fullPath.StartsWith(definingProjectDirectory, StringComparison.OrdinalIgnoreCase)) { string link = fullPath.Substring(definingProjectDirectory.Length); ITaskItem outputItem = new TaskItem(item); diff --git a/src/Tasks/AssignProjectConfiguration.cs b/src/Tasks/AssignProjectConfiguration.cs index 1f93054af17..287ddf6fa41 100644 --- a/src/Tasks/AssignProjectConfiguration.cs +++ b/src/Tasks/AssignProjectConfiguration.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -254,7 +254,7 @@ public override bool Execute() #endregion #region Methods - + /// /// Given a project reference task item and an XML document containing project configurations, /// find the configuration for that task item. diff --git a/src/Tasks/AssignTargetPath.cs b/src/Tasks/AssignTargetPath.cs index 48079383cd6..91d2f1d32b2 100644 --- a/src/Tasks/AssignTargetPath.cs +++ b/src/Tasks/AssignTargetPath.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/AxImp.cs b/src/Tasks/AxImp.cs index 643a4029724..fd0b6ccd2ae 100644 --- a/src/Tasks/AxImp.cs +++ b/src/Tasks/AxImp.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/AxReference.cs b/src/Tasks/AxReference.cs index 3b0c87d1229..81a24df2d8e 100644 --- a/src/Tasks/AxReference.cs +++ b/src/Tasks/AxReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Reflection; diff --git a/src/Tasks/AxTlbBaseReference.cs b/src/Tasks/AxTlbBaseReference.cs index 6f5ac03fb55..6ac34233207 100644 --- a/src/Tasks/AxTlbBaseReference.cs +++ b/src/Tasks/AxTlbBaseReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Tasks/AxTlbBaseTask.cs b/src/Tasks/AxTlbBaseTask.cs index a6bde0f4930..227a4efc86e 100644 --- a/src/Tasks/AxTlbBaseTask.cs +++ b/src/Tasks/AxTlbBaseTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -106,15 +106,13 @@ protected internal override void AddCommandLineCommands(CommandLineBuilderExtens /// A string containing the full path of this tool, or null if the tool was not found protected override string GenerateFullPathToTool() { - string pathToTool = SdkToolsPathUtility.GeneratePathToTool - ( + string pathToTool = SdkToolsPathUtility.GeneratePathToTool( SdkToolsPathUtility.FileInfoExists, Utilities.ProcessorArchitecture.CurrentProcessArchitecture, SdkToolsPath, ToolName, Log, - true - ); + true); return pathToTool; } diff --git a/src/Tasks/BootstrapperUtil/BootstrapperBuilder.cs b/src/Tasks/BootstrapperUtil/BootstrapperBuilder.cs index ce5faa9fb28..33082afe26f 100644 --- a/src/Tasks/BootstrapperUtil/BootstrapperBuilder.cs +++ b/src/Tasks/BootstrapperUtil/BootstrapperBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using System; @@ -552,7 +552,7 @@ private void RefreshResources() } XmlNode rootNode = resourceDoc.SelectSingleNode("Resources"); - XmlAttribute cultureAttribute = (XmlAttribute) rootNode?.Attributes.GetNamedItem("Culture"); + XmlAttribute cultureAttribute = (XmlAttribute)rootNode?.Attributes.GetNamedItem("Culture"); if (cultureAttribute != null) { XmlNode stringsNode = rootNode.SelectSingleNode("Strings"); @@ -1107,7 +1107,10 @@ private Product CreateProduct(XmlNode node) XmlNode packageFilesNode = node.SelectSingleNode(BOOTSTRAPPER_PREFIX + ":Package/" + BOOTSTRAPPER_PREFIX + ":PackageFiles", _xmlNamespaceManager); string copyAllPackageFiles = String.Empty; - if (packageFilesNode != null) copyAllPackageFiles = ReadAttribute(packageFilesNode, "CopyAllPackageFiles"); + if (packageFilesNode != null) + { + copyAllPackageFiles = ReadAttribute(packageFilesNode, "CopyAllPackageFiles"); + } product = new Product(node, productCode, results, copyAllPackageFiles); XmlNodeList packageNodeList = node.SelectNodes(BOOTSTRAPPER_PREFIX + ":Package", _xmlNamespaceManager); @@ -1124,7 +1127,10 @@ private Product CreateProduct(XmlNode node) } if (fPackageAdded) + { return product; + } + return null; } @@ -1559,7 +1565,7 @@ private bool BuildPackages(BuildSettings settings, XmlElement configElement, Res else { string configFileKey = string.Format(CultureInfo.InvariantCulture, "EULA{0}", eulas.Count); - var de = new KeyValuePair(configFileKey, eulaAttribute.Value); + var de = new KeyValuePair(configFileKey, eulaAttribute.Value); eulas[key] = de; eulaAttribute.Value = configFileKey; } @@ -1625,7 +1631,10 @@ private static void ClearReadOnlyAttribute(string strFileName) private static string ByteArrayToString(byte[] byteArray) { - if (byteArray == null) return null; + if (byteArray == null) + { + return null; + } var output = new StringBuilder(byteArray.Length); foreach (byte byteValue in byteArray) @@ -1644,12 +1653,14 @@ private static string GetFileHash(string filePath) // Bootstrapper is always signed with the SHA-256 algorithm, no matter which version of // the .NET Framework we are targeting. In ideal situations, bootstrapper files will be // pre-signed anwyay; this is a fallback in case we ever encounter a bootstrapper that is - // not signed. + // not signed. +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA256CryptoServiceProvider" #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter using (Stream s = fi.OpenRead()) { @@ -1687,7 +1698,10 @@ private Package GetPackageForSettings(BuildSettings settings, ProductBuilder bui if (ci != null) { package = builder.Product.Packages.Package(ci.Name); - if (package != null) return package; + if (package != null) + { + return package; + } // Target culture not found? Go through the progression of parent cultures (up until but excluding the invariant culture) -> fallback culture -> parent fallback culture -> default culture -> parent default culture -> any culture available // Note: there is no warning if the parent culture of the requested culture is found @@ -1697,7 +1711,10 @@ private Package GetPackageForSettings(BuildSettings settings, ProductBuilder bui while (parentCulture != CultureInfo.InvariantCulture) { package = GetPackageForSettings_Helper(ci, parentCulture, builder, results, false); - if (package != null) return package; + if (package != null) + { + return package; + } parentCulture = parentCulture.Parent; } @@ -1706,26 +1723,41 @@ private Package GetPackageForSettings(BuildSettings settings, ProductBuilder bui if (fallbackCI != null) { package = GetPackageForSettings_Helper(ci, fallbackCI, builder, results, true); - if (package != null) return package; + if (package != null) + { + return package; + } if (!fallbackCI.IsNeutralCulture) { package = GetPackageForSettings_Helper(ci, fallbackCI.Parent, builder, results, true); - if (package != null) return package; + if (package != null) + { + return package; + } } } package = GetPackageForSettings_Helper(ci, Util.DefaultCultureInfo, builder, results, true); - if (package != null) return package; + if (package != null) + { + return package; + } if (!Util.DefaultCultureInfo.IsNeutralCulture) { package = GetPackageForSettings_Helper(ci, Util.DefaultCultureInfo.Parent, builder, results, true); - if (package != null) return package; + if (package != null) + { + return package; + } } if (results != null && ci != null) + { results.AddMessage(BuildMessage.CreateMessage(BuildMessageSeverity.Warning, "GenerateBootstrapper.UsingProductCulture", ci.Name, builder.Name, builder.Product.Packages.Item(0).Culture)); + } + return builder.Product.Packages.Item(0); } @@ -1801,19 +1833,26 @@ private XmlNode GetResourcesNodeForSettings(BuildSettings settings, BuildResults CultureInfo ci = Util.GetCultureInfoFromString(settings.Culture); CultureInfo fallbackCI = Util.GetCultureInfoFromString(settings.FallbackCulture); XmlNode cultureNode; - + if (ci != null) { // Work through the progression of parent cultures (up until but excluding the invariant culture) -> fallback culture -> parent fallback culture -> default culture -> parent default culture -> any available culture cultureNode = GetResourcesNodeForSettings_Helper(ci, ci, results, ref codepage, false); - if (cultureNode != null) return cultureNode; + if (cultureNode != null) + { + return cultureNode; + } + CultureInfo parentCulture = ci.Parent; // Keep going up the chain of parents, stopping at the invariant culture while (parentCulture != CultureInfo.InvariantCulture) { cultureNode = GetResourcesNodeForSettings_Helper(ci, parentCulture, results, ref codepage, false); - if (cultureNode != null) return cultureNode; + if (cultureNode != null) + { + return cultureNode; + } parentCulture = parentCulture.Parent; } @@ -1822,22 +1861,34 @@ private XmlNode GetResourcesNodeForSettings(BuildSettings settings, BuildResults if (fallbackCI != null) { cultureNode = GetResourcesNodeForSettings_Helper(ci, fallbackCI, results, ref codepage, true); - if (cultureNode != null) return cultureNode; + if (cultureNode != null) + { + return cultureNode; + } if (!fallbackCI.IsNeutralCulture) { cultureNode = GetResourcesNodeForSettings_Helper(ci, fallbackCI.Parent, results, ref codepage, true); - if (cultureNode != null) return cultureNode; + if (cultureNode != null) + { + return cultureNode; + } } } cultureNode = GetResourcesNodeForSettings_Helper(ci, Util.DefaultCultureInfo, results, ref codepage, true); - if (cultureNode != null) return cultureNode; + if (cultureNode != null) + { + return cultureNode; + } if (!Util.DefaultCultureInfo.IsNeutralCulture) { cultureNode = GetResourcesNodeForSettings_Helper(ci, Util.DefaultCultureInfo.Parent, results, ref codepage, true); - if (cultureNode != null) return cultureNode; + if (cultureNode != null) + { + return cultureNode; + } } KeyValuePair altCulturePair = _cultures.FirstOrDefault(); @@ -2173,7 +2224,11 @@ private static void ConvertChildsNodeToAttributes(XmlNode node) private static string GetLogPath() { - if (!s_logging) return null; + if (!s_logging) + { + return null; + } + string logPath = System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\VisualStudio\" + VisualStudioConstants.CurrentVisualStudioVersion + @"\VSPLOG"); diff --git a/src/Tasks/BootstrapperUtil/BuildMessage.cs b/src/Tasks/BootstrapperUtil/BuildMessage.cs index be2c4585e76..bc4272ed8d8 100644 --- a/src/Tasks/BootstrapperUtil/BuildMessage.cs +++ b/src/Tasks/BootstrapperUtil/BuildMessage.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Tasks/BootstrapperUtil/BuildResults.cs b/src/Tasks/BootstrapperUtil/BuildResults.cs index 9b7d66b5c9a..6e3306e44a9 100644 --- a/src/Tasks/BootstrapperUtil/BuildResults.cs +++ b/src/Tasks/BootstrapperUtil/BuildResults.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Runtime.InteropServices; diff --git a/src/Tasks/BootstrapperUtil/BuildSettings.cs b/src/Tasks/BootstrapperUtil/BuildSettings.cs index 4e137089cf6..f71ab1c6a34 100644 --- a/src/Tasks/BootstrapperUtil/BuildSettings.cs +++ b/src/Tasks/BootstrapperUtil/BuildSettings.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/BootstrapperUtil/Interfaces.cs b/src/Tasks/BootstrapperUtil/Interfaces.cs index d3e45d55583..33f04d5c548 100644 --- a/src/Tasks/BootstrapperUtil/Interfaces.cs +++ b/src/Tasks/BootstrapperUtil/Interfaces.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/BootstrapperUtil/NativeMethods.cs b/src/Tasks/BootstrapperUtil/NativeMethods.cs index c79333daae6..7adc90231c8 100644 --- a/src/Tasks/BootstrapperUtil/NativeMethods.cs +++ b/src/Tasks/BootstrapperUtil/NativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Tasks/BootstrapperUtil/Package.cs b/src/Tasks/BootstrapperUtil/Package.cs index a7cf775dff5..36160c909d1 100644 --- a/src/Tasks/BootstrapperUtil/Package.cs +++ b/src/Tasks/BootstrapperUtil/Package.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; using System.Runtime.InteropServices; diff --git a/src/Tasks/BootstrapperUtil/PackageCollection.cs b/src/Tasks/BootstrapperUtil/PackageCollection.cs index 5b7a169a826..c97614576f5 100644 --- a/src/Tasks/BootstrapperUtil/PackageCollection.cs +++ b/src/Tasks/BootstrapperUtil/PackageCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Tasks/BootstrapperUtil/Product.cs b/src/Tasks/BootstrapperUtil/Product.cs index b6dc18dda9c..0909ebd1d61 100644 --- a/src/Tasks/BootstrapperUtil/Product.cs +++ b/src/Tasks/BootstrapperUtil/Product.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/BootstrapperUtil/ProductBuilder.cs b/src/Tasks/BootstrapperUtil/ProductBuilder.cs index ef3841e7386..cef60825152 100644 --- a/src/Tasks/BootstrapperUtil/ProductBuilder.cs +++ b/src/Tasks/BootstrapperUtil/ProductBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/BootstrapperUtil/ProductBuilderCollection.cs b/src/Tasks/BootstrapperUtil/ProductBuilderCollection.cs index 61023f279d7..1af1c8c7f84 100644 --- a/src/Tasks/BootstrapperUtil/ProductBuilderCollection.cs +++ b/src/Tasks/BootstrapperUtil/ProductBuilderCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; diff --git a/src/Tasks/BootstrapperUtil/ProductCollection.cs b/src/Tasks/BootstrapperUtil/ProductCollection.cs index f2c5b12202b..c13239d23b9 100644 --- a/src/Tasks/BootstrapperUtil/ProductCollection.cs +++ b/src/Tasks/BootstrapperUtil/ProductCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Tasks/BootstrapperUtil/ResourceUpdater.cs b/src/Tasks/BootstrapperUtil/ResourceUpdater.cs index 0a3fade1c5d..7d9c3eee377 100644 --- a/src/Tasks/BootstrapperUtil/ResourceUpdater.cs +++ b/src/Tasks/BootstrapperUtil/ResourceUpdater.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/BootstrapperUtil/Util.cs b/src/Tasks/BootstrapperUtil/Util.cs index d62c8247070..973ca74a61f 100644 --- a/src/Tasks/BootstrapperUtil/Util.cs +++ b/src/Tasks/BootstrapperUtil/Util.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/BootstrapperUtil/productvalidationresults.cs b/src/Tasks/BootstrapperUtil/productvalidationresults.cs index c882d9916c3..b9bac8ad628 100644 --- a/src/Tasks/BootstrapperUtil/productvalidationresults.cs +++ b/src/Tasks/BootstrapperUtil/productvalidationresults.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/BootstrapperUtil/xmlvalidationresults.cs b/src/Tasks/BootstrapperUtil/xmlvalidationresults.cs index c41406a7c10..4a144ab5db6 100644 --- a/src/Tasks/BootstrapperUtil/xmlvalidationresults.cs +++ b/src/Tasks/BootstrapperUtil/xmlvalidationresults.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; diff --git a/src/Tasks/BuildCacheDisposeWrapper.cs b/src/Tasks/BuildCacheDisposeWrapper.cs index 2667f33b55f..155522368f5 100644 --- a/src/Tasks/BuildCacheDisposeWrapper.cs +++ b/src/Tasks/BuildCacheDisposeWrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/CSharpParserUtilities.cs b/src/Tasks/CSharpParserUtilities.cs index 2f433522f74..22ce44a2e8d 100644 --- a/src/Tasks/CSharpParserUtilities.cs +++ b/src/Tasks/CSharpParserUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Text; diff --git a/src/Tasks/CallTarget.cs b/src/Tasks/CallTarget.cs index 3ce6ae1b3b0..0b64787bf00 100644 --- a/src/Tasks/CallTarget.cs +++ b/src/Tasks/CallTarget.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Microsoft.Build.Framework; @@ -76,8 +76,7 @@ public override bool Execute() var singleProject = new List(1) { null }; // Build the specified targets in the current project. - return MSBuild.ExecuteTargets - ( + return MSBuild.ExecuteTargets( singleProject, // project = null (current project) null, // propertiesTable = null null, // undefineProperties @@ -88,8 +87,7 @@ public override bool Execute() Log, _targetOutputs, false, - null // toolsVersion = null - ); + null); // toolsVersion = null } #endregion diff --git a/src/Tasks/CodeTaskFactory.cs b/src/Tasks/CodeTaskFactory.cs index c47cd7f6f9a..237817f1b2d 100644 --- a/src/Tasks/CodeTaskFactory.cs +++ b/src/Tasks/CodeTaskFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -1048,7 +1048,7 @@ public bool Initialize(string taskName, IDictionary pa TaskResources = AssemblyResources.PrimaryResources, HelpKeywordPrefix = "MSBuild." }; - + log.LogErrorWithCodeFromResources("TaskFactoryNotSupportedFailure", nameof(CodeTaskFactory)); return false; diff --git a/src/Tasks/ComDependencyWalker.cs b/src/Tasks/ComDependencyWalker.cs index cb76273bb16..3b736f1da1c 100644 --- a/src/Tasks/ComDependencyWalker.cs +++ b/src/Tasks/ComDependencyWalker.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/ComReference.cs b/src/Tasks/ComReference.cs index f1aa4c82c3f..1bcc11c2df1 100644 --- a/src/Tasks/ComReference.cs +++ b/src/Tasks/ComReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices.ComTypes; diff --git a/src/Tasks/ComReferenceInfo.cs b/src/Tasks/ComReferenceInfo.cs index 6c3be701bf6..4e74972a731 100644 --- a/src/Tasks/ComReferenceInfo.cs +++ b/src/Tasks/ComReferenceInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; diff --git a/src/Tasks/ComReferenceItemAttributes.cs b/src/Tasks/ComReferenceItemAttributes.cs index 1dfed67cd12..2c055534808 100644 --- a/src/Tasks/ComReferenceItemAttributes.cs +++ b/src/Tasks/ComReferenceItemAttributes.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/ComReferenceResolutionException.cs b/src/Tasks/ComReferenceResolutionException.cs index 7b5760fedd7..60839797eea 100644 --- a/src/Tasks/ComReferenceResolutionException.cs +++ b/src/Tasks/ComReferenceResolutionException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/ComReferenceTypes.cs b/src/Tasks/ComReferenceTypes.cs index 1b0eb4f3c02..e7fcdbe3b61 100644 --- a/src/Tasks/ComReferenceTypes.cs +++ b/src/Tasks/ComReferenceTypes.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/ComReferenceWrapperInfo.cs b/src/Tasks/ComReferenceWrapperInfo.cs index 0007cc0e64d..2f2b8ee261a 100644 --- a/src/Tasks/ComReferenceWrapperInfo.cs +++ b/src/Tasks/ComReferenceWrapperInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using Microsoft.Build.Shared; diff --git a/src/Tasks/CombinePath.cs b/src/Tasks/CombinePath.cs index b6e759aaeb3..e798dc6b265 100644 --- a/src/Tasks/CombinePath.cs +++ b/src/Tasks/CombinePath.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/CombineTargetFrameworkInfoProperties.cs b/src/Tasks/CombineTargetFrameworkInfoProperties.cs index 4108feb5246..3d8eff50d94 100644 --- a/src/Tasks/CombineTargetFrameworkInfoProperties.cs +++ b/src/Tasks/CombineTargetFrameworkInfoProperties.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Tasks/CombineXmlElements.cs b/src/Tasks/CombineXmlElements.cs index ca7525a92ac..e2cf53fe52c 100644 --- a/src/Tasks/CombineXmlElements.cs +++ b/src/Tasks/CombineXmlElements.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using System.Xml.Linq; diff --git a/src/Tasks/CommandLineBuilderExtension.cs b/src/Tasks/CommandLineBuilderExtension.cs index c07634ce739..b5ab47e0073 100644 --- a/src/Tasks/CommandLineBuilderExtension.cs +++ b/src/Tasks/CommandLineBuilderExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -36,12 +36,10 @@ public CommandLineBuilderExtension(bool quoteHyphensOnCommandLine, bool useNewLi /// /// Set a boolean switch iff its value exists and its value is 'true'. /// - internal void AppendWhenTrue - ( + internal void AppendWhenTrue( string switchName, Hashtable bag, - string parameterName - ) + string parameterName) { object obj = bag[parameterName]; // If the switch isn't set, don't add it to the command line. @@ -59,12 +57,10 @@ string parameterName /// /// Set a boolean switch only if its value exists. /// - internal void AppendPlusOrMinusSwitch - ( + internal void AppendPlusOrMinusSwitch( string switchName, Hashtable bag, - string parameterName - ) + string parameterName) { object obj = bag[parameterName]; // If the switch isn't set, don't add it to the command line. @@ -79,11 +75,9 @@ string parameterName /// /// Set a boolean switch only if its value exists. /// - internal void AppendPlusOrMinusSwitch - ( + internal void AppendPlusOrMinusSwitch( string switchName, - bool? value - ) + bool? value) { if (value.HasValue) { @@ -95,14 +89,12 @@ internal void AppendPlusOrMinusSwitch /// /// Set a switch if its value exists by choosing from the input choices /// - internal void AppendByChoiceSwitch - ( + internal void AppendByChoiceSwitch( string switchName, Hashtable bag, string parameterName, string choice1, - string choice2 - ) + string choice2) { object obj = bag[parameterName]; // If the switch isn't set, don't add it to the command line. @@ -116,12 +108,10 @@ string choice2 /// /// Set an integer switch only if its value exists. /// - internal void AppendSwitchWithInteger - ( + internal void AppendSwitchWithInteger( string switchName, Hashtable bag, - string parameterName - ) + string parameterName) { object obj = bag[parameterName]; // If the switch isn't set, don't add it to the command line. @@ -178,12 +168,10 @@ protected string GetQuotedText(string unquotedText) /// /// /// - internal void AppendSwitchIfNotNull - ( + internal void AppendSwitchIfNotNull( string switchName, ITaskItem[] parameters, - string[] attributes - ) + string[] attributes) { AppendSwitchIfNotNull(switchName, parameters, attributes, null /* treatAsFlag */); } @@ -239,20 +227,16 @@ internal static bool IsParameterEmpty(string parameter, params char[] splitOn) /// /// /// - internal void AppendSwitchIfNotNull - ( + internal void AppendSwitchIfNotNull( string switchName, ITaskItem[] parameters, string[] metadataNames, - bool[] treatAsFlags // May be null. In this case no metadata are treated as flags. - ) + bool[] treatAsFlags) // May be null. In this case no metadata are treated as flags. { - ErrorUtilities.VerifyThrow - ( + ErrorUtilities.VerifyThrow( treatAsFlags == null || (metadataNames != null && metadataNames.Length == treatAsFlags.Length), - "metadataNames and treatAsFlags should have the same length." - ); + "metadataNames and treatAsFlags should have the same length."); if (parameters != null) { @@ -312,11 +296,9 @@ internal void AppendSwitchIfNotNull /// /// Appends a switch if the specified value is true. /// - internal void AppendSwitchIfTrue - ( + internal void AppendSwitchIfTrue( string switchName, - bool? value - ) + bool? value) { if (value.HasValue && value.Value) { diff --git a/src/Tasks/ConvertToAbsolutePath.cs b/src/Tasks/ConvertToAbsolutePath.cs index a8985aefcdc..079a730a94a 100644 --- a/src/Tasks/ConvertToAbsolutePath.cs +++ b/src/Tasks/ConvertToAbsolutePath.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/Copy.cs b/src/Tasks/Copy.cs index dab3ddb553a..eefeb02668e 100644 --- a/src/Tasks/Copy.cs +++ b/src/Tasks/Copy.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -170,11 +170,9 @@ public void Cancel() /// /// The source file /// The destination file - private static bool IsMatchingSizeAndTimeStamp - ( + private static bool IsMatchingSizeAndTimeStamp( FileState sourceFile, - FileState destinationFile - ) + FileState destinationFile) { // If the destination doesn't exist, then it is not a matching file. if (!destinationFile.FileExists) @@ -224,11 +222,9 @@ private void LogDiagnostic(string message, params object[] messageArgs) /// leave the file read-write. /// /// Return true to indicate success, return false to indicate failure and NO retry, return NULL to indicate retry. - private bool? CopyFileWithLogging - ( + private bool? CopyFileWithLogging( FileState sourceFileState, // The source file - FileState destinationFileState // The destination file - ) + FileState destinationFileState) // The destination file { bool destinationFileExists = false; @@ -394,11 +390,9 @@ private void MakeFileWriteable(FileState file, bool logActivity) /// /// Thread parallelism allowed during copies. 1 uses the original algorithm, >1 uses newer algorithm. /// - internal bool Execute - ( + internal bool Execute( CopyFileWithState copyFile, - int parallelism - ) + int parallelism) { // If there are no source files then just return success. if (SourceFiles == null || SourceFiles.Length == 0) @@ -743,8 +737,7 @@ private bool DoCopyIfNecessary(FileState sourceFileState, FileState destinationF sourceFileState.Name, destinationFileState.Name, "SkipUnchangedFiles", - "true" - ); + "true"); MSBuildEventSource.Log.CopyUpToDateStop(destinationFileState.Name, true); } // We only do the cheap check for identicalness here, we try the more expensive check diff --git a/src/Tasks/CreateCSharpManifestResourceName.cs b/src/Tasks/CreateCSharpManifestResourceName.cs index 3ba09011657..e2be751c69d 100644 --- a/src/Tasks/CreateCSharpManifestResourceName.cs +++ b/src/Tasks/CreateCSharpManifestResourceName.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -30,14 +30,12 @@ public class CreateCSharpManifestResourceName : CreateManifestResourceName /// The file name of the parent of this dependency (usually a .cs file). May be null /// File contents binary stream, may be null /// Returns the manifest name - protected override string CreateManifestName - ( + protected override string CreateManifestName( string fileName, string linkFileName, string rootNamespace, string dependentUponFileName, - Stream binaryStream - ) + Stream binaryStream) { string culture = null; bool treatAsCultureNeutral = false; @@ -55,8 +53,7 @@ The reason is that CreateManifestName can't be static because it is an override of a method declared in the base class, but its convenient to expose a static version anyway for unittesting purposes. */ - return CreateManifestNameImpl - ( + return CreateManifestNameImpl( fileName, linkFileName, PrependCultureAsDirectory, @@ -65,8 +62,7 @@ The reason is that CreateManifestName can't be static because it is an culture, binaryStream, Log, - treatAsCultureNeutral - ); + treatAsCultureNeutral); } /// @@ -86,8 +82,7 @@ The reason is that CreateManifestName can't be static because it is an /// Task's TaskLoggingHelper, for logging warnings or errors /// Whether to treat the current file as 'culture-neutral' and retain the culture in the name. /// Returns the manifest name - internal static string CreateManifestNameImpl - ( + internal static string CreateManifestNameImpl( string fileName, string linkFileName, bool prependCultureAsDirectory, // true by default @@ -96,8 +91,7 @@ internal static string CreateManifestNameImpl string culture, // may be null Stream binaryStream, // File contents binary stream, may be null TaskLoggingHelper log, - bool treatAsCultureNeutral = false - ) + bool treatAsCultureNeutral = false) { // Use the link file name if there is one, otherwise, fall back to file name. string embeddedFileName = FileUtilities.FixFilePath(linkFileName); @@ -161,8 +155,7 @@ internal static string CreateManifestNameImpl || string.Equals(sourceExtension, restextFileExtension, StringComparison.OrdinalIgnoreCase) || - string.Equals(sourceExtension, resourcesFileExtension, StringComparison.OrdinalIgnoreCase) - ) + string.Equals(sourceExtension, resourcesFileExtension, StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrEmpty(directoryName)) { diff --git a/src/Tasks/CreateItem.cs b/src/Tasks/CreateItem.cs index 2ab2cf25397..8c7f8962e96 100644 --- a/src/Tasks/CreateItem.cs +++ b/src/Tasks/CreateItem.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -105,8 +105,7 @@ private List CreateOutputItems(Dictionary metadataTab { if ( (excludeItems.Count == 0) || // minor perf optimization - (!excludeItems.ContainsKey(i.ItemSpec)) - ) + (!excludeItems.ContainsKey(i.ItemSpec))) { ITaskItem newItem = i; if (metadataTable != null) diff --git a/src/Tasks/CreateManifestResourceName.cs b/src/Tasks/CreateManifestResourceName.cs index 49d1b38bd52..e271d7f6a29 100644 --- a/src/Tasks/CreateManifestResourceName.cs +++ b/src/Tasks/CreateManifestResourceName.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -85,14 +85,12 @@ public ITaskItem[] ResourceFiles /// The file name of the parent of this dependency. May be null /// File contents binary stream, may be null /// Returns the manifest name - protected abstract string CreateManifestName - ( + protected abstract string CreateManifestName( string fileName, string linkFileName, string rootNamespaceName, string dependentUponFileName, - Stream binaryStream - ); + Stream binaryStream); /// /// The derived class chooses whether this is a valid source file to work against. @@ -120,10 +118,8 @@ private static Stream CreateFileStreamOverNewFileStream(string path, FileMode mo /// /// CreateFileStream delegate /// True if task succeeded. - internal bool Execute - ( - CreateFileStream createFileStream - ) + internal bool Execute( + CreateFileStream createFileStream) { ManifestResourceNames = new ITaskItem[ResourceFiles.Length]; ResourceFilesWithManifestResourceNames = new ITaskItem[ResourceFiles.Length]; @@ -217,14 +213,12 @@ CreateFileStream createFileStream // we're done with it. using (binaryStream) { - manifestName = CreateManifestName - ( + manifestName = CreateManifestName( fileName, resourceFile.GetMetadata(ItemMetadataNames.targetPath), RootNamespace, isDependentOnSourceFile ? dependentUpon : null, - binaryStream - ); + binaryStream); } // Emit an item with our manifest name. diff --git a/src/Tasks/CreateProperty.cs b/src/Tasks/CreateProperty.cs index 5f9b2c7090b..a06e4b5a384 100644 --- a/src/Tasks/CreateProperty.cs +++ b/src/Tasks/CreateProperty.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/CreateVisualBasicManifestResourceName.cs b/src/Tasks/CreateVisualBasicManifestResourceName.cs index 27c60d89d2a..11ccf11e3a6 100644 --- a/src/Tasks/CreateVisualBasicManifestResourceName.cs +++ b/src/Tasks/CreateVisualBasicManifestResourceName.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -28,14 +28,12 @@ public class CreateVisualBasicManifestResourceName : CreateManifestResourceName /// The file name of the parent of this dependency (usually a .vb file). May be null /// File contents binary stream, may be null /// Returns the manifest name - protected override string CreateManifestName - ( + protected override string CreateManifestName( string fileName, string linkFileName, string rootNamespace, // May be null string dependentUponFileName, // May be null - Stream binaryStream // File contents binary stream, may be null - ) + Stream binaryStream) // File contents binary stream, may be null { string culture = null; bool treatAsCultureNeutral = false; @@ -53,8 +51,7 @@ The reason is that CreateManifestName can't be static because it is an override of a method declared in the base class, but its convenient to expose a static version anyway for unittesting purposes. */ - return CreateManifestNameImpl - ( + return CreateManifestNameImpl( fileName, linkFileName, PrependCultureAsDirectory, @@ -63,8 +60,7 @@ The reason is that CreateManifestName can't be static because it is an culture, binaryStream, Log, - treatAsCultureNeutral - ); + treatAsCultureNeutral); } /// @@ -84,8 +80,7 @@ The reason is that CreateManifestName can't be static because it is an /// Task's TaskLoggingHelper, for logging warnings or errors /// Whether to treat the current file as 'culture-neutral' and retain the culture in the name. /// Returns the manifest name - internal static string CreateManifestNameImpl - ( + internal static string CreateManifestNameImpl( string fileName, string linkFileName, bool prependCultureAsDirectory, // true by default @@ -94,8 +89,7 @@ internal static string CreateManifestNameImpl string culture, Stream binaryStream, // File contents binary stream, may be null TaskLoggingHelper log, - bool treatAsCultureNeutral = false - ) + bool treatAsCultureNeutral = false) { // Use the link file name if there is one, otherwise, fall back to file name. string embeddedFileName = linkFileName; @@ -160,8 +154,7 @@ internal static string CreateManifestNameImpl || string.Equals(sourceExtension, restextFileExtension, StringComparison.OrdinalIgnoreCase) || - string.Equals(sourceExtension, resourcesFileExtension, StringComparison.OrdinalIgnoreCase) - ) + string.Equals(sourceExtension, resourcesFileExtension, StringComparison.OrdinalIgnoreCase)) { manifestName.Append(Path.GetFileNameWithoutExtension(info.cultureNeutralFilename)); diff --git a/src/Tasks/Culture.cs b/src/Tasks/Culture.cs index f138332472b..7a97922bffe 100644 --- a/src/Tasks/Culture.cs +++ b/src/Tasks/Culture.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -28,12 +28,10 @@ internal struct ItemCultureInfo /// /// We've decided to ignore explicit Culture attributes on items. /// - internal static ItemCultureInfo GetItemCultureInfo - ( + internal static ItemCultureInfo GetItemCultureInfo( string name, string dependentUponFilename, - bool treatAsCultureNeutral = false - ) + bool treatAsCultureNeutral = false) { ItemCultureInfo info; info.culture = null; diff --git a/src/Tasks/CultureInfoCache.cs b/src/Tasks/CultureInfoCache.cs index 0c2a3672ad0..476c2b52ae6 100644 --- a/src/Tasks/CultureInfoCache.cs +++ b/src/Tasks/CultureInfoCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// 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.Collections.Generic; @@ -29,9 +29,9 @@ internal static class CultureInfoCache // These pseudo-locales are available in versions of Windows from Vista and later. // However, from Windows 10, version 1803, they are not returned when enumerating the // installed cultures, even if the registry keys are set. Therefore, add them to the list manually. - static readonly string[] pseudoLocales = new[] { "qps-ploc", "qps-ploca", "qps-plocm", "qps-Latn-x-sh" }; + private static readonly string[] pseudoLocales = new[] { "qps-ploc", "qps-ploca", "qps-plocm", "qps-Latn-x-sh" }; - static HashSet InitializeValidCultureNames() + private static HashSet InitializeValidCultureNames() { #if !FEATURE_CULTUREINFO_GETCULTURES if (!AssemblyUtilities.CultureInfoHasGetCultures()) diff --git a/src/Tasks/Delegate.cs b/src/Tasks/Delegate.cs index d8baa8ef059..61b226008e3 100644 --- a/src/Tasks/Delegate.cs +++ b/src/Tasks/Delegate.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -89,14 +89,12 @@ namespace Microsoft.Build.Tasks /// Receives the list of dependencies. /// Receives the list of associated scatter files. /// The framework name - internal delegate void GetAssemblyMetadata - ( + internal delegate void GetAssemblyMetadata( string path, ConcurrentDictionary assemblyMetadataCache, out AssemblyNameExtension[] dependencies, out string[] scatterFiles, - out FrameworkName frameworkNameAttribute - ); + out FrameworkName frameworkNameAttribute); /// /// Delegate to take in a dll path and read the machine type from the PEHeader diff --git a/src/Tasks/Delete.cs b/src/Tasks/Delete.cs index 2592f6f13d8..bd782dd8bae 100644 --- a/src/Tasks/Delete.cs +++ b/src/Tasks/Delete.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/DependencyFile.cs b/src/Tasks/DependencyFile.cs index c3d4ab2f05a..359a2dc7b03 100644 --- a/src/Tasks/DependencyFile.cs +++ b/src/Tasks/DependencyFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/DownloadFile.cs b/src/Tasks/DownloadFile.cs index c36685242c8..c4152670c81 100644 --- a/src/Tasks/DownloadFile.cs +++ b/src/Tasks/DownloadFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; @@ -90,10 +90,10 @@ private async Task ExecuteAsync() } int retryAttemptCount = 0; - + CancellationToken cancellationToken = _cancellationTokenSource.Token; - while(true) + while (true) { try { @@ -191,12 +191,13 @@ private async Task DownloadAsync(Uri uri, CancellationToken cancellationToken) using (var target = new FileStream(destinationFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None)) { Log.LogMessageFromResources(MessageImportance.High, "DownloadFile.Downloading", SourceUrl, destinationFile.FullName, response.Content.Headers.ContentLength); - +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter using (Stream responseStream = await response.Content.ReadAsStreamAsync( #if NET6_0_OR_GREATER cancellationToken #endif ).ConfigureAwait(false)) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { await responseStream.CopyToAsync(target, 1024, cancellationToken).ConfigureAwait(false); } diff --git a/src/Tasks/Error.cs b/src/Tasks/Error.cs index cbcfe08df2a..8cbca5f2ebd 100644 --- a/src/Tasks/Error.cs +++ b/src/Tasks/Error.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/ErrorFromResources.cs b/src/Tasks/ErrorFromResources.cs index a3b866674e9..b143db2d35e 100644 --- a/src/Tasks/ErrorFromResources.cs +++ b/src/Tasks/ErrorFromResources.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/Exec.cs b/src/Tasks/Exec.cs index 9e6eca86c59..afc49604a4e 100644 --- a/src/Tasks/Exec.cs +++ b/src/Tasks/Exec.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -57,7 +57,7 @@ public Exec() private string _command; // '^' before _any_ character escapes that character, don't escape it. - private static readonly char[] _charactersToEscape = { '(', ')', '=', ';', '!', ',', '&', ' '}; + private static readonly char[] _charactersToEscape = { '(', ')', '=', ';', '!', ',', '&', ' ' }; #endregion diff --git a/src/Tasks/ExtractedClassName.cs b/src/Tasks/ExtractedClassName.cs index d5288eddbe8..803d60a2add 100644 --- a/src/Tasks/ExtractedClassName.cs +++ b/src/Tasks/ExtractedClassName.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/FileIO/GetFileHash.cs b/src/Tasks/FileIO/GetFileHash.cs index ab35b01b7b5..23ae783b33f 100644 --- a/src/Tasks/FileIO/GetFileHash.cs +++ b/src/Tasks/FileIO/GetFileHash.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/FileIO/HashEncoding.cs b/src/Tasks/FileIO/HashEncoding.cs index bf7939b93ed..b8f39cadcbc 100644 --- a/src/Tasks/FileIO/HashEncoding.cs +++ b/src/Tasks/FileIO/HashEncoding.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/FileIO/ReadLinesFromFile.cs b/src/Tasks/FileIO/ReadLinesFromFile.cs index 80690b87af2..083e8a5ad97 100644 --- a/src/Tasks/FileIO/ReadLinesFromFile.cs +++ b/src/Tasks/FileIO/ReadLinesFromFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/FileIO/VerifyFileHash.cs b/src/Tasks/FileIO/VerifyFileHash.cs index 5d3739da436..11b168b7cd2 100644 --- a/src/Tasks/FileIO/VerifyFileHash.cs +++ b/src/Tasks/FileIO/VerifyFileHash.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/FileIO/WriteLinesToFile.cs b/src/Tasks/FileIO/WriteLinesToFile.cs index 1d8df91c6be..f7cc3a3c2dc 100644 --- a/src/Tasks/FileIO/WriteLinesToFile.cs +++ b/src/Tasks/FileIO/WriteLinesToFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Eventing; using Microsoft.Build.Framework; diff --git a/src/Tasks/FileState.cs b/src/Tasks/FileState.cs index 6d59494bb8d..f992f7bc76b 100644 --- a/src/Tasks/FileState.cs +++ b/src/Tasks/FileState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/FindAppConfigFile.cs b/src/Tasks/FindAppConfigFile.cs index 29107b7a10d..f8b1332e062 100644 --- a/src/Tasks/FindAppConfigFile.cs +++ b/src/Tasks/FindAppConfigFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/FindInList.cs b/src/Tasks/FindInList.cs index 1c3dac664af..6ce91dcfd3b 100644 --- a/src/Tasks/FindInList.cs +++ b/src/Tasks/FindInList.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/FindInvalidProjectReferences.cs b/src/Tasks/FindInvalidProjectReferences.cs index 84a92a0147a..d49ad88dfb8 100644 --- a/src/Tasks/FindInvalidProjectReferences.cs +++ b/src/Tasks/FindInvalidProjectReferences.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -21,11 +21,9 @@ public class FindInvalidProjectReferences : TaskExtension /// Regex for breaking up the platform moniker /// Example: XNA, Version=8.0 /// - private static readonly Regex s_platformMonikerFormat = new Regex - ( + private static readonly Regex s_platformMonikerFormat = new Regex( @"(?^[^,]*),\s*Version=(?.*)", - RegexOptions.IgnoreCase - ); + RegexOptions.IgnoreCase); /// /// Reference moniker metadata diff --git a/src/Tasks/FormatUrl.cs b/src/Tasks/FormatUrl.cs index d6d344db19e..8dc8abab226 100644 --- a/src/Tasks/FormatUrl.cs +++ b/src/Tasks/FormatUrl.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/FormatVersion.cs b/src/Tasks/FormatVersion.cs index e0d68649b16..88cfc595cb5 100644 --- a/src/Tasks/FormatVersion.cs +++ b/src/Tasks/FormatVersion.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Tasks/GenerateApplicationManifest.cs b/src/Tasks/GenerateApplicationManifest.cs index a6361b25472..56424601861 100644 --- a/src/Tasks/GenerateApplicationManifest.cs +++ b/src/Tasks/GenerateApplicationManifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -133,7 +133,10 @@ protected override bool OnManifestLoaded(Manifest manifest) protected override bool OnManifestResolved(Manifest manifest) { if (UseApplicationTrust) + { return BuildResolvedSettings(manifest as ApplicationManifest); + } + return true; } diff --git a/src/Tasks/GenerateBootstrapper.cs b/src/Tasks/GenerateBootstrapper.cs index 85b3cdf2fde..5a3b8da3e1b 100644 --- a/src/Tasks/GenerateBootstrapper.cs +++ b/src/Tasks/GenerateBootstrapper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/GenerateDeploymentManifest.cs b/src/Tasks/GenerateDeploymentManifest.cs index 6867f27717b..827699955c9 100644 --- a/src/Tasks/GenerateDeploymentManifest.cs +++ b/src/Tasks/GenerateDeploymentManifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Tasks/GenerateLauncher.cs b/src/Tasks/GenerateLauncher.cs index 683736168cc..865e5528331 100644 --- a/src/Tasks/GenerateLauncher.cs +++ b/src/Tasks/GenerateLauncher.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -69,7 +69,7 @@ public override bool Execute() // If the EntryPoint specified is apphost.exe or singlefilehost.exe, we need to replace the EntryPoint // with the AssemblyName instead since apphost.exe/singlefilehost.exe is an intermediate file for // for final published {assemblyname}.exe. - if ((entryPointFileName.Equals(Constants.AppHostExe, StringComparison.InvariantCultureIgnoreCase) || + if ((entryPointFileName.Equals(Constants.AppHostExe, StringComparison.InvariantCultureIgnoreCase) || entryPointFileName.Equals(Constants.SingleFileHostExe, StringComparison.InvariantCultureIgnoreCase)) && !string.IsNullOrEmpty(AssemblyName)) { diff --git a/src/Tasks/GenerateManifestBase.cs b/src/Tasks/GenerateManifestBase.cs index ef8aed08163..7fdafde410b 100644 --- a/src/Tasks/GenerateManifestBase.cs +++ b/src/Tasks/GenerateManifestBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Tasks/GenerateResource.cs b/src/Tasks/GenerateResource.cs index 5d7ef6a9107..fe22b568293 100644 --- a/src/Tasks/GenerateResource.cs +++ b/src/Tasks/GenerateResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.CodeDom; @@ -56,7 +56,7 @@ namespace Microsoft.Build.Tasks public sealed partial class GenerateResource : TaskExtension { -#region Fields + #region Fields // This cache helps us track the linked resource files listed inside of a resx resource file private ResGenDependencies _cache; @@ -164,9 +164,9 @@ public sealed partial class GenerateResource : TaskExtension /// private List _satelliteInputs; -#endregion // fields + #endregion // fields -#region Properties + #region Properties /// /// The names of the items to be converted. The extension must be one of the @@ -536,7 +536,7 @@ public string OutputDirectory set; } -#endregion // properties + #endregion // properties /// /// Simple public constructor. @@ -570,11 +570,9 @@ private void LogResgenCommandLine(List inputFiles, List ou { if (!ExtractResWFiles) { - commandLineBuilder.AppendFileNamesIfNotNull - ( + commandLineBuilder.AppendFileNamesIfNotNull( new string[] { inputFiles[i].ItemSpec, outputFiles[i].ItemSpec }, - "," - ); + ","); } else { @@ -589,12 +587,10 @@ private void LogResgenCommandLine(List inputFiles, List ou commandLineBuilder.AppendFileNamesIfNotNull(outputFiles.ToArray(), " "); // append the strongly-typed resource details - commandLineBuilder.AppendSwitchIfNotNull - ( + commandLineBuilder.AppendSwitchIfNotNull( "/str:", new string[] { StronglyTypedLanguage, StronglyTypedNamespace, StronglyTypedClassName, StronglyTypedFileName }, - "," - ); + ","); } Log.LogCommandLine(MessageImportance.Low, commandLineBuilder.ToString()); @@ -774,18 +770,14 @@ public override bool Execute() // create the list that we'll use to disconnect the taskitems once we're done _remotedTaskItems = new List(); - appDomain = AppDomain.CreateDomain - ( + appDomain = AppDomain.CreateDomain( "generateResourceAppDomain", null, - AppDomain.CurrentDomain.SetupInformation - ); + AppDomain.CurrentDomain.SetupInformation); - object obj = appDomain.CreateInstanceFromAndUnwrap - ( + object obj = appDomain.CreateInstanceFromAndUnwrap( typeof(ProcessResourceFiles).Module.FullyQualifiedName, - typeof(ProcessResourceFiles).FullName - ); + typeof(ProcessResourceFiles).FullName); Type processType = obj.GetType(); ErrorUtilities.VerifyThrow(processType == typeof(ProcessResourceFiles), "Somehow got a wrong and possibly incompatible type for ProcessResourceFiles."); @@ -1216,11 +1208,9 @@ private int CalculateResourceBatchSize(List inputsToProcess, List /// List of readers used for input. /// @@ -2357,7 +2337,7 @@ internal bool StronglyTypedResourceSuccessfullyCreated /// private bool _useSourcePath = false; -#endregion + #endregion /// /// Process all files. @@ -2721,7 +2701,7 @@ e is SerializationException || && GetFormat(inFile) != Format.Assembly // outFileOrDir is a directory when the input file is an assembly && GetFormat(outFileOrDir) != Format.Assembly) - // Never delete an assembly since we don't ever actually write to assemblies. + // Never delete an assembly since we don't ever actually write to assemblies. { RemoveCorruptedFile(outFileOrDir); } @@ -3077,9 +3057,7 @@ internal void ReadAssemblyResources(String name, String outFileOrDir) targetFrameworkAttribute != null && ( targetFrameworkAttribute.FrameworkName.StartsWith("Silverlight,", StringComparison.OrdinalIgnoreCase) || - targetFrameworkAttribute.FrameworkName.StartsWith("WindowsPhone,", StringComparison.OrdinalIgnoreCase) - ) - ) + targetFrameworkAttribute.FrameworkName.StartsWith("WindowsPhone,", StringComparison.OrdinalIgnoreCase))) { // Skip Silverlight assemblies. _logger.LogMessageFromResources("GenerateResource.SkippingExtractingFromNonSupportedFramework", name, targetFrameworkAttribute.FrameworkName); @@ -3132,13 +3110,17 @@ internal void ReadAssemblyResources(String name, String outFileOrDir) { satCulture = assemblyName.CultureInfo; if (!satCulture.Equals(CultureInfo.InvariantCulture)) + { expectedExt = '.' + satCulture.Name + ".resources"; + } } foreach (String resName in resources) { if (!resName.EndsWith(".resources", StringComparison.OrdinalIgnoreCase)) // Skip non-.resources assembly blobs + { continue; + } if (mainAssembly) { @@ -3190,7 +3172,9 @@ internal void ReadAssemblyResources(String name, String outFileOrDir) { // Remove the culture from the filename if (reader.outputFileName.EndsWith("." + reader.cultureName, StringComparison.OrdinalIgnoreCase)) + { reader.outputFileName = reader.outputFileName.Remove(reader.outputFileName.Length - (reader.cultureName.Length + 1)); + } } _readers.Add(reader); @@ -3234,7 +3218,9 @@ private NeutralResourcesLanguageAttribute CheckAssemblyCultureInfo(String name, neutralResourcesLanguageAttribute = (NeutralResourcesLanguageAttribute)attrs[0]; bool fallbackToSatellite = neutralResourcesLanguageAttribute.Location == UltimateResourceFallbackLocation.Satellite; if (!fallbackToSatellite && neutralResourcesLanguageAttribute.Location != UltimateResourceFallbackLocation.MainAssembly) + { _logger.LogWarningWithCodeFromResources(null, name, 0, 0, 0, 0, "GenerateResource.UnrecognizedUltimateResourceFallbackLocation", neutralResourcesLanguageAttribute.Location, name); + } // This MSBuild task needs to not report an error for main assemblies that don't have managed resources. } } @@ -3253,7 +3239,9 @@ private NeutralResourcesLanguageAttribute CheckAssemblyCultureInfo(String name, } if (!ContainsProperlyNamedResourcesFiles(a, false)) + { _logger.LogWarningWithCodeFromResources("GenerateResource.SatelliteAssemblyContainsNoResourcesFile", assemblyName.CultureInfo.Name); + } } return neutralResourcesLanguageAttribute; } @@ -3264,7 +3252,9 @@ private static bool ContainsProperlyNamedResourcesFiles(Assembly a, bool mainAss foreach (String manifestResourceName in a.GetManifestResourceNames()) { if (manifestResourceName.EndsWith(postfix, StringComparison.OrdinalIgnoreCase)) + { return true; + } } return false; @@ -3422,8 +3412,7 @@ private void CreateStronglyTypedResources(ReaderInfo reader, String outFile, Str _stronglyTypedResourcesNamespace, provider, generateInternalClass, - out errors - ); + out errors); CodeGeneratorOptions codeGenOptions = new CodeGeneratorOptions(); using (TextWriter output = new StreamWriter(_stronglyTypedFilename)) @@ -3575,15 +3564,21 @@ private void ReadTextResources(ReaderInfo reader, String fileName) while (ch != '=') { if (ch == '\r' || ch == '\n') + { throw new TextFileException(_logger.FormatResourceString("GenerateResource.NoEqualsInLine", name), fileName, sr.LineNumber, sr.LinePosition); + } name.Append((char)ch); ch = sr.Read(); if (ch == -1) + { break; + } } if (name.Length == 0) + { throw new TextFileException(_logger.FormatResourceString("GenerateResource.NoNameInLine"), fileName, sr.LineNumber, sr.LinePosition); + } // For the INF file, we must allow a space on both sides of the equals // sign. Deal with it. @@ -3594,7 +3589,9 @@ private void ReadTextResources(ReaderInfo reader, String fileName) ch = sr.Read(); // move past = // If it exists, move past the first space after the equals sign. if (ch == ' ') + { ch = sr.Read(); + } // Read in value value.Length = 0; @@ -3633,7 +3630,10 @@ private void ReadTextResources(ReaderInfo reader, String fileName) { int n = sr.Read(hex, index, numChars); if (n == 0) + { throw new TextFileException(_logger.FormatResourceString("GenerateResource.InvalidEscape", name.ToString(), (char)ch), fileName, sr.LineNumber, sr.LinePosition); + } + index += n; numChars -= n; } @@ -3953,7 +3953,7 @@ internal int LinePosition get { return column; } } } -#endregion // Code from ResGen.EXE + #endregion // Code from ResGen.EXE } #if !FEATURE_ASSEMBLYLOADCONTEXT diff --git a/src/Tasks/GenerateTrustInfo.cs b/src/Tasks/GenerateTrustInfo.cs index 6f8c745bbf4..e6a6a1d43cc 100644 --- a/src/Tasks/GenerateTrustInfo.cs +++ b/src/Tasks/GenerateTrustInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/GetAssemblyIdentity.cs b/src/Tasks/GetAssemblyIdentity.cs index 92edc4a81af..1d5c78c929e 100644 --- a/src/Tasks/GetAssemblyIdentity.cs +++ b/src/Tasks/GetAssemblyIdentity.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/GetCompatiblePlatform.cs b/src/Tasks/GetCompatiblePlatform.cs index c68f60f13f9..4b4da73a3c0 100644 --- a/src/Tasks/GetCompatiblePlatform.cs +++ b/src/Tasks/GetCompatiblePlatform.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -50,7 +50,7 @@ public GetCompatiblePlatform() public override bool Execute() { - + AssignedProjectsWithPlatform = new ITaskItem[AnnotatedProjects.Length]; for (int i = 0; i < AnnotatedProjects.Length; i++) { diff --git a/src/Tasks/GetFrameworkPath.cs b/src/Tasks/GetFrameworkPath.cs index 5793e004a7c..93ac97f1f62 100644 --- a/src/Tasks/GetFrameworkPath.cs +++ b/src/Tasks/GetFrameworkPath.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/GetFrameworkSDKPath.cs b/src/Tasks/GetFrameworkSDKPath.cs index 99555f83897..86d0a2eaa83 100644 --- a/src/Tasks/GetFrameworkSDKPath.cs +++ b/src/Tasks/GetFrameworkSDKPath.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -44,8 +44,7 @@ public string Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Latest, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Latest, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Latest, VisualStudioVersion.VersionLatest)); s_path = String.Empty; } @@ -82,8 +81,7 @@ public string FrameworkSdkVersion20Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version20), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version20) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version20)); s_version20Path = String.Empty; } @@ -116,8 +114,7 @@ public string FrameworkSdkVersion35Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version35, VisualStudioVersion.VersionLatest)); s_version35Path = String.Empty; } @@ -150,8 +147,7 @@ public string FrameworkSdkVersion40Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version40, VisualStudioVersion.VersionLatest)); s_version40Path = String.Empty; } @@ -184,8 +180,7 @@ public string FrameworkSdkVersion45Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version45, VisualStudioVersion.VersionLatest)); s_version45Path = String.Empty; } @@ -218,8 +213,7 @@ public string FrameworkSdkVersion451Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version451, VisualStudioVersion.VersionLatest)); s_version451Path = String.Empty; } @@ -252,8 +246,7 @@ public string FrameworkSdkVersion46Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version46, VisualStudioVersion.VersionLatest)); s_version46Path = String.Empty; } @@ -286,8 +279,7 @@ public string FrameworkSdkVersion461Path MessageImportance.High, "GetFrameworkSdkPath.CouldNotFindSDK", ToolLocationHelper.GetDotNetFrameworkSdkInstallKeyValue(TargetDotNetFrameworkVersion.Version461, VisualStudioVersion.VersionLatest), - ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version461, VisualStudioVersion.VersionLatest) - ); + ToolLocationHelper.GetDotNetFrameworkSdkRootRegistryKey(TargetDotNetFrameworkVersion.Version461, VisualStudioVersion.VersionLatest)); s_version461Path = String.Empty; } diff --git a/src/Tasks/GetInstalledSDKLocations.cs b/src/Tasks/GetInstalledSDKLocations.cs index 3f6e9524661..011ce919725 100644 --- a/src/Tasks/GetInstalledSDKLocations.cs +++ b/src/Tasks/GetInstalledSDKLocations.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/GetReferenceAssemblyPaths.cs b/src/Tasks/GetReferenceAssemblyPaths.cs index f0be08e771c..08f3821f66c 100644 --- a/src/Tasks/GetReferenceAssemblyPaths.cs +++ b/src/Tasks/GetReferenceAssemblyPaths.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/GetSDKReferenceFiles.cs b/src/Tasks/GetSDKReferenceFiles.cs index 64afe2300aa..16985d1bb3d 100644 --- a/src/Tasks/GetSDKReferenceFiles.cs +++ b/src/Tasks/GetSDKReferenceFiles.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -249,8 +249,7 @@ internal bool Execute(GetAssemblyName getAssemblyName, GetAssemblyRuntimeVersion { // Filter out all references tagged as RuntimeReferenceOnly IEnumerable filteredResolvedSDKReferences = ResolvedSDKReferences.Where( - sdkReference => !MetadataConversionUtilities.TryConvertItemMetadataToBool(sdkReference, "RuntimeReferenceOnly") - ); + sdkReference => !MetadataConversionUtilities.TryConvertItemMetadataToBool(sdkReference, "RuntimeReferenceOnly")); PopulateReferencesForSDK(filteredResolvedSDKReferences); diff --git a/src/Tasks/Hash.cs b/src/Tasks/Hash.cs index 4e093b6e2b0..e333d727f84 100644 --- a/src/Tasks/Hash.cs +++ b/src/Tasks/Hash.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Security.Cryptography; diff --git a/src/Tasks/IAnalyzerHostObject.cs b/src/Tasks/IAnalyzerHostObject.cs index 31a9ee6a777..b82830f858e 100644 --- a/src/Tasks/IAnalyzerHostObject.cs +++ b/src/Tasks/IAnalyzerHostObject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Microsoft.Build.Framework; diff --git a/src/Tasks/IComReferenceResolver.cs b/src/Tasks/IComReferenceResolver.cs index d6c14afc2df..b8682a8eb22 100644 --- a/src/Tasks/IComReferenceResolver.cs +++ b/src/Tasks/IComReferenceResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // TYPELIBATTR clashes with the one in InteropServices. using TYPELIBATTR = System.Runtime.InteropServices.ComTypes.TYPELIBATTR; diff --git a/src/Tasks/ICscHostObject.cs b/src/Tasks/ICscHostObject.cs index ffb8654611c..de3f9b8fc08 100644 --- a/src/Tasks/ICscHostObject.cs +++ b/src/Tasks/ICscHostObject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Microsoft.Build.Framework; diff --git a/src/Tasks/ICscHostObject2.cs b/src/Tasks/ICscHostObject2.cs index b34b294351c..73e83478308 100644 --- a/src/Tasks/ICscHostObject2.cs +++ b/src/Tasks/ICscHostObject2.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/ICscHostObject3.cs b/src/Tasks/ICscHostObject3.cs index 7ade210735a..4d67b70246b 100644 --- a/src/Tasks/ICscHostObject3.cs +++ b/src/Tasks/ICscHostObject3.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/ICscHostObject4.cs b/src/Tasks/ICscHostObject4.cs index 7ce014ed29f..9609d7a29c0 100644 --- a/src/Tasks/ICscHostObject4.cs +++ b/src/Tasks/ICscHostObject4.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/IVbcHostObject.cs b/src/Tasks/IVbcHostObject.cs index 5c28314e04f..556b3e7ff9e 100644 --- a/src/Tasks/IVbcHostObject.cs +++ b/src/Tasks/IVbcHostObject.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; using Microsoft.Build.Framework; diff --git a/src/Tasks/IVbcHostObject2.cs b/src/Tasks/IVbcHostObject2.cs index 8d8faf1211a..f7e62ebba9e 100644 --- a/src/Tasks/IVbcHostObject2.cs +++ b/src/Tasks/IVbcHostObject2.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/IVbcHostObject3.cs b/src/Tasks/IVbcHostObject3.cs index ea4f5434f6c..05a7c3dc390 100644 --- a/src/Tasks/IVbcHostObject3.cs +++ b/src/Tasks/IVbcHostObject3.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/IVbcHostObject4.cs b/src/Tasks/IVbcHostObject4.cs index 9e73dd5581b..f67a6abd69a 100644 --- a/src/Tasks/IVbcHostObject4.cs +++ b/src/Tasks/IVbcHostObject4.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/IVbcHostObject5.cs b/src/Tasks/IVbcHostObject5.cs index bbf959e4f68..1921933c715 100644 --- a/src/Tasks/IVbcHostObject5.cs +++ b/src/Tasks/IVbcHostObject5.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Tasks/IVbcHostObjectFreeThreaded.cs b/src/Tasks/IVbcHostObjectFreeThreaded.cs index 21a0e1f0a80..c6a763f3224 100644 --- a/src/Tasks/IVbcHostObjectFreeThreaded.cs +++ b/src/Tasks/IVbcHostObjectFreeThreaded.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.InteropServices; diff --git a/src/Tasks/InstalledSDKResolver.cs b/src/Tasks/InstalledSDKResolver.cs index 58b97e46883..101d5b29dc2 100644 --- a/src/Tasks/InstalledSDKResolver.cs +++ b/src/Tasks/InstalledSDKResolver.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -33,8 +33,7 @@ public InstalledSDKResolver(Dictionary resolvedSDKs, string s /// /// Resolve references which are found in a specific SDK /// - public override bool Resolve - ( + public override bool Resolve( AssemblyNameExtension assemblyName, string sdkName, string rawFileNameCandidate, @@ -45,8 +44,7 @@ public override bool Resolve string assemblyFolderKey, List assembliesConsideredAndRejected, out string foundPath, - out bool userRequestedSpecificFile - ) + out bool userRequestedSpecificFile) { foundPath = null; userRequestedSpecificFile = false; diff --git a/src/Tasks/Interop.cs b/src/Tasks/Interop.cs index 8becf2ba00b..05c3243bc3d 100644 --- a/src/Tasks/Interop.cs +++ b/src/Tasks/Interop.cs @@ -1,4 +1,5 @@ -// This file is decompiled C# from an assembly generated by tlbimp against a copy of urlmon's idl file +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // UrlMonTypeLib.IInternetSecurityManager using System; @@ -9,31 +10,31 @@ [Guid("79EAC9EE-BAF9-11CE-8C82-00AA004BA90B")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComConversionLoss] -interface IInternetSecurityManager +internal interface IInternetSecurityManager { - [MethodImpl(MethodImplOptions.InternalCall)] - void SetSecuritySite([In] [MarshalAs(UnmanagedType.Interface)] IInternetSecurityMgrSite pSite); + [MethodImpl(MethodImplOptions.InternalCall)] + void SetSecuritySite([In][MarshalAs(UnmanagedType.Interface)] IInternetSecurityMgrSite pSite); - [MethodImpl(MethodImplOptions.InternalCall)] - void GetSecuritySite([MarshalAs(UnmanagedType.Interface)] out IInternetSecurityMgrSite ppSite); + [MethodImpl(MethodImplOptions.InternalCall)] + void GetSecuritySite([MarshalAs(UnmanagedType.Interface)] out IInternetSecurityMgrSite ppSite); - [MethodImpl(MethodImplOptions.InternalCall)] - void MapUrlToZone([In] [MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, out int pdwZone, [In] int dwFlags); + [MethodImpl(MethodImplOptions.InternalCall)] + void MapUrlToZone([In][MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, out int pdwZone, [In] int dwFlags); - [MethodImpl(MethodImplOptions.InternalCall)] - void GetSecurityId([In] [MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, out byte pbSecurityId, [In] [Out] ref int pcbSecurityId, [In] [ComAliasName("UrlMonTypeLib.ULONG_PTR")] int dwReserved); + [MethodImpl(MethodImplOptions.InternalCall)] + void GetSecurityId([In][MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, out byte pbSecurityId, [In][Out] ref int pcbSecurityId, [In][ComAliasName("UrlMonTypeLib.ULONG_PTR")] int dwReserved); - [MethodImpl(MethodImplOptions.InternalCall)] - void ProcessUrlAction([In] [MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [In] int dwAction, out byte pPolicy, [In] int cbPolicy, [In] ref byte pContext, [In] int cbContext, [In] int dwFlags, [In] int dwReserved); + [MethodImpl(MethodImplOptions.InternalCall)] + void ProcessUrlAction([In][MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [In] int dwAction, out byte pPolicy, [In] int cbPolicy, [In] ref byte pContext, [In] int cbContext, [In] int dwFlags, [In] int dwReserved); - [MethodImpl(MethodImplOptions.InternalCall)] - void QueryCustomPolicy([In] [MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [In] [ComAliasName("UrlMonTypeLib.GUID")] ref GUID guidKey, [Out] IntPtr ppPolicy, out int pcbPolicy, [In] ref byte pContext, [In] int cbContext, [In] int dwReserved); + [MethodImpl(MethodImplOptions.InternalCall)] + void QueryCustomPolicy([In][MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [In][ComAliasName("UrlMonTypeLib.GUID")] ref GUID guidKey, [Out] IntPtr ppPolicy, out int pcbPolicy, [In] ref byte pContext, [In] int cbContext, [In] int dwReserved); - [MethodImpl(MethodImplOptions.InternalCall)] - void SetZoneMapping([In] int dwZone, [In] [MarshalAs(UnmanagedType.LPWStr)] string lpszPattern, [In] int dwFlags); + [MethodImpl(MethodImplOptions.InternalCall)] + void SetZoneMapping([In] int dwZone, [In][MarshalAs(UnmanagedType.LPWStr)] string lpszPattern, [In] int dwFlags); - [MethodImpl(MethodImplOptions.InternalCall)] - void GetZoneMappings([In] int dwZone, [MarshalAs(UnmanagedType.Interface)] out IEnumString ppenumString, [In] int dwFlags); + [MethodImpl(MethodImplOptions.InternalCall)] + void GetZoneMappings([In] int dwZone, [MarshalAs(UnmanagedType.Interface)] out IEnumString ppenumString, [In] int dwFlags); } // UrlMonTypeLib.IInternetSecurityMgrSite @@ -41,17 +42,17 @@ interface IInternetSecurityManager [ComConversionLoss] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("79EAC9ED-BAF9-11CE-8C82-00AA004BA90B")] -interface IInternetSecurityMgrSite +internal interface IInternetSecurityMgrSite { [MethodImpl(MethodImplOptions.InternalCall)] - void GetWindow([Out] [ComAliasName("UrlMonTypeLib.wireHWND")] IntPtr phwnd); + void GetWindow([Out][ComAliasName("UrlMonTypeLib.wireHWND")] IntPtr phwnd); [MethodImpl(MethodImplOptions.InternalCall)] void EnableModeless([In] int fEnable); } [StructLayout(LayoutKind.Sequential, Pack = 4)] -struct GUID +internal struct GUID { public int Data1; @@ -66,7 +67,7 @@ struct GUID [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("00000101-0000-0000-C000-000000000046")] -interface IEnumString +internal interface IEnumString { [MethodImpl(MethodImplOptions.InternalCall)] void RemoteNext([In] int celt, [MarshalAs(UnmanagedType.LPWStr)] out string rgelt, out int pceltFetched); diff --git a/src/Tasks/InvalidParameterValueException.cs b/src/Tasks/InvalidParameterValueException.cs index 7b9f650b554..cfa9c9f52d6 100644 --- a/src/Tasks/InvalidParameterValueException.cs +++ b/src/Tasks/InvalidParameterValueException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/LC.cs b/src/Tasks/LC.cs index d219536f01d..f4d5e0e871e 100644 --- a/src/Tasks/LC.cs +++ b/src/Tasks/LC.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/ListOperators/FindUnderPath.cs b/src/Tasks/ListOperators/FindUnderPath.cs index 9168bc44376..b4e08b145e8 100644 --- a/src/Tasks/ListOperators/FindUnderPath.cs +++ b/src/Tasks/ListOperators/FindUnderPath.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/ListOperators/RemoveDuplicates.cs b/src/Tasks/ListOperators/RemoveDuplicates.cs index f1a806b7a77..6c47290af27 100644 --- a/src/Tasks/ListOperators/RemoveDuplicates.cs +++ b/src/Tasks/ListOperators/RemoveDuplicates.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/LockCheck.cs b/src/Tasks/LockCheck.cs index 237a138dd64..e158a09f092 100644 --- a/src/Tasks/LockCheck.cs +++ b/src/Tasks/LockCheck.cs @@ -1,5 +1,5 @@ -// Taken from https://github.com/cklutz/LockCheck, MIT license. -// Copyright (C) Christian Klutz +// 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.Collections.Generic; @@ -129,20 +129,19 @@ internal struct RM_UNIQUE_PROCESS public FILETIME ProcessStartTime; } - const int CCH_RM_MAX_APP_NAME = 255; - const int CCH_RM_MAX_SVC_NAME = 63; - const int ERROR_SEM_TIMEOUT = 121; - const int ERROR_BAD_ARGUMENTS = 160; - const int ERROR_MAX_SESSIONS_REACHED = 353; - const int ERROR_WRITE_FAULT = 29; - const int ERROR_OUTOFMEMORY = 14; - const int ERROR_MORE_DATA = 234; - const int ERROR_ACCESS_DENIED = 5; - const int ERROR_INVALID_HANDLE = 6; - const int ERROR_CANCELLED = 1223; - - static readonly int RM_SESSION_KEY_LEN = Guid.Empty.ToByteArray().Length; // 16-byte - static readonly int CCH_RM_SESSION_KEY = RM_SESSION_KEY_LEN * 2; + private const int CCH_RM_MAX_APP_NAME = 255; + private const int CCH_RM_MAX_SVC_NAME = 63; + private const int ERROR_SEM_TIMEOUT = 121; + private const int ERROR_BAD_ARGUMENTS = 160; + private const int ERROR_MAX_SESSIONS_REACHED = 353; + private const int ERROR_WRITE_FAULT = 29; + private const int ERROR_OUTOFMEMORY = 14; + private const int ERROR_MORE_DATA = 234; + private const int ERROR_ACCESS_DENIED = 5; + private const int ERROR_INVALID_HANDLE = 6; + private const int ERROR_CANCELLED = 1223; + private static readonly int RM_SESSION_KEY_LEN = Guid.Empty.ToByteArray().Length; // 16-byte + private static readonly int CCH_RM_SESSION_KEY = RM_SESSION_KEY_LEN * 2; internal enum RM_APP_TYPE { @@ -155,7 +154,7 @@ internal enum RM_APP_TYPE RmCritical = 1000 } - enum RM_APP_STATUS + private enum RM_APP_STATUS { RmStatusUnknown = 0x0, RmStatusRunning = 0x1, @@ -168,7 +167,7 @@ enum RM_APP_STATUS RmStatusRestartMasked = 0x80 } - enum RM_REBOOT_REASON + private enum RM_REBOOT_REASON { RmRebootReasonNone = 0x0, RmRebootReasonPermissionDenied = 0x1, @@ -327,7 +326,9 @@ internal static IEnumerable GetLockingProcessInfos(params string[] { res = RmEndSession(handle); if (res != 0) + { throw GetException(res, "RmEndSession", "Failed to end the restart manager session."); + } } return Enumerable.Empty(); diff --git a/src/Tasks/MSBuild.cs b/src/Tasks/MSBuild.cs index ea4213c9688..c4d32f8cfac 100644 --- a/src/Tasks/MSBuild.cs +++ b/src/Tasks/MSBuild.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -321,8 +321,7 @@ public override bool Execute() { singleProject[0] = project; - if (!ExecuteTargets - ( + if (!ExecuteTargets( singleProject, propertiesTable, undefinePropertiesArray, @@ -333,9 +332,7 @@ public override bool Execute() Log, _targetOutputs, UnloadProjectsOnCompletion, - ToolsVersion - ) - ) + ToolsVersion)) { success = false; } @@ -388,8 +385,7 @@ private bool BuildProjectsInParallel(Dictionary propertiesTable, // Make the call to build the projects if (projectsToBuildInParallel.Count > 0) { - if (!ExecuteTargets - ( + if (!ExecuteTargets( projectsToBuildInParallel, propertiesTable, undefinePropertiesArray, @@ -400,9 +396,7 @@ private bool BuildProjectsInParallel(Dictionary propertiesTable, Log, _targetOutputs, UnloadProjectsOnCompletion, - ToolsVersion - ) - ) + ToolsVersion)) { success = false; } @@ -481,8 +475,7 @@ internal static List CreateTargetLists(string[] targets, bool runEachT } /// True if the operation was successful - internal static bool ExecuteTargets - ( + internal static bool ExecuteTargets( List projects, Dictionary propertiesTable, string[] undefineProperties, @@ -493,8 +486,7 @@ internal static bool ExecuteTargets TaskLoggingHelper log, List targetOutputs, bool unloadProjectsOnCompletion, - string toolsVersion - ) + string toolsVersion) { bool success = true; @@ -524,10 +516,9 @@ string toolsVersion // parse the string containing the properties if (!String.IsNullOrEmpty(projects[i].GetMetadata("Properties"))) { - if (!PropertyParser.GetTableWithEscaping - (log, ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.OverridingProperties", projectNames[i]), "Properties", projects[i].GetMetadata("Properties").Split(MSBuildConstants.SemicolonChar), - out Dictionary preProjectPropertiesTable) - ) + if (!PropertyParser.GetTableWithEscaping( + log, ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.OverridingProperties", projectNames[i]), "Properties", projects[i].GetMetadata("Properties").Split(MSBuildConstants.SemicolonChar), + out Dictionary preProjectPropertiesTable)) { return false; } @@ -565,10 +556,9 @@ string toolsVersion // parse the string containing the properties if (!String.IsNullOrEmpty(projects[i].GetMetadata("AdditionalProperties"))) { - if (!PropertyParser.GetTableWithEscaping - (log, ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.AdditionalProperties", projectNames[i]), "AdditionalProperties", projects[i].GetMetadata("AdditionalProperties").Split(MSBuildConstants.SemicolonChar), - out Dictionary additionalProjectPropertiesTable) - ) + if (!PropertyParser.GetTableWithEscaping( + log, ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword("General.AdditionalProperties", projectNames[i]), "AdditionalProperties", projects[i].GetMetadata("AdditionalProperties").Split(MSBuildConstants.SemicolonChar), + out Dictionary additionalProjectPropertiesTable)) { return false; } diff --git a/src/Tasks/MakeDir.cs b/src/Tasks/MakeDir.cs index 131fdb2a47f..6cc263c7254 100644 --- a/src/Tasks/MakeDir.cs +++ b/src/Tasks/MakeDir.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/ManifestUtil/ApplicationIdentity.cs b/src/Tasks/ManifestUtil/ApplicationIdentity.cs index 8b7aec3900b..c5b3c682345 100644 --- a/src/Tasks/ManifestUtil/ApplicationIdentity.cs +++ b/src/Tasks/ManifestUtil/ApplicationIdentity.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; @@ -54,7 +54,10 @@ public ApplicationIdentity(string url, string deployManifestPath, string applica public ApplicationIdentity(string url, AssemblyIdentity deployManifestIdentity, AssemblyIdentity applicationManifestIdentity) { if (String.IsNullOrEmpty(url)) + { throw new ArgumentNullException(nameof(url)); + } + _url = url; _deployManifestIdentity = deployManifestIdentity ?? throw new ArgumentNullException(nameof(deployManifestIdentity)); _applicationManifestIdentity = applicationManifestIdentity ?? throw new ArgumentNullException(nameof(applicationManifestIdentity)); diff --git a/src/Tasks/ManifestUtil/ApplicationManifest.cs b/src/Tasks/ManifestUtil/ApplicationManifest.cs index 6997aeaadb7..6b7965b66e4 100644 --- a/src/Tasks/ManifestUtil/ApplicationManifest.cs +++ b/src/Tasks/ManifestUtil/ApplicationManifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -278,7 +278,11 @@ public string OSVersion { get { - if (String.IsNullOrEmpty(_oSMajor)) return null; + if (String.IsNullOrEmpty(_oSMajor)) + { + return null; + } + Version v; try { @@ -435,7 +439,7 @@ private void ValidateCom() { if (assembly.ReferenceType == AssemblyReferenceType.NativeAssembly && !assembly.IsPrerequisite && !String.IsNullOrEmpty(assembly.ResolvedPath)) { - ComInfo[] comInfoArray = ManifestReader.GetComInfo(assembly.ResolvedPath); + ComInfo[] comInfoArray = ManifestReader.GetComInfo(assembly.ResolvedPath); if (comInfoArray != null) { foreach (ComInfo comInfo in comInfoArray) @@ -509,9 +513,16 @@ private void ValidateCom() private void ValidateConfig() { - if (String.IsNullOrEmpty(ConfigFile)) return; + if (String.IsNullOrEmpty(ConfigFile)) + { + return; + } + FileReference configFile = FileReferences.FindTargetPath(ConfigFile); - if (configFile == null) return; + if (configFile == null) + { + return; + } if (!TrustInfo.IsFullTrust) { diff --git a/src/Tasks/ManifestUtil/AssemblyIdentity.cs b/src/Tasks/ManifestUtil/AssemblyIdentity.cs index 66261651f2c..63658f51f7f 100644 --- a/src/Tasks/ManifestUtil/AssemblyIdentity.cs +++ b/src/Tasks/ManifestUtil/AssemblyIdentity.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; using System; @@ -144,7 +144,10 @@ public AssemblyIdentity(string name, string version, string publicKeyToken, stri public AssemblyIdentity(AssemblyIdentity identity) { if (identity == null) + { return; + } + _name = identity._name; _version = identity._version; _publicKeyToken = identity._publicKeyToken; diff --git a/src/Tasks/ManifestUtil/AssemblyManifest.cs b/src/Tasks/ManifestUtil/AssemblyManifest.cs index e55a2ede807..6ad61fdd4d6 100644 --- a/src/Tasks/ManifestUtil/AssemblyManifest.cs +++ b/src/Tasks/ManifestUtil/AssemblyManifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Runtime.InteropServices; diff --git a/src/Tasks/ManifestUtil/AssemblyReference.cs b/src/Tasks/ManifestUtil/AssemblyReference.cs index 702790b55d4..129cc6fee6f 100644 --- a/src/Tasks/ManifestUtil/AssemblyReference.cs +++ b/src/Tasks/ManifestUtil/AssemblyReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; @@ -86,11 +86,18 @@ internal bool IsVirtual get { if (AssemblyIdentity == null) + { return false; + } + if (String.Equals(AssemblyIdentity.Name, Constants.CLRPlatformAssemblyName, StringComparison.OrdinalIgnoreCase)) + { return true; + } else + { return false; + } } } @@ -120,14 +127,24 @@ protected internal override string SortName get { if (_assemblyIdentity == null) + { return null; + } + string name = _assemblyIdentity.ToString(); if (IsVirtual) + { name = "1: " + name; // virtual assemblies are first + } else if (_isPrerequisite) + { name = "2: " + name; // prerequisites are second + } else + { name = "3: " + name + ", " + TargetPath; // eveything else... + } + return name; } } @@ -136,9 +153,15 @@ public override string ToString() { string str = base.ToString(); if (!String.IsNullOrEmpty(str)) + { return str; + } + if (_assemblyIdentity != null) + { return _assemblyIdentity.ToString(); + } + return String.Empty; } diff --git a/src/Tasks/ManifestUtil/AssemblyReferenceCollection.cs b/src/Tasks/ManifestUtil/AssemblyReferenceCollection.cs index 09028f530cc..a67b01d991e 100644 --- a/src/Tasks/ManifestUtil/AssemblyReferenceCollection.cs +++ b/src/Tasks/ManifestUtil/AssemblyReferenceCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Tasks/ManifestUtil/BaseReference.cs b/src/Tasks/ManifestUtil/BaseReference.cs index 559f1d12c05..fe1143a4024 100644 --- a/src/Tasks/ManifestUtil/BaseReference.cs +++ b/src/Tasks/ManifestUtil/BaseReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; diff --git a/src/Tasks/ManifestUtil/CngLightup.cs b/src/Tasks/ManifestUtil/CngLightup.cs index 54c02703f4f..2dc0e2cb4b1 100644 --- a/src/Tasks/ManifestUtil/CngLightup.cs +++ b/src/Tasks/ManifestUtil/CngLightup.cs @@ -1,8 +1,5 @@ -// ==++== -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// -// ==--== +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // Supported preprocessor declarations: // @@ -586,7 +583,7 @@ private static CspParameters CopyCspParameters(ICspAsymmetricAlgorithm cspAlgori return cspParameters; } - private static Type GetSystemCoreType(string namespaceQualifiedTypeName, bool throwOnError=true) + private static Type GetSystemCoreType(string namespaceQualifiedTypeName, bool throwOnError = true) { #if CNG_LIGHTUP_NO_SYSTEM_CORE string assemblyQualifiedTypeName = namespaceQualifiedTypeName + ", " + AssemblyRef.SystemCore; diff --git a/src/Tasks/ManifestUtil/ComImporter.cs b/src/Tasks/ManifestUtil/ComImporter.cs index 96a941a43e0..084c04b607e 100644 --- a/src/Tasks/ManifestUtil/ComImporter.cs +++ b/src/Tasks/ManifestUtil/ComImporter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Win32; using System; @@ -46,7 +46,9 @@ public ComImporter(string path, OutputMessageCollection outputMessages, string o _outputDisplayName = outputDisplayName; if (NativeMethods.SfcIsFileProtected(IntPtr.Zero, path) != 0) + { outputMessages.AddWarningMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.ProtectedFile")); + } object obj = null; try { NativeMethods.LoadTypeLibEx(path, NativeMethods.RegKind.RegKind_None, out obj); } @@ -168,18 +170,18 @@ private ClassInfo GetRegisteredClassInfo(Guid clsid) using (RegistryKey userKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\CLASSES\\CLSID")) { - if (GetRegisteredClassInfo(userKey, clsid, ref info)) - { - return info; - } + if (GetRegisteredClassInfo(userKey, clsid, ref info)) + { + return info; + } } using (RegistryKey machineKey = Registry.ClassesRoot.OpenSubKey("CLSID")) { - if (GetRegisteredClassInfo(machineKey, clsid, ref info)) - { - return info; - } + if (GetRegisteredClassInfo(machineKey, clsid, ref info)) + { + return info; + } } // Check Wow6432Node of HKCR incase the COM reference is to a 32-bit binary. diff --git a/src/Tasks/ManifestUtil/CompatibleFramework.cs b/src/Tasks/ManifestUtil/CompatibleFramework.cs index 8d94458c72d..fa6c8fe8f50 100644 --- a/src/Tasks/ManifestUtil/CompatibleFramework.cs +++ b/src/Tasks/ManifestUtil/CompatibleFramework.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Runtime.InteropServices; diff --git a/src/Tasks/ManifestUtil/CompatibleFrameworkCollection.cs b/src/Tasks/ManifestUtil/CompatibleFrameworkCollection.cs index 4ae85e83195..94f50627a82 100644 --- a/src/Tasks/ManifestUtil/CompatibleFrameworkCollection.cs +++ b/src/Tasks/ManifestUtil/CompatibleFrameworkCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; diff --git a/src/Tasks/ManifestUtil/Constants.cs b/src/Tasks/ManifestUtil/Constants.cs index e68a9f0b404..5e7491a974c 100644 --- a/src/Tasks/ManifestUtil/Constants.cs +++ b/src/Tasks/ManifestUtil/Constants.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/ManifestUtil/ConvertUtil.cs b/src/Tasks/ManifestUtil/ConvertUtil.cs index a666c7bbbdc..7945fed64e5 100644 --- a/src/Tasks/ManifestUtil/ConvertUtil.cs +++ b/src/Tasks/ManifestUtil/ConvertUtil.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Tasks/ManifestUtil/DeployManifest.cs b/src/Tasks/ManifestUtil/DeployManifest.cs index ddfda42d466..de29d6ac5b2 100644 --- a/src/Tasks/ManifestUtil/DeployManifest.cs +++ b/src/Tasks/ManifestUtil/DeployManifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; diff --git a/src/Tasks/ManifestUtil/EmbeddedManifestReader.cs b/src/Tasks/ManifestUtil/EmbeddedManifestReader.cs index bcf29162ac8..01cb5f8f5d3 100644 --- a/src/Tasks/ManifestUtil/EmbeddedManifestReader.cs +++ b/src/Tasks/ManifestUtil/EmbeddedManifestReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -60,7 +60,10 @@ private bool EnumResNameCallback(IntPtr hModule, IntPtr pType, IntPtr pName, Int public static Stream Read(string path) { - if (path == null) throw new ArgumentNullException(nameof(path)); + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } if (!path.EndsWith(".manifest", StringComparison.Ordinal) && !path.EndsWith(".dll", StringComparison.Ordinal)) { diff --git a/src/Tasks/ManifestUtil/FileAssociation.cs b/src/Tasks/ManifestUtil/FileAssociation.cs index 7993cacb561..16c88e91cad 100644 --- a/src/Tasks/ManifestUtil/FileAssociation.cs +++ b/src/Tasks/ManifestUtil/FileAssociation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; using System.Runtime.InteropServices; diff --git a/src/Tasks/ManifestUtil/FileAssociationCollection.cs b/src/Tasks/ManifestUtil/FileAssociationCollection.cs index 0b879fe09bc..d2b0384b001 100644 --- a/src/Tasks/ManifestUtil/FileAssociationCollection.cs +++ b/src/Tasks/ManifestUtil/FileAssociationCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.Collections.Generic; diff --git a/src/Tasks/ManifestUtil/FileReference.cs b/src/Tasks/ManifestUtil/FileReference.cs index e13dad0af4f..be212c4bc51 100644 --- a/src/Tasks/ManifestUtil/FileReference.cs +++ b/src/Tasks/ManifestUtil/FileReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -105,7 +105,7 @@ public bool IsDataFile [XmlIgnore] public TypeLib[] TypeLibs => _typeLibs; -#region " XmlSerializer " + #region " XmlSerializer " [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] @@ -143,7 +143,7 @@ public string XmlWriteableType set => _writeableType = value; } -#endregion + #endregion } [ComVisible(false)] @@ -183,7 +183,7 @@ internal ComClass(Guid tlbId, Guid clsId, string progId, string threadingModel, [XmlIgnore] public string TlbId => _tlbid; -#region " XmlSerializer " + #region " XmlSerializer " [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] @@ -230,7 +230,7 @@ public string XmlTlbId set => _tlbid = value; } -#endregion + #endregion } [ComVisible(false)] @@ -295,7 +295,7 @@ private static string FlagsFromInt(int flags) [XmlIgnore] public string Version => _version; -#region " XmlSerializer " + #region " XmlSerializer " [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] @@ -342,7 +342,7 @@ public string XmlVersion set => _version = value; } -#endregion + #endregion } [ComVisible(false)] @@ -382,7 +382,7 @@ public bool Versioned } } -#region " XmlSerializer " + #region " XmlSerializer " [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] @@ -402,7 +402,7 @@ public string XmlVersioned set => _versioned = value; } -#endregion + #endregion } [ComVisible(false)] @@ -429,7 +429,7 @@ public class ProxyStub [XmlIgnore] public string TlbId => _tlbid; -#region " XmlSerializer " + #region " XmlSerializer " [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] @@ -476,6 +476,6 @@ public string XmlTlbId set => _tlbid = value; } -#endregion + #endregion } } diff --git a/src/Tasks/ManifestUtil/FileReferenceCollection.cs b/src/Tasks/ManifestUtil/FileReferenceCollection.cs index 1c12a7f904e..1cccda62a91 100644 --- a/src/Tasks/ManifestUtil/FileReferenceCollection.cs +++ b/src/Tasks/ManifestUtil/FileReferenceCollection.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Tasks/ManifestUtil/LauncherBuilder.cs b/src/Tasks/ManifestUtil/LauncherBuilder.cs index 068568a6815..c65068ddc1f 100644 --- a/src/Tasks/ManifestUtil/LauncherBuilder.cs +++ b/src/Tasks/ManifestUtil/LauncherBuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/ManifestUtil/Manifest.cs b/src/Tasks/ManifestUtil/Manifest.cs index 0d17d52f4e4..8f55d2f3540 100644 --- a/src/Tasks/ManifestUtil/Manifest.cs +++ b/src/Tasks/ManifestUtil/Manifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -233,7 +233,10 @@ public void ResolveFiles() public void ResolveFiles(string[] searchPaths) { if (searchPaths == null) + { throw new ArgumentNullException(nameof(searchPaths)); + } + CollectionToArray(); ResolveFiles_1(searchPaths); ResolveFiles_2(searchPaths); diff --git a/src/Tasks/ManifestUtil/ManifestFormatter.cs b/src/Tasks/ManifestUtil/ManifestFormatter.cs index 5434d2ebbb1..a4295b3da34 100644 --- a/src/Tasks/ManifestUtil/ManifestFormatter.cs +++ b/src/Tasks/ManifestUtil/ManifestFormatter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Tasks/ManifestUtil/ManifestReader.cs b/src/Tasks/ManifestUtil/ManifestReader.cs index 28879b378ab..7f3ccb4f721 100644 --- a/src/Tasks/ManifestUtil/ManifestReader.cs +++ b/src/Tasks/ManifestUtil/ManifestReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -106,7 +106,11 @@ private static Manifest ReadEmbeddedManifest(string path) /// A base object representation of the manifest. Can be cast to AssemblyManifest, ApplicationManifest, or DeployManifest to access more specific functionality. public static Manifest ReadManifest(string path, bool preserveStream) { - if (path == null) throw new ArgumentNullException(nameof(path)); + if (path == null) + { + throw new ArgumentNullException(nameof(path)); + } + string manifestType = null; if (path.EndsWith(".application", StringComparison.Ordinal)) { diff --git a/src/Tasks/ManifestUtil/ManifestWriter.cs b/src/Tasks/ManifestUtil/ManifestWriter.cs index cc076b2a08a..23c43ee0e02 100644 --- a/src/Tasks/ManifestUtil/ManifestWriter.cs +++ b/src/Tasks/ManifestUtil/ManifestWriter.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Tasks/ManifestUtil/MetadataReader.cs b/src/Tasks/ManifestUtil/MetadataReader.cs index 1b2dbef040f..fe8269ecdca 100644 --- a/src/Tasks/ManifestUtil/MetadataReader.cs +++ b/src/Tasks/ManifestUtil/MetadataReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Specialized; @@ -45,7 +45,7 @@ private MetadataReader(string path) } } } - catch(Exception) + catch (Exception) { Close(); } @@ -90,11 +90,15 @@ private void ImportCustomAttributesNames() { EntityHandle ctorHandle = _reader.GetCustomAttribute(handle).Constructor; if (ctorHandle.Kind != HandleKind.MemberReference) + { continue; + } EntityHandle mHandle = _reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent; if (mHandle.Kind != HandleKind.TypeReference) + { continue; + } string type = GetTypeName((TypeReferenceHandle)mHandle); @@ -169,11 +173,13 @@ private string GetPublicKeyToken() an.SetPublicKey(pk); byte[] pkt = an.GetPublicKeyToken(); - publicKeyToken = BitConverter.ToString(pkt).Replace("-",""); + publicKeyToken = BitConverter.ToString(pkt).Replace("-", ""); } if (!String.IsNullOrEmpty(publicKeyToken)) + { publicKeyToken = publicKeyToken.ToUpperInvariant(); + } return publicKeyToken; } @@ -346,9 +352,14 @@ private void ImportAttributes() string version = refid.GetAttribute(null, "version"); string publicKeyToken = refid.GetAttribute(null, "publicKeyToken"); if (String.Equals(publicKeyToken, "neutral", StringComparison.OrdinalIgnoreCase)) + { publicKeyToken = String.Empty; + } else if (!String.IsNullOrEmpty(publicKeyToken)) + { publicKeyToken = publicKeyToken.ToUpperInvariant(); + } + string culture = refid.GetAttribute(null, "culture"); string processorArchitecture = refid.GetAttribute(null, "processorArchitecture"); if (!String.IsNullOrEmpty(processorArchitecture)) @@ -397,7 +408,7 @@ private interface IMetaDataDispenser { int DefineScope(); [PreserveSig] - int OpenScope([In][MarshalAs(UnmanagedType.LPWStr)] string szScope, [In] UInt32 dwOpenFlags, [In] ref Guid riid, [Out][MarshalAs(UnmanagedType.Interface)] out object obj); + int OpenScope([In][MarshalAs(UnmanagedType.LPWStr)] string szScope, [In] UInt32 dwOpenFlags, [In] ref Guid riid, [Out][MarshalAs(UnmanagedType.Interface)] out object obj); int OpenScopeOnMemory(); } } diff --git a/src/Tasks/ManifestUtil/NativeMethods.cs b/src/Tasks/ManifestUtil/NativeMethods.cs index ac61c9eac01..145db59746e 100644 --- a/src/Tasks/ManifestUtil/NativeMethods.cs +++ b/src/Tasks/ManifestUtil/NativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Tasks/ManifestUtil/OutputMessage.cs b/src/Tasks/ManifestUtil/OutputMessage.cs index c1c28bce018..7d0c5bb096c 100644 --- a/src/Tasks/ManifestUtil/OutputMessage.cs +++ b/src/Tasks/ManifestUtil/OutputMessage.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; using System; diff --git a/src/Tasks/ManifestUtil/PathUtil.cs b/src/Tasks/ManifestUtil/PathUtil.cs index a9136b0f290..8394babb735 100644 --- a/src/Tasks/ManifestUtil/PathUtil.cs +++ b/src/Tasks/ManifestUtil/PathUtil.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using System; @@ -38,7 +38,11 @@ public static string[] GetPathSegments(string path) // Resolves the path, and if path is a url also canonicalizes it. public static string Format(string path) { - if (String.IsNullOrEmpty(path)) return path; + if (String.IsNullOrEmpty(path)) + { + return path; + } + string resolvedPath = Resolve(path); Uri u = new Uri(resolvedPath); return u.AbsoluteUri; @@ -46,12 +50,36 @@ public static string Format(string path) public static bool IsAssembly(string path) { - if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); - if (String.Equals(Path.GetExtension(path), ".application", StringComparison.Ordinal)) return true; - if (String.Equals(Path.GetExtension(path), ".manifest", StringComparison.Ordinal)) return true; - if (!IsProgramFile(path)) return false; // optimization, don't want to sniff every every kind of file -- just dll's or exe's - if (IsManagedAssembly(path)) return true; - if (IsNativeAssembly(path)) return true; + if (String.IsNullOrEmpty(path)) + { + throw new ArgumentNullException(nameof(path)); + } + + if (String.Equals(Path.GetExtension(path), ".application", StringComparison.Ordinal)) + { + return true; + } + + if (String.Equals(Path.GetExtension(path), ".manifest", StringComparison.Ordinal)) + { + return true; + } + + if (!IsProgramFile(path)) + { + return false; // optimization, don't want to sniff every every kind of file -- just dll's or exe's + } + + if (IsManagedAssembly(path)) + { + return true; + } + + if (IsNativeAssembly(path)) + { + return true; + } + return false; } @@ -75,21 +103,38 @@ public static bool IsLocalPath(string path) { Uri u = new Uri(path, UriKind.RelativeOrAbsolute); if (!u.IsAbsoluteUri) + { return true; + } + return String.IsNullOrEmpty(u.Host); } public static bool IsManagedAssembly(string path) { - if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); + if (String.IsNullOrEmpty(path)) + { + throw new ArgumentNullException(nameof(path)); + } + using (MetadataReader r = MetadataReader.Create(path)) + { return r != null; + } } public static bool IsNativeAssembly(string path) { - if (String.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path)); - if (String.Equals(Path.GetExtension(path), ".manifest", StringComparison.Ordinal)) return true; + if (String.IsNullOrEmpty(path)) + { + throw new ArgumentNullException(nameof(path)); + } + + if (String.Equals(Path.GetExtension(path), ".manifest", StringComparison.Ordinal)) + { + return true; + } + return EmbeddedManifestReader.Read(path) != null; } @@ -116,14 +161,20 @@ public static bool IsUncPath(string path) { Uri u; if (!Uri.TryCreate(path, UriKind.Absolute, out u) || u == null) + { return false; + } + return u.IsUnc; } public static bool IsUrl(string path) { if (!Uri.TryCreate(path, UriKind.Absolute, out Uri u) || u == null) + { return false; + } + return !u.IsUnc && !String.IsNullOrEmpty(u.Host); } @@ -131,8 +182,16 @@ public static bool IsUrl(string path) // If path is a relative path, resolves to a full path. public static string Resolve(string path) { - if (String.IsNullOrEmpty(path)) return path; - if (IsUncPath(path)) return path; // if it's UNC then do nothing + if (String.IsNullOrEmpty(path)) + { + return path; + } + + if (IsUncPath(path)) + { + return path; // if it's UNC then do nothing + } + if (IsUrl(path)) // if it's a URL then need to check for "localhost"... { // Replace "localhost" with the actual machine name... diff --git a/src/Tasks/ManifestUtil/RSAPKCS1SHA256SignatureDescription.cs b/src/Tasks/ManifestUtil/RSAPKCS1SHA256SignatureDescription.cs index e78f825dcaa..d41a32ad42a 100644 --- a/src/Tasks/ManifestUtil/RSAPKCS1SHA256SignatureDescription.cs +++ b/src/Tasks/ManifestUtil/RSAPKCS1SHA256SignatureDescription.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; diff --git a/src/Tasks/ManifestUtil/SecurityUtil.cs b/src/Tasks/ManifestUtil/SecurityUtil.cs index 8e16ee1a599..01a5da96803 100644 --- a/src/Tasks/ManifestUtil/SecurityUtil.cs +++ b/src/Tasks/ManifestUtil/SecurityUtil.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Utilities; using Microsoft.Win32; @@ -419,11 +419,16 @@ private static SecurityElement XmlElementToSecurityElement(XmlElement xe) { SecurityElement se = new SecurityElement(xe.Name); foreach (XmlAttribute xa in xe.Attributes) + { se.AddAttribute(xa.Name, xa.Value); + } + foreach (XmlNode xn in xe.ChildNodes) { if (xn.NodeType == XmlNodeType.Element) + { se.AddChild(XmlElementToSecurityElement((XmlElement)xn)); + } } return se; @@ -434,7 +439,10 @@ private static string[] XmlToIdentityList(XmlElement psElement) XmlNamespaceManager nsmgr = XmlNamespaces.GetNamespaceManager(psElement.OwnerDocument.NameTable); XmlNodeList nodes = psElement.SelectNodes(XPaths.permissionClassAttributeQuery, nsmgr); if (nodes == null || nodes.Count == 0) + { nodes = psElement.SelectNodes(XmlUtil.TrimPrefix(XPaths.permissionClassAttributeQuery)); + } + string[] a; if (nodes != null) { @@ -660,9 +668,13 @@ private static void SignFileInternal(X509Certificate2 cert, if (PathUtil.IsPEFile(path)) { if (IsCertInStore(cert)) + { SignPEFile(cert, timestampUrl, path, resources, useSha256); + } else + { throw new InvalidOperationException(resources.GetString("SignFile.CertNotInStore")); + } } else { @@ -675,7 +687,10 @@ private static void SignFileInternal(X509Certificate2 cert, #endif { if (rsa == null) + { throw new ApplicationException(resources.GetString("SecurityUtil.OnlyRSACertsAreAllowed")); + } + try { var doc = new XmlDocument { PreserveWhitespace = true }; @@ -711,9 +726,14 @@ private static void SignFileInternal(X509Certificate2 cert, // No need to check hModule - Sign() method will quickly fail if we did not load clr.dll #endif if (timestampUrl == null) + { manifest.Sign(signer); + } else + { manifest.Sign(signer, timestampUrl.ToString(), disallowMansignTimestampFallback); + } + doc.Save(path); } catch (Exception ex) @@ -746,7 +766,7 @@ private static void SignPEFile(X509Certificate2 cert, Uri timestampUrl, string p { SignPEFileInternal(cert, timestampUrl, path, resources, useSha256, true); } - catch(ApplicationException) when (timestampUrl != null) + catch (ApplicationException) when (timestampUrl != null) { // error, retry with signtool /t if timestamp url was given SignPEFileInternal(cert, timestampUrl, path, resources, useSha256, false); @@ -887,7 +907,9 @@ private static bool IsCertInStore(X509Certificate2 cert) personalStore.Open(OpenFlags.ReadOnly); X509Certificate2Collection foundCerts = personalStore.Certificates.Find(X509FindType.FindByThumbprint, cert.Thumbprint, false); if (foundCerts.Count == 1) + { return true; + } } finally { diff --git a/src/Tasks/ManifestUtil/TrustInfo.cs b/src/Tasks/ManifestUtil/TrustInfo.cs index dc7880cd52a..d3e38a5fd5d 100644 --- a/src/Tasks/ManifestUtil/TrustInfo.cs +++ b/src/Tasks/ManifestUtil/TrustInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -187,11 +187,14 @@ private XmlElement GetInputPermissionSetElement() private XmlElement GetInputRequestedPrivilegeElement() { if (_inputTrustInfoDocument == null) + { return null; + } + XmlNamespaceManager nsmgr = XmlNamespaces.GetNamespaceManager(_inputTrustInfoDocument.NameTable); XmlElement trustInfoElement = _inputTrustInfoDocument.DocumentElement; - XmlElement securityElement = (XmlElement) trustInfoElement?.SelectSingleNode(XPaths.securityElement, nsmgr); - XmlElement requestedPrivilegeElement = (XmlElement) securityElement?.SelectSingleNode(XPaths.requestedPrivilegeElement, nsmgr); + XmlElement securityElement = (XmlElement)trustInfoElement?.SelectSingleNode(XPaths.securityElement, nsmgr); + XmlElement requestedPrivilegeElement = (XmlElement)securityElement?.SelectSingleNode(XPaths.requestedPrivilegeElement, nsmgr); return requestedPrivilegeElement; } @@ -242,7 +245,7 @@ private static XmlElement GetRequestedPrivilegeElement(XmlElement inputRequested // here so we can allow the passed-in node to override it if there is a comment present // System.Resources.ResourceManager resources = new System.Resources.ResourceManager("Microsoft.Build.Tasks.Core.Strings.ManifestUtilities", typeof(SecurityUtilities).Module.Assembly); - commentString = resources.GetString("TrustInfo.RequestedExecutionLevelComment"); + commentString = resources.GetString("TrustInfo.RequestedExecutionLevelComment"); } else { @@ -396,7 +399,7 @@ public bool IsFullTrust { #if RUNTIME_TYPE_NETCORE // Always use full-trust on .NET Core. - return true; + return true; #else GetInputPermissionSet(); return _isFullTrust; @@ -506,7 +509,9 @@ private void ReadTrustInfo(string xml) #endif XmlAttribute sameSiteAttribute = (XmlAttribute)psElement.Attributes.GetNamedItem(XmlUtil.TrimPrefix(XPaths.sameSiteAttribute)); if (sameSiteAttribute != null) + { _sameSiteSetting = sameSiteAttribute.Value; + } } /// @@ -733,7 +738,9 @@ public void WriteManifest(Stream input, Stream output) XmlNodeList permissionSetNodes = applicationRequestMinimumElement.SelectNodes(XPaths.permissionSetElement, nsmgr); foreach (XmlNode permissionSetNode in permissionSetNodes) + { applicationRequestMinimumElement.RemoveChild(permissionSetNode); + } XmlElement fullTrustPermissionSetElement = document.CreateElement(XmlUtil.TrimPrefix(XPaths.permissionSetElement), XmlNamespaces.asmv2); XmlAttribute unrestrictedAttribute = document.CreateAttribute(XmlUtil.TrimPrefix(XPaths.unrestrictedAttribute), XmlNamespaces.asmv2); diff --git a/src/Tasks/ManifestUtil/Util.cs b/src/Tasks/ManifestUtil/Util.cs index fd197c183f5..0a8f9a2654c 100644 --- a/src/Tasks/ManifestUtil/Util.cs +++ b/src/Tasks/ManifestUtil/Util.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; @@ -63,20 +63,32 @@ internal static class Util public static string ByteArrayToHex(Byte[] a) { if (a == null) + { return null; + } + StringBuilder s = new StringBuilder(a.Length); foreach (Byte b in a) + { s.Append(b.ToString("X02", CultureInfo.InvariantCulture)); + } + return s.ToString(); } public static string ByteArrayToString(Byte[] a) { if (a == null) + { return null; + } + StringBuilder s = new StringBuilder(a.Length); foreach (Byte b in a) + { s.Append(Convert.ToChar(b)); + } + return s.ToString(); } @@ -105,9 +117,13 @@ public static string FilterNonprintableChars(string value) while (i < sb.Length) { if (sb[i] < ' ') + { sb.Remove(i, 1); + } else + { ++i; + } } return sb.ToString(); @@ -139,7 +155,9 @@ public static string GetClrVersion() public static string GetClrVersion(string targetFrameworkVersion) { if (string.IsNullOrEmpty(targetFrameworkVersion)) + { return GetClrVersion(); + } Version clrVersion; #if RUNTIME_TYPE_NETCORE @@ -227,19 +245,23 @@ private static void GetFileInfoImpl(string path, string targetFrameWorkVersion, if (string.IsNullOrEmpty(targetFrameWorkVersion) || CompareFrameworkVersions(targetFrameWorkVersion, Constants.TargetFrameworkVersion40) <= 0) { +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter hashAlg = SHA1.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA1CryptoServiceProvider" #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter } else { +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter hashAlg = SHA256.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA256CryptoServiceProvider" #endif ); +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter } byte[] hashBytes = hashAlg.ComputeHash(s); hash = Convert.ToBase64String(hashBytes); @@ -252,10 +274,17 @@ private static void GetFileInfoImpl(string path, string targetFrameWorkVersion, private static string GetLogPath() { - if (!logging) return null; + if (!logging) + { + return null; + } + string logPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\VisualStudio\8.0\VSPLOG"); if (!FileSystems.Default.DirectoryExists(logPath)) + { Directory.CreateDirectory(logPath); + } + return logPath; } @@ -268,7 +297,9 @@ public static string GetRegisteredOrganization() string org = (string)key.GetValue("RegisteredOrganization"); org = org?.Trim(); if (!String.IsNullOrEmpty(org)) + { return org; + } } return null; } @@ -281,9 +312,15 @@ public static bool IsValidAssemblyName(string value) public static bool IsValidCulture(string value) { if (String.Equals(value, "neutral", StringComparison.OrdinalIgnoreCase)) + { return true; // "neutral" is valid in a manifest but not in CultureInfo class + } + if (String.Equals(value, "*", StringComparison.OrdinalIgnoreCase)) + { return true; // "*" is same as "neutral" + } + CultureInfo culture; try { @@ -330,13 +367,24 @@ public static bool IsValidVersion(string value, int octets) } if (octets >= 1 && version.Major < 0) + { return false; + } + if (octets >= 2 && version.Minor < 0) + { return false; + } + if (octets >= 3 && version.Build < 0) + { return false; + } + if (octets >= 4 && version.Revision < 0) + { return false; + } return true; } @@ -344,7 +392,10 @@ public static bool IsValidVersion(string value, int octets) internal static bool IsValidFrameworkVersion(string value) { if (value.StartsWith("v", StringComparison.OrdinalIgnoreCase)) + { return IsValidVersion(value.Substring(1), 2); + } + return IsValidVersion(value, 2); } @@ -353,7 +404,9 @@ public static string PlatformToProcessorArchitecture(string platform) for (int i = 0; i < s_platforms.Length; ++i) { if (String.Equals(platform, s_platforms[i], StringComparison.OrdinalIgnoreCase)) + { return s_processorArchitectures[i]; + } } return null; @@ -362,9 +415,15 @@ public static string PlatformToProcessorArchitecture(string platform) private static ITaskItem[] RemoveDuplicateItems(ITaskItem[] items) { if (items == null) + { return null; + } + if (items.Length <= 1) + { return items; + } + var list = new Dictionary(); foreach (ITaskItem item in items) { @@ -397,7 +456,10 @@ public static ITaskItem[] SortItems(ITaskItem[] items) { ITaskItem[] outputItems = RemoveDuplicateItems(items); if (outputItems != null) + { Array.Sort(outputItems, s_itemComparer); + } + return outputItems; } @@ -418,7 +480,10 @@ public static void WriteFile(string path, Stream s) public static void WriteLog(string text) { if (!logging) + { return; + } + if (s_logFileWriter == null) { try @@ -450,7 +515,10 @@ public static void WriteLog(string text) public static void WriteLogFile(string filename, Stream s) { if (!logging) + { return; + } + string path = Path.Combine(logPath, filename); StreamReader r = new StreamReader(s); string text = r.ReadToEnd(); @@ -476,7 +544,10 @@ public static void WriteLogFile(string filename, Stream s) public static void WriteLogFile(string filename, string s) { if (!logging) + { return; + } + string path = Path.Combine(logPath, filename); try { @@ -503,7 +574,10 @@ public static void WriteLogFile(string filename, string s) public static void WriteLogFile(string filename, System.Xml.XmlElement element) { if (!logging) + { return; + } + WriteLogFile(filename, element.OuterXml); } @@ -525,7 +599,7 @@ public static string WriteTempFile(string s) return path; } -#region ItemComparer + #region ItemComparer private static readonly ItemComparer s_itemComparer = new ItemComparer(); private class ItemComparer : IComparer { @@ -551,7 +625,7 @@ int IComparer.Compare(object obj1, object obj2) return String.Compare(item1.ItemSpec, item2.ItemSpec, StringComparison.Ordinal); } } -#endregion + #endregion public static Version ConvertFrameworkVersionToString(string version) { diff --git a/src/Tasks/ManifestUtil/XPaths.cs b/src/Tasks/ManifestUtil/XPaths.cs index 573fb85df4b..fad943f8d0d 100644 --- a/src/Tasks/ManifestUtil/XPaths.cs +++ b/src/Tasks/ManifestUtil/XPaths.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/ManifestUtil/XmlNamespaces.cs b/src/Tasks/ManifestUtil/XmlNamespaces.cs index 3edb86d6bd4..033c1f4006c 100644 --- a/src/Tasks/ManifestUtil/XmlNamespaces.cs +++ b/src/Tasks/ManifestUtil/XmlNamespaces.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Xml; diff --git a/src/Tasks/ManifestUtil/XmlUtil.cs b/src/Tasks/ManifestUtil/XmlUtil.cs index e370c0cad8a..e2360d23b24 100644 --- a/src/Tasks/ManifestUtil/XmlUtil.cs +++ b/src/Tasks/ManifestUtil/XmlUtil.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -25,9 +25,13 @@ public static string GetQName(XmlTextReader r, XmlNamespaceManager nsmgr) { string prefix = !String.IsNullOrEmpty(r.Prefix) ? r.Prefix : nsmgr.LookupPrefix(r.NamespaceURI); if (!String.IsNullOrEmpty(prefix)) + { return prefix + ":" + r.LocalName; + } else + { return r.LocalName; + } } // NOTE: XmlDocument.ImportNode munges "xmlns:asmv2" to "xmlns:d1p1" for some reason, use XmlUtil.CloneElementToDocument instead @@ -60,7 +64,10 @@ public static string TrimPrefix(string s) { int i = s.IndexOf(':'); if (i < 0) + { return s; + } + return s.Substring(i + 1); } @@ -144,7 +151,9 @@ public override Object GetEntity(Uri uri, string role, Type t) s = a.GetManifestResourceStream(String.Format(CultureInfo.InvariantCulture, "{0}.{1}", typeof(Util).Namespace, filename)); if (s != null) + { return s; + } // Next look in current directory... try @@ -155,7 +164,9 @@ public override Object GetEntity(Uri uri, string role, Type t) { } if (s != null) + { return s; + } } // Lastly, look at full specified uri path... @@ -170,7 +181,9 @@ public override Object GetEntity(Uri uri, string role, Type t) { } if (s != null) + { return s; + } // Didn't find the resource... Debug.Fail(String.Format(CultureInfo.CurrentCulture, "ResourceResolver could not find file '{0}'", filename)); diff --git a/src/Tasks/ManifestUtil/mansign2.cs b/src/Tasks/ManifestUtil/mansign2.cs index 9c29d1cbb1d..23e273cdad6 100644 --- a/src/Tasks/ManifestUtil/mansign2.cs +++ b/src/Tasks/ManifestUtil/mansign2.cs @@ -1,8 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// -// mansign.cs -// +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.IO; @@ -124,59 +121,59 @@ internal struct AXL_TIMESTAMPER_INFO // DllImport declarations. // [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern IntPtr GetProcessHeap(); [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - internal extern static + internal static extern bool HeapFree( - [In] IntPtr hHeap, - [In] uint dwFlags, - [In] IntPtr lpMem); + [In] IntPtr hHeap, + [In] uint dwFlags, + [In] IntPtr lpMem); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int CertTimestampAuthenticodeLicense( - [In] ref CRYPT_DATA_BLOB pSignedLicenseBlob, - [In] string pwszTimestampURI, - [In, Out] ref CRYPT_DATA_BLOB pTimestampSignatureBlob); + [In] ref CRYPT_DATA_BLOB pSignedLicenseBlob, + [In] string pwszTimestampURI, + [In, Out] ref CRYPT_DATA_BLOB pTimestampSignatureBlob); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int CertVerifyAuthenticodeLicense( - [In] ref CRYPT_DATA_BLOB pLicenseBlob, - [In] uint dwFlags, - [In, Out] ref AXL_SIGNER_INFO pSignerInfo, - [In, Out] ref AXL_TIMESTAMPER_INFO pTimestamperInfo); + [In] ref CRYPT_DATA_BLOB pLicenseBlob, + [In] uint dwFlags, + [In, Out] ref AXL_SIGNER_INFO pSignerInfo, + [In, Out] ref AXL_TIMESTAMPER_INFO pTimestamperInfo); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int CertFreeAuthenticodeSignerInfo( - [In] ref AXL_SIGNER_INFO pSignerInfo); + [In] ref AXL_SIGNER_INFO pSignerInfo); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int CertFreeAuthenticodeTimestamperInfo( - [In] ref AXL_TIMESTAMPER_INFO pTimestamperInfo); + [In] ref AXL_TIMESTAMPER_INFO pTimestamperInfo); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int _AxlGetIssuerPublicKeyHash( - [In] IntPtr pCertContext, + [In] IntPtr pCertContext, [In, Out] ref IntPtr ppwszPublicKeyHash); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int _AxlRSAKeyValueToPublicKeyToken( - [In] ref CRYPT_DATA_BLOB pModulusBlob, - [In] ref CRYPT_DATA_BLOB pExponentBlob, + [In] ref CRYPT_DATA_BLOB pModulusBlob, + [In] ref CRYPT_DATA_BLOB pExponentBlob, [In, Out] ref IntPtr ppwszPublicKeyToken); [DllImport(MSCORWKS, CharSet = CharSet.Auto, SetLastError = true)] - internal extern static + internal static extern int _AxlPublicKeyBlobToPublicKeyToken( - [In] ref CRYPT_DATA_BLOB pCspPublicKeyBlob, + [In] ref CRYPT_DATA_BLOB pCspPublicKeyBlob, [In, Out] ref IntPtr ppwszPublicKeyToken); // RFC3161 timestamp support @@ -213,15 +210,15 @@ internal struct CRYPT_TIMESTAMP_PARA [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] [DllImport(CRYPT32, CallingConvention = CallingConvention.Winapi, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - internal extern static + internal static extern bool CryptRetrieveTimeStamp( - [In] [MarshalAs(UnmanagedType.LPWStr)] string wszUrl, - [In] uint dwRetrievalFlags, - [In] int dwTimeout, - [In] [MarshalAs(UnmanagedType.LPStr)] string pszHashId, + [In][MarshalAs(UnmanagedType.LPWStr)] string wszUrl, + [In] uint dwRetrievalFlags, + [In] int dwTimeout, + [In][MarshalAs(UnmanagedType.LPStr)] string pszHashId, [In, Out] ref CRYPT_TIMESTAMP_PARA pPara, - [In] byte[] pbData, - [In] int cbData, + [In] byte[] pbData, + [In] int cbData, [In, Out] ref IntPtr ppTsContext, [In, Out] ref IntPtr ppTsSigner, [In, Out] ref IntPtr phStore); @@ -286,11 +283,16 @@ public override XmlElement GetIdElement(XmlDocument document, string idValue) { // We only care about Id references inside of the KeyInfo section if (_verify) + { return base.GetIdElement(document, idValue); + } KeyInfo keyInfo = this.KeyInfo; if (keyInfo.Id != idValue) + { return null; + } + return keyInfo.GetXml(); } } @@ -382,7 +384,10 @@ private XmlElement ExtractPrincipalFromManifest() nsm.AddNamespace("asm", AssemblyNamespaceUri); XmlNode assemblyIdentityNode = _manifestDom.SelectSingleNode("asm:assembly/asm:assemblyIdentity", nsm); if (assemblyIdentityNode == null) + { throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN); + } + return assemblyIdentityNode as XmlElement; } @@ -442,7 +447,9 @@ private static void RemoveExistingSignature(XmlDocument manifestDom) nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); XmlNode signatureNode = manifestDom.SelectSingleNode("asm:assembly/ds:Signature", nsm); if (signatureNode != null) + { signatureNode.ParentNode.RemoveChild(signatureNode); + } } /// @@ -555,11 +562,13 @@ private static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldF if (useSha256) { +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter using (SHA256 sha2 = SHA256.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA256CryptoServiceProvider" #endif )) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { byte[] hash = sha2.ComputeHash(exc.GetOutput() as MemoryStream); if (hash == null) @@ -572,11 +581,13 @@ private static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldF } else { +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter using (SHA1 sha1 = SHA1.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA1CryptoServiceProvider" #endif )) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { byte[] hash = sha1.ComputeHash(exc.GetOutput() as MemoryStream); if (hash == null) @@ -611,11 +622,13 @@ private static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldF if (useSha256) { +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter using (SHA256 sha2 = SHA256.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA256CryptoServiceProvider" #endif )) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { byte[] hash = sha2.ComputeHash(exc.GetOutput() as MemoryStream); if (hash == null) @@ -628,11 +641,13 @@ private static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldF } else { +#pragma warning disable SA1111, SA1009 // Closing parenthesis should be on line of last parameter using (SHA1 sha1 = SHA1.Create( #if FEATURE_CRYPTOGRAPHIC_FACTORY_ALGORITHM_NAMES "System.Security.Cryptography.SHA1CryptoServiceProvider" #endif )) +#pragma warning restore SA1111, SA1009 // Closing parenthesis should be on line of last parameter { byte[] hash = sha1.ComputeHash(exc.GetOutput() as MemoryStream); if (hash == null) @@ -836,13 +851,19 @@ private static string ObtainRFC3161Timestamp(string timeStampUrl, string signatu finally { if (ppTsContext != IntPtr.Zero) + { Win32.CryptMemFree(ppTsContext); + } if (ppTsSigner != IntPtr.Zero) + { Win32.CertFreeCertificateContext(ppTsSigner); + } if (phStore != IntPtr.Zero) + { Win32.CertCloseStore(phStore, 0); + } } } @@ -1063,12 +1084,16 @@ internal CmiManifestSigner2(AsymmetricAlgorithm strongNameKey) : internal CmiManifestSigner2(AsymmetricAlgorithm strongNameKey, X509Certificate2 certificate, bool useSha256) { if (strongNameKey == null) + { throw new ArgumentNullException(nameof(strongNameKey)); + } #if (true) // BUGBUG: Fusion only supports RSA. Do we throw if not RSA??? RSA rsa = strongNameKey as RSA; if (rsa == null) + { throw new ArgumentNullException(nameof(strongNameKey)); + } #endif _strongNameKey = strongNameKey; _certificate = certificate; @@ -1143,9 +1168,15 @@ internal X509IncludeOption IncludeOption set { if (value < X509IncludeOption.None || value > X509IncludeOption.WholeChain) + { throw new ArgumentException("value"); + } + if (_includeOption == X509IncludeOption.None) + { throw new NotSupportedException(); + } + _includeOption = value; } } @@ -1161,7 +1192,9 @@ internal CmiManifestSignerFlag Flag unchecked { if ((value & ((CmiManifestSignerFlag)~CimManifestSignerFlagMask)) != 0) + { throw new ArgumentException("value"); + } } _signerFlag = value; } diff --git a/src/Tasks/Message.cs b/src/Tasks/Message.cs index 52b85a04103..2b16f5bcd27 100644 --- a/src/Tasks/Message.cs +++ b/src/Tasks/Message.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/Move.cs b/src/Tasks/Move.cs index 1e0b1da9200..42f0e20b968 100644 --- a/src/Tasks/Move.cs +++ b/src/Tasks/Move.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -190,11 +190,9 @@ private static void MakeWriteableIfReadOnly(string file) /// Move one file from source to destination. Create the target directory if necessary. /// /// IO related exceptions - private bool MoveFileWithLogging - ( + private bool MoveFileWithLogging( string sourceFile, - string destinationFile - ) + string destinationFile) { if (FileSystems.Default.DirectoryExists(destinationFile)) { diff --git a/src/Tasks/NativeMethods.cs b/src/Tasks/NativeMethods.cs index a100afbb4e7..a55f04aa68c 100644 --- a/src/Tasks/NativeMethods.cs +++ b/src/Tasks/NativeMethods.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -819,12 +819,10 @@ internal static bool MakeHardLink(string newFileName, string exitingFileName, re // MoveFileEx //------------------------------------------------------------------------------ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileEx")] - internal static extern bool MoveFileExWindows - ( + internal static extern bool MoveFileExWindows( [In] string existingFileName, [In] string newFileName, - [In] MoveFileFlags flags - ); + [In] MoveFileFlags flags); /// /// Add implementation of this function when not running on windows. The implementation is @@ -883,14 +881,12 @@ internal static bool MoveFileEx(string existingFileName, string newFileName, Mov // UnRegisterTypeLib //------------------------------------------------------------------------------ [DllImport("oleaut32", PreserveSig = false, EntryPoint = "UnRegisterTypeLib")] - internal static extern void UnregisterTypeLib - ( + internal static extern void UnregisterTypeLib( [In] ref Guid guid, [In] short wMajorVerNum, [In] short wMinorVerNum, [In] int lcid, - [In] System.Runtime.InteropServices.ComTypes.SYSKIND syskind - ); + [In] System.Runtime.InteropServices.ComTypes.SYSKIND syskind); //------------------------------------------------------------------------------ // LoadTypeLib @@ -958,8 +954,7 @@ internal static extern IntPtr CreateFileMapping(IntPtr hFile, IntPtr lpFileMappi //------------------------------------------------------------------------------ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CreateProcess - ( + internal static extern bool CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, @@ -970,8 +965,7 @@ internal static extern bool CreateProcess IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, - out PROCESS_INFORMATION lpProcessInformation - ); + out PROCESS_INFORMATION lpProcessInformation); //------------------------------------------------------------------------------ // ImageNtHeader diff --git a/src/Tasks/ParserState.cs b/src/Tasks/ParserState.cs index 5bfc18c8401..0f1b0ec7405 100644 --- a/src/Tasks/ParserState.cs +++ b/src/Tasks/ParserState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Text; diff --git a/src/Tasks/PiaReference.cs b/src/Tasks/PiaReference.cs index 01157e389f6..f98a07f512d 100644 --- a/src/Tasks/PiaReference.cs +++ b/src/Tasks/PiaReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/RCWForCurrentContext.cs b/src/Tasks/RCWForCurrentContext.cs index 690f8d9773b..9c2d4675327 100644 --- a/src/Tasks/RCWForCurrentContext.cs +++ b/src/Tasks/RCWForCurrentContext.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.InteropServices; diff --git a/src/Tasks/RedistList.cs b/src/Tasks/RedistList.cs index 2fdd200203a..3428a752a0d 100644 --- a/src/Tasks/RedistList.cs +++ b/src/Tasks/RedistList.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -95,7 +95,11 @@ private RedistList(AssemblyTableInfo[] assemblyTableInfos) var assemblyList = new List(); var remappingEntries = new List(); - if (assemblyTableInfos == null) throw new ArgumentNullException(nameof(assemblyTableInfos)); + if (assemblyTableInfos == null) + { + throw new ArgumentNullException(nameof(assemblyTableInfos)); + } + foreach (AssemblyTableInfo assemblyTableInfo in assemblyTableInfos) { ReadFile(assemblyTableInfo, assemblyList, errors, errorFilenames, remappingEntries); @@ -332,7 +336,11 @@ internal string RedistName(string assemblyName) /// public static RedistList GetRedistList(AssemblyTableInfo[] assemblyTables) { - if (assemblyTables == null) throw new ArgumentNullException(nameof(assemblyTables)); + if (assemblyTables == null) + { + throw new ArgumentNullException(nameof(assemblyTables)); + } + Array.Sort(assemblyTables); var keyBuilder = assemblyTables.Length > 0 ? new StringBuilder(assemblyTables[0].Descriptor) : new StringBuilder(); @@ -359,14 +367,22 @@ public static RedistList GetRedistList(AssemblyTableInfo[] assemblyTables) private static string GetSimpleName(string assemblyName) { - if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); + if (assemblyName == null) + { + throw new ArgumentNullException(nameof(assemblyName)); + } + int i = assemblyName.IndexOf(",", StringComparison.Ordinal); return i > 0 ? assemblyName.Substring(0, i) : assemblyName; } private AssemblyEntry GetUnifiedAssemblyEntry(string assemblyName) { - if (assemblyName == null) throw new ArgumentNullException(nameof(assemblyName)); + if (assemblyName == null) + { + throw new ArgumentNullException(nameof(assemblyName)); + } + if (!_assemblyNameToUnifiedAssemblyName.TryGetValue(assemblyName, out AssemblyEntry unifiedEntry)) { string simpleName = GetSimpleName(assemblyName); @@ -875,7 +891,10 @@ public int Compare(object a, object b) public int Compare(AssemblyEntry firstEntry, AssemblyEntry secondEntry) { Debug.Assert(firstEntry != null && secondEntry != null); - if (firstEntry == null || secondEntry == null) return 0; + if (firstEntry == null || secondEntry == null) + { + return 0; + } AssemblyNameExtension firstAssemblyName = firstEntry.AssemblyNameExtension; AssemblyNameExtension secondAssemblyName = secondEntry.AssemblyNameExtension; @@ -1105,7 +1124,7 @@ public AssemblyEntry(string name, string version, string publicKeyToken, string public string FullName { get; } public bool InGAC { get; } - public bool? IsRedistRoot { get; } + public bool? IsRedistRoot { get; } public string RedistName { get; } public string SimpleName { get; } public string FrameworkDirectory { get; } diff --git a/src/Tasks/RegisterAssembly.cs b/src/Tasks/RegisterAssembly.cs index a7b6a78edf4..3ce50fcde06 100644 --- a/src/Tasks/RegisterAssembly.cs +++ b/src/Tasks/RegisterAssembly.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_APPDOMAIN @@ -120,7 +120,7 @@ public override bool Execute() #if DEBUG catch (Exception e) { - Debug.Assert(false, "Unexpected exception in AssemblyRegistration.Execute. " + + Debug.Assert(false, "Unexpected exception in AssemblyRegistration.Execute. " + "Please log a MSBuild bug specifying the steps to reproduce the problem. " + e.Message); throw; diff --git a/src/Tasks/RemoveDir.cs b/src/Tasks/RemoveDir.cs index 4e94778a998..3c9d3c4e9f1 100644 --- a/src/Tasks/RemoveDir.cs +++ b/src/Tasks/RemoveDir.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/RequiresFramework35SP1Assembly.cs b/src/Tasks/RequiresFramework35SP1Assembly.cs index a7c10c1a9dd..068315c907c 100644 --- a/src/Tasks/RequiresFramework35SP1Assembly.cs +++ b/src/Tasks/RequiresFramework35SP1Assembly.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; diff --git a/src/Tasks/ResGen.cs b/src/Tasks/ResGen.cs index 8c45e0a33c1..731c376b5e2 100644 --- a/src/Tasks/ResGen.cs +++ b/src/Tasks/ResGen.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -425,8 +425,7 @@ protected override bool ValidateParameters() if ( !String.IsNullOrEmpty(StronglyTypedClassName) || !String.IsNullOrEmpty(StronglyTypedNamespace) || - !String.IsNullOrEmpty(StronglyTypedFileName) - ) + !String.IsNullOrEmpty(StronglyTypedFileName)) { // We have no language to generate a STR, but nevertheless the user passed us a class, // namespace, and/or filename. Let them know that they probably wanted to pass a language too. @@ -514,15 +513,13 @@ private string GenerateResGenFullPath() // If it still hasn't been found, try to generate the appropriate path. if (pathToTool == null) { - pathToTool = SdkToolsPathUtility.GeneratePathToTool - ( + pathToTool = SdkToolsPathUtility.GeneratePathToTool( SdkToolsPathUtility.FileInfoExists, MSBuildProcessorArchitecture.CurrentProcessArchitecture, SdkToolsPath, ToolExe, Log, - true /* log errors and warnings */ - ); + true); /* log errors and warnings */ pathToTool = NativeMethodsShared.GetLongFilePath(pathToTool); } @@ -600,11 +597,9 @@ private void GenerateResGenCommands(CommandLineBuilderExtension resGenArguments, } else { - resGenArguments.AppendFileNamesIfNotNull - ( + resGenArguments.AppendFileNamesIfNotNull( new[] { inputFiles[i], outputFiles[i] }, - "," - ); + ","); } } } @@ -616,12 +611,10 @@ private void GenerateResGenCommands(CommandLineBuilderExtension resGenArguments, resGenArguments.AppendFileNamesIfNotNull(OutputFiles, " "); // append the strongly-typed resource details - resGenArguments.AppendSwitchIfNotNull - ( + resGenArguments.AppendSwitchIfNotNull( "/str:", new[] { StronglyTypedLanguage, StronglyTypedNamespace, StronglyTypedClassName, StronglyTypedFileName }, - "," - ); + ","); } } diff --git a/src/Tasks/ResGenDependencies.cs b/src/Tasks/ResGenDependencies.cs index 530982c0f32..ea0be01f3fa 100644 --- a/src/Tasks/ResGenDependencies.cs +++ b/src/Tasks/ResGenDependencies.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -106,7 +106,8 @@ public override void Translate(ITranslator translator) { translator.TranslateDictionary(ref resXFiles, (ITranslator translator, ref string s) => translator.Translate(ref s), - (ITranslator translator, ref ResXFile resx) => { + (ITranslator translator, ref ResXFile resx) => + { ResXFile temp = resx ?? new(); temp.Translate(translator); resx = temp; @@ -114,7 +115,8 @@ public override void Translate(ITranslator translator) count => new Dictionary(count)); translator.TranslateDictionary(ref portableLibraries, (ITranslator translator, ref string s) => translator.Translate(ref s), - (ITranslator translator, ref PortableLibraryFile portableLibrary) => { + (ITranslator translator, ref PortableLibraryFile portableLibrary) => + { PortableLibraryFile temp = portableLibrary ?? new(); temp.Translate(translator); portableLibrary = temp; @@ -415,7 +417,7 @@ internal bool Equals(PortableLibraryFile otherLibrary) return true; } } - + /// /// Whether this cache is dirty or not. /// diff --git a/src/Tasks/ResolveCodeAnalysisRuleSet.cs b/src/Tasks/ResolveCodeAnalysisRuleSet.cs index 474e6b46795..3bcb41882e1 100644 --- a/src/Tasks/ResolveCodeAnalysisRuleSet.cs +++ b/src/Tasks/ResolveCodeAnalysisRuleSet.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using Microsoft.Build.Framework; diff --git a/src/Tasks/ResolveComReference.cs b/src/Tasks/ResolveComReference.cs index bdca81a2457..0c7348a73ac 100644 --- a/src/Tasks/ResolveComReference.cs +++ b/src/Tasks/ResolveComReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; #if !RUNTIME_TYPE_NETCORE @@ -141,6 +141,7 @@ internal interface IResolveComReferenceTaskContract /// public sealed partial class ResolveComReference : Microsoft.Build.Tasks.TaskExtension, IResolveComReferenceTaskContract { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Properties public ITaskItem[] TypeLibNames { get; set; } @@ -196,6 +197,7 @@ public override bool Execute() } #endregion +#pragma warning restore format } #else @@ -205,6 +207,7 @@ public override bool Execute() /// public sealed partial class ResolveComReference : AppDomainIsolatedTaskExtension, IResolveComReferenceTaskContract, IComReferenceResolver { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Properties public ITaskItem[] TypeLibNames { get; set; } @@ -287,7 +290,7 @@ public string TargetProcessorArchitecture public string TargetFrameworkVersion { get; set; } = String.Empty; private Version _projectTargetFramework; - + /// version 4.0 private static readonly Version s_targetFrameworkVersion_40 = new Version("4.0"); @@ -850,13 +853,11 @@ internal void AddMissingTlbReferences() /// /// Resolves the COM reference, and adds it to the appropriate item list. /// - private bool ResolveReferenceAndAddToList - ( + private bool ResolveReferenceAndAddToList( ComDependencyWalker dependencyWalker, ComReferenceInfo projectRefInfo, List resolvedReferenceList, - List moduleList - ) + List moduleList) { if (ResolveReference(dependencyWalker, projectRefInfo, WrapperOutputDirectory, out ITaskItem referencePath)) { @@ -1164,7 +1165,9 @@ bool IComReferenceResolver.ResolveNetAssemblyReference(string assemblyName, out // if we have a strong name, strip off everything but the assembly name if (commaIndex != -1) + { assemblyName = assemblyName.Substring(0, commaIndex); + } assemblyName += ".dll"; @@ -1767,6 +1770,7 @@ internal static TYPELIBATTR TaskItemToTypeLibAttr(ITaskItem taskItem) } #endregion +#pragma warning restore format } #endif diff --git a/src/Tasks/ResolveComReferenceCache.cs b/src/Tasks/ResolveComReferenceCache.cs index 1d6d7f2f006..b140ed58af7 100644 --- a/src/Tasks/ResolveComReferenceCache.cs +++ b/src/Tasks/ResolveComReferenceCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -36,7 +36,7 @@ internal sealed class ResolveComReferenceCache : StateFileBase, ITranslatable /// indicates whether the cache contents have changed since it's been created /// internal bool Dirty => _dirty; - + [NonSerialized] private bool _dirty; diff --git a/src/Tasks/ResolveKeySource.cs b/src/Tasks/ResolveKeySource.cs index 9960105ee1d..be85bca1a5f 100644 --- a/src/Tasks/ResolveKeySource.cs +++ b/src/Tasks/ResolveKeySource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -27,7 +27,7 @@ public class ResolveKeySource : TaskExtension #if !RUNTIME_TYPE_NETCORE private const string pfxFileContainerPrefix = "VS_KEY_"; #endif - + #region Properties public string KeyFile { get; set; } diff --git a/src/Tasks/ResolveManifestFiles.cs b/src/Tasks/ResolveManifestFiles.cs index 80e55c6aaca..9b98bcf97a8 100644 --- a/src/Tasks/ResolveManifestFiles.cs +++ b/src/Tasks/ResolveManifestFiles.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -127,7 +127,7 @@ public ITaskItem[] SatelliteAssemblies public string AssemblyName { get; set; } - public bool LauncherBasedDeployment {get; set; } = false; + public bool LauncherBasedDeployment { get; set; } = false; public string TargetFrameworkVersion { @@ -853,7 +853,7 @@ public void Add(ITaskItem item) } else { - fusionName = Path.GetFileNameWithoutExtension(item.ItemSpec); + fusionName = Path.GetFileNameWithoutExtension(item.ItemSpec); } } @@ -953,7 +953,11 @@ public void Add(ITaskItem item, bool includedByDefault) { string targetPath = GetItemTargetPath(item); Debug.Assert(!String.IsNullOrEmpty(targetPath)); - if (String.IsNullOrEmpty(targetPath)) return; + if (String.IsNullOrEmpty(targetPath)) + { + return; + } + string key = targetPath.ToLowerInvariant(); Debug.Assert(!_dictionary.ContainsKey(key), String.Format(CultureInfo.CurrentCulture, "Two or more items with same '{0}' attribute detected", ItemMetadataNames.targetPath)); var entry = new MapEntry(item, includedByDefault); diff --git a/src/Tasks/ResolveNativeReference.cs b/src/Tasks/ResolveNativeReference.cs index a765f4a4d7a..66a5ac3c70b 100644 --- a/src/Tasks/ResolveNativeReference.cs +++ b/src/Tasks/ResolveNativeReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -140,10 +140,12 @@ public override bool Execute() try { #endif - if (!ExtractFromManifest(NativeReferences[reference], path, containingReferenceFilesTable, containedPrerequisiteAssembliesTable, containedComComponentsTable, containedTypeLibrariesTable, containedLooseTlbFilesTable, containedLooseEtcFilesTable)) - { - retValue = false; - } +#pragma warning disable format //invalid formatting in Release when try-catch is skipped + if (!ExtractFromManifest(NativeReferences[reference], path, containingReferenceFilesTable, containedPrerequisiteAssembliesTable, containedComComponentsTable, containedTypeLibrariesTable, containedLooseTlbFilesTable, containedLooseEtcFilesTable)) + { + retValue = false; + } +#pragma warning restore format #if DEBUG } catch (Exception) diff --git a/src/Tasks/ResolveNonMSBuildProjectOutput.cs b/src/Tasks/ResolveNonMSBuildProjectOutput.cs index 96779b3374d..6667c4bb082 100644 --- a/src/Tasks/ResolveNonMSBuildProjectOutput.cs +++ b/src/Tasks/ResolveNonMSBuildProjectOutput.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/ResolveProjectBase.cs b/src/Tasks/ResolveProjectBase.cs index 3995d2a35f1..7be78aa7458 100644 --- a/src/Tasks/ResolveProjectBase.cs +++ b/src/Tasks/ResolveProjectBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/ResolveSDKReference.cs b/src/Tasks/ResolveSDKReference.cs index 9936453c588..e8ea34b2e30 100644 --- a/src/Tasks/ResolveSDKReference.cs +++ b/src/Tasks/ResolveSDKReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -37,11 +37,9 @@ public class ResolveSDKReference : TaskExtension /// Regex for breaking up the sdk reference include into pieces. /// Example: XNA, Version=8.0 /// - private static readonly Regex s_sdkReferenceFormat = new Regex - ( + private static readonly Regex s_sdkReferenceFormat = new Regex( @"(?^[^,]*),\s*Version=(?.*)", - RegexOptions.IgnoreCase - ); + RegexOptions.IgnoreCase); /// /// SimpleName group diff --git a/src/Tasks/ResourceHandling/BinaryFormatterByteArrayResource.cs b/src/Tasks/ResourceHandling/BinaryFormatterByteArrayResource.cs index 42dcdf53794..3aaa1b89c12 100644 --- a/src/Tasks/ResourceHandling/BinaryFormatterByteArrayResource.cs +++ b/src/Tasks/ResourceHandling/BinaryFormatterByteArrayResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Resources.Extensions; diff --git a/src/Tasks/ResourceHandling/FileStreamResource.cs b/src/Tasks/ResourceHandling/FileStreamResource.cs index 6c93f0464c5..ea29bf5b772 100644 --- a/src/Tasks/ResourceHandling/FileStreamResource.cs +++ b/src/Tasks/ResourceHandling/FileStreamResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Resources; diff --git a/src/Tasks/ResourceHandling/IResource.cs b/src/Tasks/ResourceHandling/IResource.cs index 891d9e8f8c5..3856774fac8 100644 --- a/src/Tasks/ResourceHandling/IResource.cs +++ b/src/Tasks/ResourceHandling/IResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; diff --git a/src/Tasks/ResourceHandling/InputFormatNotSupportedException.cs b/src/Tasks/ResourceHandling/InputFormatNotSupportedException.cs index b756eb62bd9..a6b797a7d94 100644 --- a/src/Tasks/ResourceHandling/InputFormatNotSupportedException.cs +++ b/src/Tasks/ResourceHandling/InputFormatNotSupportedException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/ResourceHandling/LiveObjectResource.cs b/src/Tasks/ResourceHandling/LiveObjectResource.cs index 4bc3f884d30..5a051dc2097 100644 --- a/src/Tasks/ResourceHandling/LiveObjectResource.cs +++ b/src/Tasks/ResourceHandling/LiveObjectResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; diff --git a/src/Tasks/ResourceHandling/MSBuildResXException.cs b/src/Tasks/ResourceHandling/MSBuildResXException.cs index 7eac7ce9a2a..ce6d5b589c2 100644 --- a/src/Tasks/ResourceHandling/MSBuildResXException.cs +++ b/src/Tasks/ResourceHandling/MSBuildResXException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/ResourceHandling/MSBuildResXReader.cs b/src/Tasks/ResourceHandling/MSBuildResXReader.cs index 91786f0f529..9e1cea4fcd4 100644 --- a/src/Tasks/ResourceHandling/MSBuildResXReader.cs +++ b/src/Tasks/ResourceHandling/MSBuildResXReader.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using System; @@ -52,7 +52,7 @@ public static IReadOnlyList ReadResources(Stream s, string filename, } } - private static void ParseAssemblyAlias(Dictionary aliases, XElement elem) + private static void ParseAssemblyAlias(Dictionary aliases, XElement elem) { string alias = elem.Attribute("alias")?.Value; string name = elem.Attribute("name").Value; @@ -101,7 +101,7 @@ private static string GetFullTypeNameFromAlias(string aliasedTypeName, Dictionar return aliasedTypeName; } - private static void ParseData(string resxFilename, bool pathsRelativeToBasePath, List resources, Dictionary aliases, XElement elem) + private static void ParseData(string resxFilename, bool pathsRelativeToBasePath, List resources, Dictionary aliases, XElement elem) { string name = elem.Attribute("name").Value; string value; @@ -313,20 +313,32 @@ internal static string[] ParseResxFileRefString(string stringValue) { int lastIndexOfQuote = stringValue.LastIndexOf("\""); if (lastIndexOfQuote - 1 < 0) + { throw new ArgumentException(nameof(stringValue)); + } + fileName = stringValue.Substring(1, lastIndexOfQuote - 1); // remove the quotes in" ..... " if (lastIndexOfQuote + 2 > stringValue.Length) + { throw new ArgumentException(nameof(stringValue)); + } + remainingString = stringValue.Substring(lastIndexOfQuote + 2); } else { int nextSemiColumn = stringValue.IndexOf(";"); if (nextSemiColumn == -1) + { throw new ArgumentException(nameof(stringValue)); + } + fileName = stringValue.Substring(0, nextSemiColumn); if (nextSemiColumn + 1 > stringValue.Length) + { throw new ArgumentException(nameof(stringValue)); + } + remainingString = stringValue.Substring(nextSemiColumn + 1); } string[] parts = remainingString.Split(';'); diff --git a/src/Tasks/ResourceHandling/NameUtilities.cs b/src/Tasks/ResourceHandling/NameUtilities.cs index 6b07b11c0c4..13f0f795e98 100644 --- a/src/Tasks/ResourceHandling/NameUtilities.cs +++ b/src/Tasks/ResourceHandling/NameUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; @@ -7,7 +7,7 @@ namespace Microsoft.Build.Tasks.ResourceHandling { - static class NameUtilities + internal static class NameUtilities { /// /// Extract the full name of a type from an assembly-qualified name string. diff --git a/src/Tasks/ResourceHandling/PreserializedResourceWriterRequiredException.cs b/src/Tasks/ResourceHandling/PreserializedResourceWriterRequiredException.cs index ef532e02a0c..d72a71f17b0 100644 --- a/src/Tasks/ResourceHandling/PreserializedResourceWriterRequiredException.cs +++ b/src/Tasks/ResourceHandling/PreserializedResourceWriterRequiredException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/ResourceHandling/StringResource.cs b/src/Tasks/ResourceHandling/StringResource.cs index 9e2ca1c6ff7..7b082804b7b 100644 --- a/src/Tasks/ResourceHandling/StringResource.cs +++ b/src/Tasks/ResourceHandling/StringResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; diff --git a/src/Tasks/ResourceHandling/TypeConverterByteArrayResource.cs b/src/Tasks/ResourceHandling/TypeConverterByteArrayResource.cs index 6b65b7e72a7..d239ec802c7 100644 --- a/src/Tasks/ResourceHandling/TypeConverterByteArrayResource.cs +++ b/src/Tasks/ResourceHandling/TypeConverterByteArrayResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Resources.Extensions; diff --git a/src/Tasks/ResourceHandling/TypeConverterStringResource.cs b/src/Tasks/ResourceHandling/TypeConverterStringResource.cs index 09035c4e3fb..35efc4928bf 100644 --- a/src/Tasks/ResourceHandling/TypeConverterStringResource.cs +++ b/src/Tasks/ResourceHandling/TypeConverterStringResource.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Resources; using System.Resources.Extensions; diff --git a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs index abeba2b2791..70c13531635 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCodeType.cs b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCodeType.cs index d8dc633f91f..b3adf5e45a6 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCodeType.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCodeType.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCompilers.cs b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCompilers.cs index 4606d244cd7..ff9fc4289ef 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCompilers.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryCompilers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; diff --git a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryTaskInfo.cs b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryTaskInfo.cs index 9cf70c2535d..72993020895 100644 --- a/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryTaskInfo.cs +++ b/src/Tasks/RoslynCodeTaskFactory/RoslynCodeTaskFactoryTaskInfo.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/SGen.cs b/src/Tasks/SGen.cs index 3e540d14394..8ed872450f0 100644 --- a/src/Tasks/SGen.cs +++ b/src/Tasks/SGen.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if !RUNTIME_TYPE_NETCORE using System; @@ -22,7 +22,7 @@ namespace Microsoft.Build.Tasks /// internal interface ISGenTaskContract { - #region Properties + #region Properties // Input files [Required] @@ -64,13 +64,14 @@ internal interface ISGenTaskContract /// string[] Types { get; set; } - #endregion + #endregion } #if RUNTIME_TYPE_NETCORE public class SGen : ToolTaskExtension, ISGenTaskContract { - #region Properties +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both + #region Properties [Required] public string BuildAssemblyName { get; set; } @@ -105,9 +106,9 @@ public class SGen : ToolTaskExtension, ISGenTaskContract public string[] Types { get; set; } - #endregion + #endregion - #region Tool Members + #region Tool Members protected override string ToolName { @@ -130,7 +131,8 @@ public override bool Execute() return false; } - #endregion + #endregion +#pragma warning restore format } #else /// @@ -139,6 +141,7 @@ public override bool Execute() public class SGen : ToolTaskExtension, ISGenTaskContract { private string _buildAssemblyPath; +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Properties // Input files @@ -453,6 +456,7 @@ protected override string GenerateCommandLineCommands() } #endregion +#pragma warning restore format } #endif } diff --git a/src/Tasks/SdkToolsPathUtility.cs b/src/Tasks/SdkToolsPathUtility.cs index 79e6ce9defe..bacccd00dad 100644 --- a/src/Tasks/SdkToolsPathUtility.cs +++ b/src/Tasks/SdkToolsPathUtility.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -60,9 +60,9 @@ internal static string GeneratePathToTool(FileExists fileExists, string currentA { // There may not be an arm directory so we will fall back to the x86 tool location // but if there is then we should try and use it. - ProcessorArchitecture.ARM => Path.Combine(sdkToolsPath, "arm"), + ProcessorArchitecture.ARM => Path.Combine(sdkToolsPath, "arm"), ProcessorArchitecture.AMD64 => Path.Combine(sdkToolsPath, "x64"), - ProcessorArchitecture.IA64 => Path.Combine(sdkToolsPath, "ia64"), + ProcessorArchitecture.IA64 => Path.Combine(sdkToolsPath, "ia64"), _ => sdkToolsPath, }; pathToTool = Path.Combine(processorSpecificToolDirectory, toolName); diff --git a/src/Tasks/SetRidAgnosticValueForProjects.cs b/src/Tasks/SetRidAgnosticValueForProjects.cs index 689a4eb9711..f2c9290abfa 100644 --- a/src/Tasks/SetRidAgnosticValueForProjects.cs +++ b/src/Tasks/SetRidAgnosticValueForProjects.cs @@ -1,6 +1,5 @@ // 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.Linq; @@ -51,7 +50,7 @@ public override bool Execute() } updatedItem.SetMetadata("IsRidAgnostic", isRidAgnosticArray[targetFrameworkIndex]); - + return updatedItem; }) .ToArray(); diff --git a/src/Tasks/SignFile.cs b/src/Tasks/SignFile.cs index 379fe059587..b07e6370082 100644 --- a/src/Tasks/SignFile.cs +++ b/src/Tasks/SignFile.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.ComponentModel; @@ -53,8 +53,8 @@ public override bool Execute() SecurityUtilities.SignFile( CertificateThumbprint, TimestampUrl == null ? null : new Uri(TimestampUrl), - SigningTarget.ItemSpec, - TargetFrameworkVersion, + SigningTarget.ItemSpec, + TargetFrameworkVersion, TargetFrameworkIdentifier, DisallowMansignTimestampFallback); return true; diff --git a/src/Tasks/StateFileBase.cs b/src/Tasks/StateFileBase.cs index 4d8d2de3422..5c674fb9732 100644 --- a/src/Tasks/StateFileBase.cs +++ b/src/Tasks/StateFileBase.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -99,7 +99,7 @@ internal static StateFileBase DeserializeCache(string stateFile, TaskLoggingHelp retVal = constructor.Invoke(new object[] { translator }) as StateFileBase; } } - + if (retVal == null || !requiredReturnType.IsInstanceOfType(retVal)) { log.LogMessageFromResources("General.CouldNotReadStateFileMessage", stateFile, diff --git a/src/Tasks/StrongNameException.cs b/src/Tasks/StrongNameException.cs index 2ea63bf9491..899f4ed825b 100644 --- a/src/Tasks/StrongNameException.cs +++ b/src/Tasks/StrongNameException.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Serialization; diff --git a/src/Tasks/StrongNameUtils.cs b/src/Tasks/StrongNameUtils.cs index 1102627ce30..2e223cc2c74 100644 --- a/src/Tasks/StrongNameUtils.cs +++ b/src/Tasks/StrongNameUtils.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Tasks/System.Design.cs b/src/Tasks/System.Design.cs index 0ab4947d7b6..2c417146818 100644 --- a/src/Tasks/System.Design.cs +++ b/src/Tasks/System.Design.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Reflection; @@ -99,7 +99,7 @@ public MainAssemblyFallbackResourceManager(string baseName, Assembly assembly) : internal SR() { - _resources = new MainAssemblyFallbackResourceManager("System.Design", this.GetType().Assembly); + _resources = new MainAssemblyFallbackResourceManager("System.Design", this.GetType().Assembly); } private static SR GetLoader() @@ -129,7 +129,10 @@ public static string GetString(string name, params object[] args) { SR sys = GetLoader(); if (sys == null) + { return null; + } + string res = sys._resources.GetString(name, SR.Culture); if (args?.Length > 0) @@ -154,7 +157,10 @@ public static string GetString(string name) { SR sys = GetLoader(); if (sys == null) + { return null; + } + return sys._resources.GetString(name, SR.Culture); } @@ -169,7 +175,10 @@ public static object GetObject(string name) { SR sys = GetLoader(); if (sys == null) + { return null; + } + return sys._resources.GetObject(name, SR.Culture); } } diff --git a/src/Tasks/SystemState.cs b/src/Tasks/SystemState.cs index da98c85bd10..9e174d054ca 100644 --- a/src/Tasks/SystemState.cs +++ b/src/Tasks/SystemState.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Concurrent; @@ -230,10 +230,8 @@ public SystemState(ITranslator translator) /// of the FX folders. /// /// List of Assembly Table Info. - internal void SetInstalledAssemblyInformation - ( - AssemblyTableInfo[] installedAssemblyTableInfos - ) + internal void SetInstalledAssemblyInformation( + AssemblyTableInfo[] installedAssemblyTableInfos) { redistList = RedistList.GetRedistList(installedAssemblyTableInfos); } @@ -245,7 +243,9 @@ AssemblyTableInfo[] installedAssemblyTableInfos public override void Translate(ITranslator translator) { if (instanceLocalFileStateCache is null) + { throw new NullReferenceException(nameof(instanceLocalFileStateCache)); + } translator.TranslateDictionary( ref instanceLocalFileStateCache, @@ -361,7 +361,7 @@ private FileState ComputeFileStateFromCachesAndDisk(string path) DateTime lastModified = GetAndCacheLastModified(path); bool isCachedInInstance = instanceLocalFileStateCache.TryGetValue(path, out FileState cachedInstanceFileState); bool isCachedInProcess = s_processWideFileStateCache.TryGetValue(path, out FileState cachedProcessFileState); - + bool isInstanceFileStateUpToDate = isCachedInInstance && lastModified == cachedInstanceFileState.LastModified; bool isProcessFileStateUpToDate = isCachedInProcess && lastModified == cachedProcessFileState.LastModified; @@ -421,10 +421,8 @@ private AssemblyNameExtension GetAssemblyName(string path) if (string.Equals(extension, ".dll", StringComparison.OrdinalIgnoreCase)) { - IEnumerable assemblyNames = redistList.FindAssemblyNameFromSimpleName - ( - Path.GetFileNameWithoutExtension(path) - ); + IEnumerable assemblyNames = redistList.FindAssemblyNameFromSimpleName( + Path.GetFileNameWithoutExtension(path)); string filename = Path.GetFileName(path); foreach (AssemblyEntry a in assemblyNames) @@ -438,7 +436,7 @@ private AssemblyNameExtension GetAssemblyName(string path) } } } - + // Not a well-known FX assembly so now check the cache. FileState fileState = GetFileState(path); if (fileState.Assembly == null) @@ -488,26 +486,22 @@ private string GetRuntimeVersion(string path) /// Receives the list of dependencies. /// Receives the list of associated scatter files. /// - private void GetAssemblyMetadata - ( + private void GetAssemblyMetadata( string path, ConcurrentDictionary assemblyMetadataCache, out AssemblyNameExtension[] dependencies, out string[] scatterFiles, - out FrameworkName frameworkName - ) + out FrameworkName frameworkName) { FileState fileState = GetFileState(path); if (fileState.dependencies == null) { - getAssemblyMetadata - ( + getAssemblyMetadata( path, assemblyMetadataCache, out fileState.dependencies, out fileState.scatterFiles, - out fileState.frameworkName - ); + out fileState.frameworkName); isDirty = true; } diff --git a/src/Tasks/TaskExtension.cs b/src/Tasks/TaskExtension.cs index 2e87720584a..2e2f35096c0 100644 --- a/src/Tasks/TaskExtension.cs +++ b/src/Tasks/TaskExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Shared; using Microsoft.Build.Utilities; diff --git a/src/Tasks/TaskTranslatorHelpers.cs b/src/Tasks/TaskTranslatorHelpers.cs index 6e43de0c3a4..f12b4cda30a 100644 --- a/src/Tasks/TaskTranslatorHelpers.cs +++ b/src/Tasks/TaskTranslatorHelpers.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Runtime.Versioning; @@ -14,7 +14,9 @@ internal static class TaskTranslatorHelpers public static void Translate(this ITranslator translator, ref FrameworkName frameworkName) { if (!translator.TranslateNullable(frameworkName)) + { return; + } string identifier = null; Version version = null; diff --git a/src/Tasks/Telemetry.cs b/src/Tasks/Telemetry.cs index 5e550be948a..894fafea3db 100644 --- a/src/Tasks/Telemetry.cs +++ b/src/Tasks/Telemetry.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Shared; diff --git a/src/Tasks/TlbImp.cs b/src/Tasks/TlbImp.cs index 2debd69fa9b..1c9bc7c6228 100644 --- a/src/Tasks/TlbImp.cs +++ b/src/Tasks/TlbImp.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Tasks/TlbReference.cs b/src/Tasks/TlbReference.cs index f08ae5f4d27..4f438378071 100644 --- a/src/Tasks/TlbReference.cs +++ b/src/Tasks/TlbReference.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; @@ -317,36 +317,28 @@ private void WriteWrapperToDisk(AssemblyBuilder assemblyBuilder, string wrapperP switch (_targetProcessorArchitecture) { case UtilitiesProcessorArchitecture.X86: - assemblyBuilder.Save - ( + assemblyBuilder.Save( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, - ImageFileMachine.I386 - ); + ImageFileMachine.I386); break; case UtilitiesProcessorArchitecture.AMD64: - assemblyBuilder.Save - ( + assemblyBuilder.Save( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, - ImageFileMachine.AMD64 - ); + ImageFileMachine.AMD64); break; case UtilitiesProcessorArchitecture.IA64: - assemblyBuilder.Save - ( + assemblyBuilder.Save( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.PE32Plus, - ImageFileMachine.IA64 - ); + ImageFileMachine.IA64); break; case UtilitiesProcessorArchitecture.ARM: - assemblyBuilder.Save - ( + assemblyBuilder.Save( wrapperFile.Name, PortableExecutableKinds.ILOnly | PortableExecutableKinds.Required32Bit, - ImageFileMachine.ARM - ); + ImageFileMachine.ARM); break; case UtilitiesProcessorArchitecture.MSIL: default: diff --git a/src/Tasks/ToolTaskExtension.cs b/src/Tasks/ToolTaskExtension.cs index 8a5b14510f4..a162e7eb4f5 100644 --- a/src/Tasks/ToolTaskExtension.cs +++ b/src/Tasks/ToolTaskExtension.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using Microsoft.Build.Shared; diff --git a/src/Tasks/Touch.cs b/src/Tasks/Touch.cs index 77a2060bdd3..08da8b86dc8 100644 --- a/src/Tasks/Touch.cs +++ b/src/Tasks/Touch.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -49,15 +49,13 @@ public class Touch : TaskExtension /// Implementation of the execute method. /// /// - internal bool ExecuteImpl - ( + internal bool ExecuteImpl( FileExists fileExists, FileCreate fileCreate, GetAttributes fileGetAttributes, SetAttributes fileSetAttributes, SetLastAccessTime fileSetLastAccessTime, - SetLastWriteTime fileSetLastWriteTime - ) + SetLastWriteTime fileSetLastWriteTime) { // See what time we are touching all files to DateTime touchDateTime; @@ -89,8 +87,7 @@ SetLastWriteTime fileSetLastWriteTime // touched items. if ( - TouchFile - ( + TouchFile( path, touchDateTime, fileExists, @@ -98,9 +95,7 @@ SetLastWriteTime fileSetLastWriteTime fileGetAttributes, fileSetAttributes, fileSetLastAccessTime, - fileSetLastWriteTime - ) - ) + fileSetLastWriteTime)) { touchedItems.Add(file); } @@ -125,15 +120,13 @@ SetLastWriteTime fileSetLastWriteTime /// public override bool Execute() { - return ExecuteImpl - ( + return ExecuteImpl( File.Exists, File.Create, File.GetAttributes, File.SetAttributes, File.SetLastAccessTime, - File.SetLastWriteTime - ); + File.SetLastWriteTime); } /// @@ -142,11 +135,9 @@ public override bool Execute() /// /// /// "true" if the file was created. - private bool CreateFile - ( + private bool CreateFile( string file, - FileCreate fileCreate - ) + FileCreate fileCreate) { try { @@ -167,8 +158,7 @@ FileCreate fileCreate /// Helper method touches a file. /// /// "True" if the file was touched. - private bool TouchFile - ( + private bool TouchFile( string file, DateTime dt, FileExists fileExists, @@ -176,8 +166,7 @@ private bool TouchFile GetAttributes fileGetAttributes, SetAttributes fileSetAttributes, SetLastAccessTime fileSetLastAccessTime, - SetLastWriteTime fileSetLastWriteTime - ) + SetLastWriteTime fileSetLastWriteTime) { if (!fileExists(file)) { diff --git a/src/Tasks/UnregisterAssembly.cs b/src/Tasks/UnregisterAssembly.cs index 88e0ed11611..fb74aec9202 100644 --- a/src/Tasks/UnregisterAssembly.cs +++ b/src/Tasks/UnregisterAssembly.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_APPDOMAIN @@ -118,7 +118,7 @@ public override bool Execute() #if DEBUG catch (Exception e) { - Debug.Assert(false, "Unexpected exception in AssemblyRegistration.Execute. " + + Debug.Assert(false, "Unexpected exception in AssemblyRegistration.Execute. " + "Please log a MSBuild bug specifying the steps to reproduce the problem. " + e.Message); throw; @@ -267,7 +267,7 @@ private bool Unregister(string assemblyPath, string typeLibPath) else { #if DEBUG - Debug.Assert(false, "Unexpected exception in UnregisterAssembly.DoExecute. " + + Debug.Assert(false, "Unexpected exception in UnregisterAssembly.DoExecute. " + "Please log a MSBuild bug specifying the steps to reproduce the problem."); #endif throw; diff --git a/src/Tasks/Unzip.cs b/src/Tasks/Unzip.cs index eff8d18aec5..df5e28463e7 100644 --- a/src/Tasks/Unzip.cs +++ b/src/Tasks/Unzip.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/UpdateManifest.cs b/src/Tasks/UpdateManifest.cs index ebefc10a2d1..0e9e78bef9c 100644 --- a/src/Tasks/UpdateManifest.cs +++ b/src/Tasks/UpdateManifest.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using Microsoft.Build.Tasks.Deployment.ManifestUtilities; diff --git a/src/Tasks/VisualBasicParserUtilities.cs b/src/Tasks/VisualBasicParserUtilities.cs index b92543818a5..4a333cd6675 100644 --- a/src/Tasks/VisualBasicParserUtilities.cs +++ b/src/Tasks/VisualBasicParserUtilities.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.IO; using System.Text; diff --git a/src/Tasks/Warning.cs b/src/Tasks/Warning.cs index 60b7ca674f3..ce60c6a1945 100644 --- a/src/Tasks/Warning.cs +++ b/src/Tasks/Warning.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #nullable disable diff --git a/src/Tasks/WinMDExp.cs b/src/Tasks/WinMDExp.cs index a77dfbef18c..28e2662c997 100644 --- a/src/Tasks/WinMDExp.cs +++ b/src/Tasks/WinMDExp.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics.CodeAnalysis; diff --git a/src/Tasks/WriteCodeFragment.cs b/src/Tasks/WriteCodeFragment.cs index a781f20b2c3..6f53fd01eba 100644 --- a/src/Tasks/WriteCodeFragment.cs +++ b/src/Tasks/WriteCodeFragment.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.CodeDom; @@ -253,8 +253,7 @@ private string GenerateCode(out string extension) // as well as within the namespaces that we automatically import. Lazy attributeType = new( () => Type.GetType(attribute.Name, throwOnError: false) ?? NamespaceImports.Select(x => Type.GetType($"{x}.{attribute.Name}", throwOnError: false)).FirstOrDefault(), - System.Threading.LazyThreadSafetyMode.None - ); + System.Threading.LazyThreadSafetyMode.None); if ( !AddArguments(attribute, attributeType, providedOrderedParameters, isPositional: true) @@ -319,7 +318,8 @@ private IReadOnlyDictionary ExtractParameterTypes(IDictio keysToRemove.Add(key); // The parameter will have an explicit type. The metadata value is the type name. - parameterTypes[parameterNameKey] = new ParameterType { + parameterTypes[parameterNameKey] = new ParameterType + { Kind = ParameterTypeKind.Typed, TypeName = value }; @@ -351,7 +351,8 @@ private IReadOnlyDictionary ExtractParameterTypes(IDictio // that needs to be written to the generated file for that parameter. if (string.Equals(value, "true", StringComparison.OrdinalIgnoreCase)) { - parameterTypes[parameterNameKey] = new ParameterType { + parameterTypes[parameterNameKey] = new ParameterType + { Kind = ParameterTypeKind.Literal }; } @@ -381,8 +382,7 @@ private bool AddArguments( CodeAttributeDeclaration attribute, Lazy attributeType, IReadOnlyList parameters, - bool isPositional - ) + bool isPositional) { Type[] constructorParameterTypes = null; @@ -433,8 +433,7 @@ bool isPositional value = ConvertParameterValueToInferredType( constructorParameterTypes[i], parameter.Value, - $"#{i + 1}" /* back to 1 based */ - ); + $"#{i + 1}"); /* back to 1 based */ } else { @@ -442,8 +441,7 @@ bool isPositional value = ConvertParameterValueToInferredType( attributeType.Value?.GetProperty(parameter.Name)?.PropertyType, parameter.Value, - parameter.Name - ); + parameter.Name); } break; diff --git a/src/Tasks/XamlTaskFactory/CommandLineGenerator.cs b/src/Tasks/XamlTaskFactory/CommandLineGenerator.cs index 554e77cb6b7..19692a2fec9 100644 --- a/src/Tasks/XamlTaskFactory/CommandLineGenerator.cs +++ b/src/Tasks/XamlTaskFactory/CommandLineGenerator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/XamlTaskFactory/CommandLineToolSwitch.cs b/src/Tasks/XamlTaskFactory/CommandLineToolSwitch.cs index a74a8143b66..a1abf73861f 100644 --- a/src/Tasks/XamlTaskFactory/CommandLineToolSwitch.cs +++ b/src/Tasks/XamlTaskFactory/CommandLineToolSwitch.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/XamlTaskFactory/Property.cs b/src/Tasks/XamlTaskFactory/Property.cs index 10a3579e486..e035df86c4c 100644 --- a/src/Tasks/XamlTaskFactory/Property.cs +++ b/src/Tasks/XamlTaskFactory/Property.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/XamlTaskFactory/RelationsParser.cs b/src/Tasks/XamlTaskFactory/RelationsParser.cs index a8e2ace0c3e..f6f9f9687c3 100644 --- a/src/Tasks/XamlTaskFactory/RelationsParser.cs +++ b/src/Tasks/XamlTaskFactory/RelationsParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/XamlTaskFactory/TaskGenerator.cs b/src/Tasks/XamlTaskFactory/TaskGenerator.cs index 28a24d722ea..20ee37d6014 100644 --- a/src/Tasks/XamlTaskFactory/TaskGenerator.cs +++ b/src/Tasks/XamlTaskFactory/TaskGenerator.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -942,7 +942,9 @@ private void GenerateStrings(Property property, CodeMemberProperty propertyName) private bool ContainsCurrentPlatform(Property property) { if (Platform == null) + { return true; + } if (property.Values.Count > 0) { @@ -966,7 +968,9 @@ private bool ContainsCurrentPlatform(string SwitchValue) { // If we don't have a platform defined it meens all if (Platform == null) + { return true; + } if (_relationsParser.SwitchRelationsList.TryGetValue(SwitchValue, out SwitchRelations rel)) { @@ -975,7 +979,9 @@ private bool ContainsCurrentPlatform(string SwitchValue) foreach (string excludedPlatform in rel.ExcludedPlatforms) { if (Platform == excludedPlatform) + { return false; + } } } if (rel.IncludedPlatforms.Count > 0) @@ -984,7 +990,9 @@ private bool ContainsCurrentPlatform(string SwitchValue) foreach (string includedPlatform in rel.IncludedPlatforms) { if (Platform == includedPlatform) + { isIncluded = true; + } } return isIncluded; } @@ -1185,8 +1193,8 @@ private void GenerateRelations(CodeTypeDeclaration taskClass) } } - checkRequired.TrueStatements.Add(new CodeMethodInvokeExpression - (new CodeThisReferenceExpression(), "RemoveSwitchToolBasedOnValue", + checkRequired.TrueStatements.Add(new CodeMethodInvokeExpression( + new CodeThisReferenceExpression(), "RemoveSwitchToolBasedOnValue", new CodeSnippetExpression(SurroundWithQuotes(switchRelations.Key)))); addValidateRelationsMethod.Statements.Add(checkRequired); diff --git a/src/Tasks/XamlTaskFactory/TaskParser.cs b/src/Tasks/XamlTaskFactory/TaskParser.cs index 73fc516867b..87d63f90391 100644 --- a/src/Tasks/XamlTaskFactory/TaskParser.cs +++ b/src/Tasks/XamlTaskFactory/TaskParser.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -126,7 +126,9 @@ private bool ParseAsContentOrFile(string contentOrFile, string desiredRule) { isRootedPath = Path.IsPathRooted(contentOrFile); if (!isRootedPath) + { maybeFullPath = Path.GetFullPath(contentOrFile); + } } catch (Exception e) when (!ExceptionHandling.IsCriticalException(e)) { @@ -138,7 +140,9 @@ private bool ParseAsContentOrFile(string contentOrFile, string desiredRule) // valid *absolute* file path if (!FileSystems.Default.FileExists(contentOrFile)) + { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Xaml.RuleFileNotFound", contentOrFile)); + } return ParseXamlDocument(new StreamReader(contentOrFile), desiredRule); } @@ -146,12 +150,16 @@ private bool ParseAsContentOrFile(string contentOrFile, string desiredRule) // On Windows, xml content string is not a valid path, so, maybeFullPath == null // On Unix, xml content string would be a valid path, so, maybeFullPath != null if (maybeFullPath == null) + { // Unable to convert to a path, parse as XML return ParseXamlDocument(new StringReader(contentOrFile), desiredRule); + } if (FileSystems.Default.FileExists(maybeFullPath)) + { // file found, parse as a file return ParseXamlDocument(new StreamReader(maybeFullPath), desiredRule); + } // @maybeFullPath is either: // - a non-existent fullpath @@ -160,9 +168,13 @@ private bool ParseAsContentOrFile(string contentOrFile, string desiredRule) // // On Windows, this means that @contentOrFile is really a non-existent file name if (NativeMethodsShared.IsWindows) + { throw new ArgumentException(ResourceUtilities.FormatResourceStringStripCodeAndKeyword("Xaml.RuleFileNotFound", maybeFullPath)); + } else // On !Windows, try parsing as XML + { return ParseXamlDocument(new StringReader(contentOrFile), desiredRule); + } } /// diff --git a/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs b/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs index 1f79b6ccd1c..1d8a2ba8d4e 100644 --- a/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs +++ b/src/Tasks/XamlTaskFactory/XamlDataDrivenToolTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; diff --git a/src/Tasks/XamlTaskFactory/XamlTaskFactory.cs b/src/Tasks/XamlTaskFactory/XamlTaskFactory.cs index eec457b6a96..68cb433ad55 100644 --- a/src/Tasks/XamlTaskFactory/XamlTaskFactory.cs +++ b/src/Tasks/XamlTaskFactory/XamlTaskFactory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -117,16 +117,14 @@ public bool Initialize(string taskName, IDictionary ta // create the code generator options // Since we are running msbuild 12.0 these had better load. - var compilerParameters = new CompilerParameters - ( + var compilerParameters = new CompilerParameters( new[] { "System.dll", Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Framework.dll"), Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Utilities.Core.dll"), Path.Combine(pathToMSBuildBinaries, "Microsoft.Build.Tasks.Core.dll") - } - ) + }) { GenerateInMemory = true, TreatWarningsAsErrors = false @@ -245,7 +243,7 @@ public TaskPropertyInfo[] GetTaskParameters() public sealed class XamlTaskFactory : ITaskFactory { public string FactoryName => "XamlTaskFactory"; - + public Type TaskType { get; } = null; public bool Initialize(string taskName, IDictionary parameterGroup, string taskBody, IBuildEngine taskFactoryLoggingHost) @@ -255,7 +253,7 @@ public bool Initialize(string taskName, IDictionary pa TaskResources = AssemblyResources.PrimaryResources, HelpKeywordPrefix = "MSBuild." }; - + log.LogErrorWithCodeFromResources("TaskFactoryNotSupportedFailure", nameof(XamlTaskFactory)); return false; diff --git a/src/Tasks/XmlPeek.cs b/src/Tasks/XmlPeek.cs index d1f2e2ea5ea..9d8c7326a4f 100644 --- a/src/Tasks/XmlPeek.cs +++ b/src/Tasks/XmlPeek.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/XmlPoke.cs b/src/Tasks/XmlPoke.cs index 78f0fa6c50c..a60147e0cc8 100644 --- a/src/Tasks/XmlPoke.cs +++ b/src/Tasks/XmlPoke.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; diff --git a/src/Tasks/XslTransformation.cs b/src/Tasks/XslTransformation.cs index a3f9bdb3bf4..eaecfe3dd83 100644 --- a/src/Tasks/XslTransformation.cs +++ b/src/Tasks/XslTransformation.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Tasks/ZipDirectory.cs b/src/Tasks/ZipDirectory.cs index 8b9c83ad762..0832a5e8f4f 100644 --- a/src/Tasks/ZipDirectory.cs +++ b/src/Tasks/ZipDirectory.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Microsoft.Build.Framework; using System; diff --git a/src/Tasks/system.design/stronglytypedresourcebuilder.cs b/src/Tasks/system.design/stronglytypedresourcebuilder.cs index 2a0ecc35e16..7b9fbd54b77 100644 --- a/src/Tasks/system.design/stronglytypedresourcebuilder.cs +++ b/src/Tasks/system.design/stronglytypedresourcebuilder.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. // ************************************************************************************************ // ************************************************************************************************ @@ -319,9 +319,13 @@ private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String na if (resourcesNamespace != null) { if (resourcesNamespace.Length > 0) + { resMgrCtorParam = resourcesNamespace + '.' + baseName; + } else + { resMgrCtorParam = baseName; + } } else if (!string.IsNullOrEmpty(nameSpace)) { @@ -341,9 +345,14 @@ private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String na CodeConstructor ctor = new CodeConstructor(); ctor.CustomAttributes.Add(suppressMessageAttrib); if (useStatic || internalClass) + { ctor.Attributes = MemberAttributes.FamilyAndAssembly; + } else + { ctor.Attributes = MemberAttributes.Public; + } + srClass.Members.Add(ctor); // Emit _resMgr field. @@ -353,7 +362,10 @@ private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String na Attributes = MemberAttributes.Private }; if (useStatic) + { field.Attributes |= MemberAttributes.Static; + } + srClass.Members.Add(field); // Emit _resCulture field, and leave it set to null. @@ -361,7 +373,10 @@ private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String na field = new CodeMemberField(CultureTypeReference, CultureInfoFieldName); field.Attributes = MemberAttributes.Private; if (useStatic) + { field.Attributes |= MemberAttributes.Static; + } + srClass.Members.Add(field); // Emit ResMgr property @@ -372,11 +387,18 @@ private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String na resMgr.HasSet = false; resMgr.Type = ResMgrCodeTypeReference; if (internalClass) + { resMgr.Attributes = MemberAttributes.Assembly; + } else + { resMgr.Attributes = MemberAttributes.Public; + } + if (useStatic) + { resMgr.Attributes |= MemberAttributes.Static; + } // Mark the ResMgr property as advanced var editorBrowsableStateTypeRef = @@ -398,16 +420,22 @@ private static void EmitBasicClassMembers(CodeTypeDeclaration srClass, String na culture.HasSet = true; culture.Type = CultureTypeReference; if (internalClass) + { culture.Attributes = MemberAttributes.Assembly; + } else + { culture.Attributes = MemberAttributes.Public; + } if (useStatic) + { culture.Attributes |= MemberAttributes.Static; + } // Mark the Culture property as advanced culture.CustomAttributes.Add(editorBrowsableAdvancedAttribute); - + /* // Here's what I'm trying to emit. Since not all languages support // try/finally, we'll avoid our double lock pattern here. @@ -468,7 +496,9 @@ private static string TruncateAndFormatCommentStringForOutput(string commentStri { // Stop at some length if (commentString.Length > DocCommentLengthThreshold) + { commentString = SR.GetString(SR.StringPropertyTruncatedComment, commentString.Substring(0, DocCommentLengthThreshold)); + } // Encode the comment so it is safe for xml. SecurityElement.Escape is the only method I've found to do this. commentString = System.Security.SecurityElement.Escape(commentString); @@ -545,12 +575,18 @@ private static bool DefineResourceFetchingProperty(String propertyName, String r prop.Type = valueType; if (internalClass) + { prop.Attributes = MemberAttributes.Assembly; + } else + { prop.Attributes = MemberAttributes.Public; + } if (useStatic) + { prop.Attributes |= MemberAttributes.Static; + } // For Strings, emit this: // return ResourceManager.GetString("name", _resCulture); @@ -573,11 +609,17 @@ private static bool DefineResourceFetchingProperty(String propertyName, String r } if (isString) + { getMethodName = "GetString"; + } else if (isStream) + { getMethodName = "GetStream"; + } else + { getMethodName = "GetObject"; + } if (isString) { @@ -587,9 +629,13 @@ private static bool DefineResourceFetchingProperty(String propertyName, String r { // Stream or Object if (valueAsString == null || String.Equals(typeName, valueAsString)) // If the type did not override ToString, ToString just returns the type name. + { text = SR.GetString(SR.NonStringPropertyComment, typeName); + } else + { text = SR.GetString(SR.NonStringPropertyDetailedComment, typeName, valueAsString); + } } prop.Comments.Add(new CodeCommentStatement(DocCommentSummaryStart, true)); @@ -625,29 +671,42 @@ internal static String VerifyResourceName(String key, CodeDomProvider provider) private static String VerifyResourceName(String key, CodeDomProvider provider, bool isNameSpace) { if (key == null) + { throw new ArgumentNullException(nameof(key)); + } + if (provider == null) + { throw new ArgumentNullException(nameof(provider)); + } foreach (char c in s_charsToReplace) { // For namespaces, allow . and :: if (!(isNameSpace && (c == '.' || c == ':'))) + { key = key.Replace(c, ReplacementChar); + } } if (provider.IsValidIdentifier(key)) + { return key; + } // Now try fixing up keywords like "for". key = provider.CreateValidIdentifier(key); if (provider.IsValidIdentifier(key)) + { return key; + } // make one last ditch effort by prepending _. This fixes keys that start with a number key = "_" + key; if (provider.IsValidIdentifier(key)) + { return key; + } return null; } diff --git a/src/UnitTests.Shared/RunnerUtilities.cs b/src/UnitTests.Shared/RunnerUtilities.cs index 53d2512e201..78b694d815d 100644 --- a/src/UnitTests.Shared/RunnerUtilities.cs +++ b/src/UnitTests.Shared/RunnerUtilities.cs @@ -1,4 +1,7 @@ -using Microsoft.Build.Shared; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Microsoft.Build.Shared; using System; using System.Diagnostics; using Xunit.Abstractions; diff --git a/src/Utilities.UnitTests/AssemblyInfo.cs b/src/Utilities.UnitTests/AssemblyInfo.cs index 7f6f30fcef9..3b5d7bbb185 100644 --- a/src/Utilities.UnitTests/AssemblyInfo.cs +++ b/src/Utilities.UnitTests/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. global using NativeMethodsShared = Microsoft.Build.Framework.NativeMethods; diff --git a/src/Utilities.UnitTests/CanonicalError_Tests.cs b/src/Utilities.UnitTests/CanonicalError_Tests.cs index 755fc101ddd..fc9dbca3816 100644 --- a/src/Utilities.UnitTests/CanonicalError_Tests.cs +++ b/src/Utilities.UnitTests/CanonicalError_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Shouldly; using Xunit; diff --git a/src/Utilities.UnitTests/CommandLineBuilder_Tests.cs b/src/Utilities.UnitTests/CommandLineBuilder_Tests.cs index a9b45f36e8b..5e518f37a7a 100644 --- a/src/Utilities.UnitTests/CommandLineBuilder_Tests.cs +++ b/src/Utilities.UnitTests/CommandLineBuilder_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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; @@ -288,8 +288,7 @@ public void AppendSingleFileNameWithQuotes() c.AppendFileNameIfNotNull("string with \"quotes\""); c.ShouldBe("\"string with \\\"quotes\\\"\""); - } - ); + }); } /// /// Trigger escaping of literal quotes. @@ -450,7 +449,7 @@ public void UseNewLineSeparators() string[] actual = c.ToString().Split(MSBuildConstants.EnvironmentNewLine, StringSplitOptions.None); - string[] expected = + string[] expected = { "/foo:bar", "18056896847C4FFC9706F1D585C077B4", @@ -484,8 +483,7 @@ public void TestVerifyThrowElse() TestCommandLineBuilder c = new TestCommandLineBuilder(); c.TestVerifyThrow("SuperSwitch", @"Parameter"); c.TestVerifyThrow("SuperSwitch", @"Para""meter"); - } - ); + }); } } diff --git a/src/Utilities.UnitTests/EventArgsFormatting_Tests.cs b/src/Utilities.UnitTests/EventArgsFormatting_Tests.cs index 2776d3762bb..3a62f1fd10d 100644 --- a/src/Utilities.UnitTests/EventArgsFormatting_Tests.cs +++ b/src/Utilities.UnitTests/EventArgsFormatting_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Framework; @@ -163,8 +163,7 @@ public void FormatEventMessageOnNullBEEA() MyLogger l = new MyLogger(); BuildErrorEventArgs beea = null; l.FormatErrorEvent(beea); - } - ); + }); } /// /// Check null handling @@ -177,8 +176,7 @@ public void FormatEventMessageOnNullBWEA() MyLogger l = new MyLogger(); BuildWarningEventArgs bwea = null; l.FormatWarningEvent(bwea); - } - ); + }); } } diff --git a/src/Utilities.UnitTests/Logger_Tests.cs b/src/Utilities.UnitTests/Logger_Tests.cs index c1c2b3bd79a..4bcecdc4237 100644 --- a/src/Utilities.UnitTests/Logger_Tests.cs +++ b/src/Utilities.UnitTests/Logger_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System; diff --git a/src/Utilities.UnitTests/MockEngine.cs b/src/Utilities.UnitTests/MockEngine.cs index 90cc814a137..e5b5986bee8 100644 --- a/src/Utilities.UnitTests/MockEngine.cs +++ b/src/Utilities.UnitTests/MockEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Utilities.UnitTests/MockTask.cs b/src/Utilities.UnitTests/MockTask.cs index 52b8160a3f1..e72febfb0e6 100644 --- a/src/Utilities.UnitTests/MockTask.cs +++ b/src/Utilities.UnitTests/MockTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Reflection; using System.Resources; diff --git a/src/Utilities.UnitTests/MuxLogger_Tests.cs b/src/Utilities.UnitTests/MuxLogger_Tests.cs index fac643fade0..7d9d44ccf72 100644 --- a/src/Utilities.UnitTests/MuxLogger_Tests.cs +++ b/src/Utilities.UnitTests/MuxLogger_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -69,8 +69,7 @@ public void RegisteringLoggerBeforeBuildStartedThrows() { MuxLogger muxLogger = new MuxLogger(); muxLogger.RegisterLogger(1, new MockLogger()); - } - ); + }); } /// /// Verifies that building with a logger attached to the mux logger is equivalent to building with the logger directly. diff --git a/src/Utilities.UnitTests/PlatformManifest_Tests.cs b/src/Utilities.UnitTests/PlatformManifest_Tests.cs index 85b4ba832db..a6d4eee348f 100644 --- a/src/Utilities.UnitTests/PlatformManifest_Tests.cs +++ b/src/Utilities.UnitTests/PlatformManifest_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; diff --git a/src/Utilities.UnitTests/ProcessExtensions_Tests.cs b/src/Utilities.UnitTests/ProcessExtensions_Tests.cs index f549235ca90..99917144b38 100644 --- a/src/Utilities.UnitTests/ProcessExtensions_Tests.cs +++ b/src/Utilities.UnitTests/ProcessExtensions_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using Shouldly; using Xunit; diff --git a/src/Utilities.UnitTests/ProcessorArchitecture_Tests.cs b/src/Utilities.UnitTests/ProcessorArchitecture_Tests.cs index 19501687e94..f46e35ee4e3 100644 --- a/src/Utilities.UnitTests/ProcessorArchitecture_Tests.cs +++ b/src/Utilities.UnitTests/ProcessorArchitecture_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Microsoft.Build.Shared; diff --git a/src/Utilities.UnitTests/StringExtensions_Tests.cs b/src/Utilities.UnitTests/StringExtensions_Tests.cs index 1b115cb0f7f..d7b84659fb1 100644 --- a/src/Utilities.UnitTests/StringExtensions_Tests.cs +++ b/src/Utilities.UnitTests/StringExtensions_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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 Shouldly; diff --git a/src/Utilities.UnitTests/TaskItem_Tests.cs b/src/Utilities.UnitTests/TaskItem_Tests.cs index f182975a6ac..f774fdfc69e 100644 --- a/src/Utilities.UnitTests/TaskItem_Tests.cs +++ b/src/Utilities.UnitTests/TaskItem_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -32,7 +32,7 @@ public void ConstructWithITaskItem() TaskItem to = new TaskItem((ITaskItem)from); to.ItemSpec.ShouldBe("Monkey.txt"); ((string)to).ShouldBe("Monkey.txt"); - + to.GetMetadata("Dog").ShouldBe("Bingo"); to.GetMetadata("Cat").ShouldBe("Morris"); @@ -79,8 +79,7 @@ public void NullITaskItem() TaskItem taskItem = new TaskItem(item); // no NullReferenceException - } - ); + }); } [Fact] @@ -108,8 +107,7 @@ public void NullITaskItemCast() string result = (string)item; // no NullReferenceException - } - ); + }); } [Fact] public void ConstructFromDictionary() @@ -144,8 +142,7 @@ public void CannotChangeModifiers() Console.WriteLine(e.Message); throw; } - } - ); + }); } [Fact] @@ -165,8 +162,7 @@ public void CannotRemoveModifiers() Console.WriteLine(e.Message); throw; } - } - ); + }); } [Fact] public void CheckMetadataCount() @@ -186,12 +182,9 @@ public void NonexistentRequestFullPath() TaskItem from = new TaskItem(); from.ItemSpec = "Monkey.txt"; from.GetMetadata(FileUtilities.ItemSpecModifiers.FullPath).ShouldBe( - Path.Combine - ( + Path.Combine( Directory.GetCurrentDirectory(), - "Monkey.txt" - ) - ); + "Monkey.txt")); } [Fact] @@ -295,8 +288,7 @@ public void CreateNullNamedMetadata() { TaskItem item = new TaskItem("foo"); item.SetMetadata(null, "x"); - } - ); + }); } /// /// Verify metadata cannot be created with empty name @@ -308,8 +300,7 @@ public void CreateEmptyNamedMetadata() { TaskItem item = new TaskItem("foo"); item.SetMetadata("", "x"); - } - ); + }); } /// /// Create a TaskItem with a null metadata value -- this is allowed, but @@ -349,18 +340,14 @@ public void RemoteTaskItem() AppDomain appDomain = null; try { - appDomain = AppDomain.CreateDomain - ( + appDomain = AppDomain.CreateDomain( "generateResourceAppDomain", null, - AppDomain.CurrentDomain.SetupInformation - ); + AppDomain.CurrentDomain.SetupInformation); - object obj = appDomain.CreateInstanceFromAndUnwrap - ( + object obj = appDomain.CreateInstanceFromAndUnwrap( typeof(TaskItemCreator).Module.FullyQualifiedName, - typeof(TaskItemCreator).FullName - ); + typeof(TaskItemCreator).FullName); TaskItemCreator creator = (TaskItemCreator)obj; diff --git a/src/Utilities.UnitTests/TaskLoggingHelper_Tests.cs b/src/Utilities.UnitTests/TaskLoggingHelper_Tests.cs index b37dbed11db..33c2cab46f3 100644 --- a/src/Utilities.UnitTests/TaskLoggingHelper_Tests.cs +++ b/src/Utilities.UnitTests/TaskLoggingHelper_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.IO; @@ -203,7 +203,10 @@ nor is this } finally { - if (file != null) File.Delete(file); + if (file != null) + { + File.Delete(file); + } } } @@ -224,8 +227,7 @@ public void CheckResourcesRegistered() Console.WriteLine(e.Message); throw; } - } - ); + }); } /// /// Verify the LogErrorFromException & LogWarningFromException methods diff --git a/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs b/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs index ad43b36401b..8c961c597f1 100644 --- a/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs +++ b/src/Utilities.UnitTests/ToolLocationHelper_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 0219 @@ -519,8 +519,7 @@ public void FindFrameworksPathRunningThisTest() ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.Version40), DirectoryExists, GetDirectories, - SharedDotNetFrameworkArchitecture.Current - ); + SharedDotNetFrameworkArchitecture.Current); #if FEATURE_INSTALLED_MSBUILD path.ShouldBe(Path.GetDirectoryName(typeof(object).GetTypeInfo().Module.FullyQualifiedName)); @@ -538,14 +537,12 @@ public void FindFrameworksPathRunningThisTest() [PlatformSpecific(TestPlatforms.Windows)] public void FindFrameworksPathRunningUnderWhidbey() { - string path = FrameworkLocationHelper.FindDotNetFrameworkPath - ( + string path = FrameworkLocationHelper.FindDotNetFrameworkPath( @"{runtime-base}\v1.2.x86dbg", // Simulate "Whidbey" as the current runtime. "v1.2", DirectoryExists, GetDirectories, - SharedDotNetFrameworkArchitecture.Current - ); + SharedDotNetFrameworkArchitecture.Current); path.ShouldBe(Path.Combine("{runtime-base}", "v1.2.x86dbg")); } @@ -558,14 +555,12 @@ public void FindFrameworksPathRunningUnderWhidbey() [PlatformSpecific(TestPlatforms.Windows)] public void FindFrameworksPathRunningUnderOrcas() { - string path = FrameworkLocationHelper.FindDotNetFrameworkPath - ( + string path = FrameworkLocationHelper.FindDotNetFrameworkPath( Path.Combine("{runtime-base}", "v1.3.x86dbg"), // Simulate "Orcas" as the current runtime.} "v1.2", // But we're looking for "Whidbey" DirectoryExists, GetDirectories, - SharedDotNetFrameworkArchitecture.Current - ); + SharedDotNetFrameworkArchitecture.Current); path.ShouldBe(Path.Combine("{runtime-base}", "v1.2.x86fre")); } @@ -578,14 +573,12 @@ public void FindFrameworksPathRunningUnderOrcas() [PlatformSpecific(TestPlatforms.Windows)] public void FindFrameworksPathRunningUnderEverett() { - string path = FrameworkLocationHelper.FindDotNetFrameworkPath - ( + string path = FrameworkLocationHelper.FindDotNetFrameworkPath( Path.Combine("{runtime-base}", "v1.1.x86dbg"), // Simulate "Everett" as the current runtime. "v1.2", // But we're looking for "Whidbey" DirectoryExists, GetDirectories, - SharedDotNetFrameworkArchitecture.Current - ); + SharedDotNetFrameworkArchitecture.Current); path.ShouldBe(Path.Combine("{runtime-base}", "v1.2.x86fre")); } @@ -598,14 +591,12 @@ public void FindFrameworksPathRunningUnderEverett() [Fact] public void FindPathForNonexistentFrameworks() { - string path = FrameworkLocationHelper.FindDotNetFrameworkPath - ( + string path = FrameworkLocationHelper.FindDotNetFrameworkPath( Path.Combine(@"{runtime-base}", "v1.1"), // Simulate "everett" as the current runtime "v1.3", // And we're trying to find "orchas" runtime which isn't installed. DirectoryExists, GetDirectories, - SharedDotNetFrameworkArchitecture.Current - ); + SharedDotNetFrameworkArchitecture.Current); path.ShouldBeNull(); } @@ -623,14 +614,12 @@ public void FindPathForEverettThatIsntProperlyInstalled() string fakeEverettPath = Path.Combine(tempPath, "v1.1.43225"); Directory.CreateDirectory(fakeEverettPath); - string path = FrameworkLocationHelper.FindDotNetFrameworkPath - ( + string path = FrameworkLocationHelper.FindDotNetFrameworkPath( fakeWhidbeyPath, // Simulate "whidbey" as the current runtime "v1.1", // We're looking for "everett" DirectoryExists, GetDirectories, - SharedDotNetFrameworkArchitecture.Current - ); + SharedDotNetFrameworkArchitecture.Current); FileUtilities.DeleteWithoutTrailingBackslash(fakeEverettPath); path.ShouldBeNull(); @@ -661,53 +650,39 @@ public void ExerciseMiscToolLocationHelperMethods() ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Latest).ShouldBe(FrameworkLocationHelper.PathToDotNetFrameworkV40); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version11, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV11(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV11(SharedDotNetFrameworkArchitecture.Bitness32)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV20(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV20(SharedDotNetFrameworkArchitecture.Bitness32)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version30, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV30(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV30(SharedDotNetFrameworkArchitecture.Bitness32)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version35, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV35(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV35(SharedDotNetFrameworkArchitecture.Bitness32)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version40, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness32)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness32)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Latest, UtilitiesDotNetFrameworkArchitecture.Bitness32).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness32) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness32)); if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { // 64-bit machine, so we should test the 64-bit overloads as well ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version11, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV11(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV11(SharedDotNetFrameworkArchitecture.Bitness64)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version20, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV20(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV20(SharedDotNetFrameworkArchitecture.Bitness64)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version30, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV30(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV30(SharedDotNetFrameworkArchitecture.Bitness64)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version35, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV35(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV35(SharedDotNetFrameworkArchitecture.Bitness64)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Version40, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness64)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.VersionLatest, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness64)); ToolLocationHelper.GetPathToDotNetFramework(TargetDotNetFrameworkVersion.Latest, UtilitiesDotNetFrameworkArchitecture.Bitness64).ShouldBe( - FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness64) - ); + FrameworkLocationHelper.GetPathToDotNetFrameworkV40(SharedDotNetFrameworkArchitecture.Bitness64)); } } @@ -934,7 +909,7 @@ public void TestGetDotNetFrameworkSdkInstallKeyValue() #if FEATURE_REGISTRY_SDKS [Fact(Skip = "https://github.com/dotnet/msbuild/issues/995")] #else - [Fact (Skip="Registry SDKs not supported")] + [Fact(Skip = "Registry SDKs not supported")] #endif [PlatformSpecific(TestPlatforms.Windows)] public void GetPathToDotNetFrameworkSdk() @@ -1356,8 +1331,7 @@ public void GenerateReferencAssemblyInvalidProfile() FrameworkNameVersioning frameworkName = new FrameworkNameVersioning(targetFrameworkIdentifier, targetFrameworkVersion, targetFrameworkProfile); FrameworkLocationHelper.GenerateReferenceAssemblyPath(targetFrameworkRootPath, frameworkName); - } - ); + }); } /// /// Make sure if the identifier has invalid chars which would be used as part of path generation that we get an InvalidOperationException @@ -1378,8 +1352,7 @@ public void GenerateReferencAssemblyInvalidIdentifier() FrameworkNameVersioning frameworkName = new FrameworkNameVersioning(targetFrameworkIdentifier, targetFrameworkVersion, targetFrameworkProfile); FrameworkLocationHelper.GenerateReferenceAssemblyPath(targetFrameworkRootPath, frameworkName); - } - ); + }); } /// /// Make sure if the moniker and the root make a too long path that an InvalidOperationException is raised @@ -1404,8 +1377,7 @@ public void GenerateReferencAssemblyPathTooLong() FrameworkNameVersioning frameworkName = new FrameworkNameVersioning(targetFrameworkIdentifier, targetFrameworkVersion, targetFrameworkProfile); FrameworkLocationHelper.GenerateReferenceAssemblyPath(targetFrameworkRootPath, frameworkName); - } - ); + }); } #endregion @@ -1588,8 +1560,7 @@ public void ChainReferenceAssembliesRedistExistsBadFile() FileUtilities.DeleteWithoutTrailingBackslash(redist40Directory, true); } } - } - ); + }); } /// /// Make sure we get the correct exception when the xml file points to an included framework which does not exist. @@ -1656,8 +1627,7 @@ public void ChainReferenceAssembliesRedistInvalidPathChars() FileUtilities.DeleteWithoutTrailingBackslash(redist41Directory, true); } } - } - ); + }); } /// /// Make sure we get the correct exception when the xml file points to an included framework which has invalid path chars. @@ -1693,8 +1663,7 @@ public void ChainReferenceAssembliesRedistPathTooLong() FileUtilities.DeleteWithoutTrailingBackslash(redist41Directory, true); } } - } - ); + }); } #endregion @@ -1891,8 +1860,7 @@ public void GetPathToReferenceAssembliesNullFrameworkName() Should.Throw(() => { ToolLocationHelper.GetPathToReferenceAssemblies("Not Null String", (FrameworkNameVersioning)null); - } - ); + }); } /// /// Make sure we get the correct exception when both parameters are null @@ -1903,8 +1871,7 @@ public void GetPathToReferenceAssembliesNullArgumentNameandFrameworkName() Should.Throw(() => { ToolLocationHelper.GetPathToReferenceAssemblies(null, (FrameworkNameVersioning)null); - } - ); + }); } /// /// Make sure we get the correct exception when the root is null but the frameworkname is not null @@ -1916,8 +1883,7 @@ public void GetPathToReferenceAssembliesNullArgumentGoodFrameworkNameNullRoot() { FrameworkNameVersioning frameworkName = new FrameworkNameVersioning("Ident", new Version("2.0")); ToolLocationHelper.GetPathToReferenceAssemblies(null, frameworkName); - } - ); + }); } /// /// Make sure we get the correct exception when the root is null but the frameworkname is not null @@ -1930,8 +1896,7 @@ public void GetPathToReferenceAssembliesNullArgumentGoodFrameworkNameEmptyRoot() { FrameworkNameVersioning frameworkName = new FrameworkNameVersioning("Ident", new Version("2.0")); ToolLocationHelper.GetPathToReferenceAssemblies(string.Empty, frameworkName); - } - ); + }); } /// /// Make sure we get the correct exception when the root is null but the frameworkname is not empty to make sure we cover the different input cases @@ -1944,8 +1909,7 @@ public void GetPathToReferenceAssembliesNullArgumentGoodFrameworkNameEmptyRoot2( { FrameworkNameVersioning frameworkName = new FrameworkNameVersioning("Ident", new Version("2.0")); ToolLocationHelper.GetPathToReferenceAssemblies(string.Empty, frameworkName); - } - ); + }); } #endregion @@ -1961,8 +1925,7 @@ public void GetPathToReferenceAssembliesDefaultLocationNullFrameworkName() Should.Throw(() => { ToolLocationHelper.GetPathToReferenceAssemblies((FrameworkNameVersioning)null); - } - ); + }); } /// @@ -2453,8 +2416,7 @@ public void GetAssemblyFoldersExInfoTestEmptyRegistryRoot() Should.Throw(() => { ToolLocationHelper.GetAssemblyFoldersExInfo("", "v3.0", "AssemblyFoldersEx", null, null, System.Reflection.ProcessorArchitecture.MSIL); - } - ); + }); } /// /// Verify we can an argumentNull exception if we try and pass a null registry root @@ -2465,8 +2427,7 @@ public void GetAssemblyFoldersExInfoListTestNullRegistryRoot() Should.Throw(() => { ToolLocationHelper.GetAssemblyFoldersExInfo(null, "v3.0", "AssemblyFoldersEx", null, null, System.Reflection.ProcessorArchitecture.MSIL); - } - ); + }); } /// /// Verify we can an argument exception if we try and pass a empty registry suffix @@ -2477,8 +2438,7 @@ public void GetAssemblyFoldersExInfoTestEmptyRegistrySuffix() Should.Throw(() => { ToolLocationHelper.GetAssemblyFoldersExInfo(@"SOFTWARE\Microsoft\.UnitTest", "v3.0", "", null, null, System.Reflection.ProcessorArchitecture.MSIL); - } - ); + }); } /// /// Verify we can an argumentNull exception if we try and pass a null registry suffix @@ -2489,8 +2449,7 @@ public void GetAssemblyFoldersExInfoTestNullRegistrySuffix() Should.Throw(() => { ToolLocationHelper.GetAssemblyFoldersExInfo(@"SOFTWARE\Microsoft\.UnitTest", "v3.0", null, null, null, System.Reflection.ProcessorArchitecture.MSIL); - } - ); + }); } /// /// Verify we can an argument exception if we try and pass a empty registry suffix @@ -2501,8 +2460,7 @@ public void GetAssemblyFoldersExInfoTestEmptyTargetRuntime() Should.Throw(() => { ToolLocationHelper.GetAssemblyFoldersExInfo(@"SOFTWARE\Microsoft\.UnitTest", "", "AssemblyFoldersEx", null, null, System.Reflection.ProcessorArchitecture.MSIL); - } - ); + }); } /// /// Verify we can an argumentNull exception if we try and pass a null target runtime version @@ -2513,8 +2471,7 @@ public void GetAssemblyFoldersExInfoTestNullTargetRuntimeVersion() Should.Throw(() => { ToolLocationHelper.GetAssemblyFoldersExInfo(@"SOFTWARE\Microsoft\.UnitTest", null, "AssemblyFoldersEx", null, null, System.Reflection.ProcessorArchitecture.MSIL); - } - ); + }); } /// /// Verify we can get a list of directories out of the public API. @@ -3172,8 +3129,7 @@ public void ResolveFromDirectoryPathTooLong() var targetPlatform = new Dictionary(); ToolLocationHelper.GatherSDKListFromDirectory(paths, targetPlatform); - } - ); + }); } /// diff --git a/src/Utilities.UnitTests/ToolTask_Tests.cs b/src/Utilities.UnitTests/ToolTask_Tests.cs index d6004dc55d6..b36c5d2ba11 100644 --- a/src/Utilities.UnitTests/ToolTask_Tests.cs +++ b/src/Utilities.UnitTests/ToolTask_Tests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Diagnostics; diff --git a/src/Utilities.UnitTests/TrackedDependencies/FileTrackerTests.cs b/src/Utilities.UnitTests/TrackedDependencies/FileTrackerTests.cs index 14cd1e7820f..5c2d97eabd1 100644 --- a/src/Utilities.UnitTests/TrackedDependencies/FileTrackerTests.cs +++ b/src/Utilities.UnitTests/TrackedDependencies/FileTrackerTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -903,7 +903,7 @@ public void FileTrackerFileIsExcludedFromDependencies() ? tempPath : FileUtilities.EnsureTrailingSlash( NativeMethodsShared.GetLongFilePath(tempPath).ToUpperInvariant()); - + // We don't want to be including these as dependencies or outputs: // 1. Files under %USERPROFILE%\Application Data in XP and %USERPROFILE%\AppData\Roaming in Vista and later. // 2. Files under %USERPROFILE%\Local Settings\Application Data in XP and %USERPROFILE%\AppData\Local in Vista and later. @@ -1024,8 +1024,7 @@ public void InProcTrackingTestStopBeforeWrite() // This should throw a COMException, since we have cleaned up FileTracker.WriteContextTLogs(Path.GetFullPath("."), tlogRootName); - } - ); + }); } [Fact(Skip = "FileTracker tests require VS2015 Update 3 or a packaged version of Tracker.exe https://github.com/dotnet/msbuild/issues/649")] public void InProcTrackingTestNotStop() @@ -1359,8 +1358,7 @@ public void InProcTrackingTwoContextsTwoEnds() File.Delete(tlogWriteFile); File.Delete(tlogWriteFile2); } - } - ); + }); } [Fact(Skip = "Test fails in xunit because tracker includes the PID in the log file.")] diff --git a/src/Utilities.UnitTests/TrackedDependencies/MockEngine.cs b/src/Utilities.UnitTests/TrackedDependencies/MockEngine.cs index 8da0dfbfc00..ffc7f3d824a 100644 --- a/src/Utilities.UnitTests/TrackedDependencies/MockEngine.cs +++ b/src/Utilities.UnitTests/TrackedDependencies/MockEngine.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; diff --git a/src/Utilities.UnitTests/TrackedDependencies/TrackedDependenciesTests.cs b/src/Utilities.UnitTests/TrackedDependencies/TrackedDependenciesTests.cs index dc79f6c8cc1..3c3e924cd2b 100644 --- a/src/Utilities.UnitTests/TrackedDependencies/TrackedDependenciesTests.cs +++ b/src/Utilities.UnitTests/TrackedDependencies/TrackedDependenciesTests.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #pragma warning disable 0219 @@ -85,86 +85,86 @@ public void FormatNormalizedRootingMarkerTests() var tests = new Dictionary { { - new ITaskItem[] {new TaskItem("Debug\\link.9999-cvtres.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.9999-cvtres.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.[ID]-cvtres.write.[ID].tlog") .ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.0000-cvtres.read.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.0000-cvtres.read.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.[ID]-cvtres.read.[ID].tlog") .ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.4567-cvtres.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.4567-cvtres.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.[ID]-cvtres.write.[ID].tlog") .ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.9999.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.9999.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.[ID].write.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.0000.read.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.0000.read.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.[ID].read.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.4567.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.4567.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.[ID].write.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link2345.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link2345.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link2345.write.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("link.4567.write.1.tlog")}, + new ITaskItem[] {new TaskItem("link.4567.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "link.[ID].write.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\a.1234.b\\link.4567.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\a.1234.b\\link.4567.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\a.1234.b\\link.[ID].write.[ID].tlog") .ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("link.write.tlog")}, + new ITaskItem[] {new TaskItem("link.write.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "link.write.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("link%20with%20spaces.write.3.tlog")}, + new ITaskItem[] {new TaskItem("link%20with%20spaces.write.3.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "link with spaces.write.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[2] {new TaskItem("link.write.tlog"), new TaskItem("Debug\\link2345.write.1.tlog")}, + new ITaskItem[2] {new TaskItem("link.write.tlog"), new TaskItem("Debug\\link2345.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link2345.write.[ID].tlog") .ToUpperInvariant() + "|" + Path.Combine(Directory.GetCurrentDirectory(), "link.write.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("link.write.tlog1234")}, + new ITaskItem[] {new TaskItem("link.write.tlog1234") }, Path.Combine(Directory.GetCurrentDirectory(), "link.write.tlog1234").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("1234link.write.tlog")}, + new ITaskItem[] {new TaskItem("1234link.write.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "1234link.write.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("link-1234.write.tlog")}, + new ITaskItem[] {new TaskItem("link-1234.write.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "link-1234.write.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("C:\\Debug\\a.1234.b\\link.4567.write.1.tlog")}, + new ITaskItem[] {new TaskItem("C:\\Debug\\a.1234.b\\link.4567.write.1.tlog") }, "C:\\DEBUG\\A.1234.B\\LINK.[ID].WRITE.[ID].TLOG" }, { - new ITaskItem[] {new TaskItem("a\\")}, + new ITaskItem[] {new TaskItem("a\\") }, Path.Combine(Directory.GetCurrentDirectory(), "a\\").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.45\\67.write.1.tlog")}, + new ITaskItem[] {new TaskItem("Debug\\link.45\\67.write.1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.45\\67.write.[ID].tlog") .ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("Debug\\link.4567.write.1.tlog\\")}, + new ITaskItem[] {new TaskItem("Debug\\link.4567.write.1.tlog\\") }, Path.Combine(Directory.GetCurrentDirectory(), "Debug\\link.4567.write.1.tlog\\").ToUpperInvariant() }, {Array.Empty(), ""}, @@ -212,47 +212,47 @@ public void FormatNormalizedRootingMarkerTests() Path.Combine(Directory.GetCurrentDirectory(), "cl.write.[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("foo\\.tlog")}, + new ITaskItem[] {new TaskItem("foo\\.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "foo\\.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("foo\\1.tlog")}, + new ITaskItem[] {new TaskItem("foo\\1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), "foo\\1.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("\\1.tlog")}, + new ITaskItem[] {new TaskItem("\\1.tlog") }, Path.Combine(Path.GetPathRoot(Directory.GetCurrentDirectory()), "1.tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem(".1.tlog")}, + new ITaskItem[] {new TaskItem(".1.tlog") }, Path.Combine(Directory.GetCurrentDirectory(), ".[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("-2")}, + new ITaskItem[] {new TaskItem("-2") }, Path.Combine(Directory.GetCurrentDirectory(), "-2").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem(".2")}, + new ITaskItem[] {new TaskItem(".2") }, Path.Combine(Directory.GetCurrentDirectory(), ".2").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("2-")}, + new ITaskItem[] {new TaskItem("2-") }, Path.Combine(Directory.GetCurrentDirectory(), "2-").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("2.")}, + new ITaskItem[] {new TaskItem("2.") }, Path.Combine(Directory.GetCurrentDirectory(), "2").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("\\.1.tlog")}, + new ITaskItem[] {new TaskItem("\\.1.tlog") }, Path.Combine(Path.GetPathRoot(Directory.GetCurrentDirectory()), ".[ID].tlog").ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("\\")}, + new ITaskItem[] {new TaskItem("\\") }, Path.GetPathRoot(Directory.GetCurrentDirectory()).ToUpperInvariant() }, { - new ITaskItem[] {new TaskItem("\\\\share\\foo.read.8.tlog")}, + new ITaskItem[] {new TaskItem("\\\\share\\foo.read.8.tlog") }, "\\\\share\\foo.read.[ID].tlog".ToUpperInvariant() } }; @@ -280,16 +280,14 @@ public void CreateTrackedDependencies() Console.WriteLine("Test: CreateTrackedDependencies"); ITaskItem[] sources = null; ITaskItem[] outputs = null; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, null, sources, null, outputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ Assert.NotNull(d); } @@ -312,16 +310,14 @@ public void SingleCanonicalCL() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -341,16 +337,14 @@ public void NonExistentTlog() // Just to be sure, delete the test tlog. File.Delete(Path.Combine("TestFiles", "one.tlog")); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -369,16 +363,14 @@ public void EmptyTLog() DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one.obj"), ""); DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one.tlog"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -399,20 +391,18 @@ public void InvalidReadTLogName() MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( task, DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\|one|.tlog")), DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\one.cpp")), null, DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\one.obj")), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ d.ComputeSourcesNeedingCompilation(); - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have an error." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have an error." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -429,18 +419,16 @@ public void ReadTLogWithInitialEmptyLine() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "", "^FOO" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -457,18 +445,16 @@ public void ReadTLogWithEmptyLineImmediatelyAfterRoot() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "^FOO", "", "FOO" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -485,18 +471,16 @@ public void ReadTLogWithEmptyLineBetweenRoots() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "^FOO", "FOO", "", "^BAR", "BAR" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -513,18 +497,16 @@ public void ReadTLogWithEmptyRoot() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "^", "FOO" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -543,16 +525,14 @@ public void ReadTLogWithDuplicateInRoot() File.WriteAllLines("TestFiles\\one.tlog", new[] { "^TestFiles\\foo.cpp|TestFiles\\foo.cpp", "TestFiles\\bar.cpp", "TestFiles\\foo.cpp" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( task, DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\one.tlog")), sources, null, DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\one.obj")), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ Assert.NotEmpty(d.DependencyTable); // "Dependency Table should not be empty." } @@ -564,13 +544,11 @@ public void InvalidWriteTLogName() MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles - ( + CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles( task, - DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\|one|.write.tlog")) - ); + DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\|one|.write.tlog"))); - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have an error." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have an error." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -583,13 +561,11 @@ public void WriteTLogWithInitialEmptyLine() File.WriteAllLines(Path.Combine("TestFiles", "one.write.tlog"), new[] { "", "^FOO" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles - ( + CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles( task, - DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog"))) - ); + DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -602,13 +578,11 @@ public void WriteTLogWithEmptyLineImmediatelyAfterRoot() File.WriteAllLines(Path.Combine("TestFiles", "one.write.tlog"), new[] { "^FOO", "", "FOO" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles - ( + CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles( task, - DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog"))) - ); + DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -621,13 +595,11 @@ public void WriteTLogWithEmptyLineBetweenRoots() File.WriteAllLines(Path.Combine("TestFiles", "one.write.tlog"), new[] { "^FOO", "FOO", "", "^BAR", "BAR" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles - ( + CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles( task, - DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog"))) - ); + DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -640,13 +612,11 @@ public void WriteTLogWithEmptyRoot() File.WriteAllLines(Path.Combine("TestFiles", "one.write.tlog"), new[] { "^", "FOO" }); MockTask task = DependencyTestHelper.MockTask; - CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles - ( + CanonicalTrackedOutputFiles d = new CanonicalTrackedOutputFiles( task, - DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog"))) - ); + DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(d.DependencyTable); // "DependencyTable should be empty." } @@ -672,16 +642,14 @@ public void PrimarySourceNotInTlog() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one.obj"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -712,16 +680,14 @@ public void MultipleCanonicalCL() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one2.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -760,16 +726,14 @@ public void MultipleCanonicalCLCompactMissingOnSuccess() compactOutputs.SaveTlog(); // Compact the read tlog - CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, compactOutputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ compactInputs.RemoveDependenciesFromEntryIfMissing(new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp")))); compactInputs.SaveTlog(); @@ -777,16 +741,14 @@ public void MultipleCanonicalCLCompactMissingOnSuccess() CanonicalTrackedOutputFiles outputs = new CanonicalTrackedOutputFiles(DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, outputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -829,16 +791,14 @@ public void MultipleCanonicalCLCompactMissingOnSuccessMultiEntry() compactOutputs.RemoveDependenciesFromEntryIfMissing(new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp")))); compactOutputs.SaveTlog(); // Compact the read tlog - CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, compactOutputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ compactInputs.RemoveDependenciesFromEntryIfMissing(new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp")))); compactInputs.SaveTlog(); @@ -846,16 +806,14 @@ public void MultipleCanonicalCLCompactMissingOnSuccessMultiEntry() CanonicalTrackedOutputFiles writtenOutputs = new CanonicalTrackedOutputFiles(DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); - CanonicalTrackedInputFiles writtenInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles writtenInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, writtenOutputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ Assert.Single(writtenOutputs.DependencyTable[Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))]); Assert.Equal(4, writtenInputs.DependencyTable[Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))].Count); @@ -908,30 +866,26 @@ public void RemoveDependencyFromEntry() Assert.False(writtenOutputs.DependencyTable[Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))].ContainsKey(Path.GetFullPath(Path.Combine("TestFiles", "one3.obj")))); - CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, compactOutputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ compactInputs.RemoveDependencyFromEntry(new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one3.obj")))); compactInputs.SaveTlog(); - CanonicalTrackedInputFiles writtenInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles writtenInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, writtenOutputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ Assert.False(writtenInputs.DependencyTable[Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))].ContainsKey(Path.GetFullPath(Path.Combine("TestFiles", "one3.obj")))); } @@ -983,30 +937,26 @@ public void RemoveDependencyFromEntries() Assert.False(writtenOutputs.DependencyTable[rootingMarker].ContainsKey(Path.GetFullPath(Path.Combine("TestFiles", "one3.obj")))); - CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), new[] { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }, null, compactOutputs, false, /* no minimal rebuild optimization */ - true /* shred composite rooting markers */ - ); + true); /* shred composite rooting markers */ compactInputs.RemoveDependencyFromEntry(new[] { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }, new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one3.obj")))); compactInputs.SaveTlog(); - CanonicalTrackedInputFiles writtenInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles writtenInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), new[] { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }, null, writtenOutputs, false, /* no minimal rebuild optimization */ - true /* shred composite rooting markers */ - ); + true); /* shred composite rooting markers */ Assert.False(writtenInputs.DependencyTable[rootingMarker].ContainsKey(Path.GetFullPath(Path.Combine("TestFiles", "one3.obj")))); } @@ -1126,16 +1076,14 @@ public void MultipleCanonicalCLMissingDependency() string missing = Path.GetFullPath(Path.Combine("TestFiles", "one2.h")); File.Delete(missing); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // We're out of date, since a missing dependency indicates out-of-dateness ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1150,16 +1098,14 @@ public void MultipleCanonicalCLMissingDependency() d.SaveTlog(); // read the tlog back in again - d = new CanonicalTrackedInputFiles - ( + d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // We're out of date, since a missing dependency indicates out-of-dateness outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1218,16 +1164,14 @@ public void MultipleCanonicalCLMissingOutputDependencyRemoved() // Read the Tlogs back in.. compactOutputs = new CanonicalTrackedOutputFiles(DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); // Compact the read tlog - CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles compactInputs = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), new[] { new TaskItem(Path.Combine("TestFiles", "one.cpp")), new TaskItem(Path.Combine("TestFiles", "two.cpp")) }, null, compactOutputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ compactInputs.SaveTlog(); @@ -1258,16 +1202,14 @@ public void MultipleCanonicalCLMissingInputDependencyRemoved() string missing = Path.GetFullPath(Path.Combine("TestFiles", "one2.h")); File.Delete(missing); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // We're out of date, since a missing dependency indicates out-of-dateness ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1285,16 +1227,14 @@ public void MultipleCanonicalCLMissingInputDependencyRemoved() }); // read the tlog back in again - d = new CanonicalTrackedInputFiles - ( + d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // We're not out of date, since the missing dependency has been removed outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1337,8 +1277,7 @@ public void MultiplePrimaryCanonicalCL() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "two2.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), new ITaskItem[] { @@ -1351,8 +1290,7 @@ public void MultiplePrimaryCanonicalCL() new TaskItem(Path.Combine("TestFiles", "two.obj")), }, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1404,8 +1342,7 @@ public void MultiplePrimaryCanonicalCLUnderTemp() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "two2.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), new ITaskItem[] { @@ -1418,8 +1355,7 @@ public void MultiplePrimaryCanonicalCLUnderTemp() new TaskItem(Path.Combine("TestFiles", "two.obj")), }, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1466,8 +1402,7 @@ public void MultiplePrimaryCanonicalCLSharedDependency() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one2.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), new ITaskItem[] { @@ -1480,8 +1415,7 @@ public void MultiplePrimaryCanonicalCLSharedDependency() new TaskItem(Path.Combine("TestFiles", "two.obj")), }, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1515,16 +1449,14 @@ public void MultipleCanonicalCLAcrossCommand1() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one1.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1557,16 +1489,14 @@ public void MultipleCanonicalCLAcrossCommand2() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one2.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1603,16 +1533,14 @@ public void MultipleCanonicalCLAcrossCommandNonDependency() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "two2.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1652,16 +1580,14 @@ public void MultipleCanonicalCLAcrossTlogs1() new TaskItem(Path.Combine("TestFiles", "one2.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1702,16 +1628,14 @@ public void MultipleCanonicalCLAcrossTlogs2() new TaskItem(Path.Combine("TestFiles", "one2.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1738,16 +1662,14 @@ public void SingleRootedCL() Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "one.h"), ""); - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1788,16 +1710,14 @@ public void MultipleRootedCLAcrossTlogs1() new TaskItem(Path.Combine("TestFiles", "one2.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1840,16 +1760,14 @@ public void MultipleRootedCL() new TaskItem(Path.Combine("TestFiles", "one2.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "two.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1891,16 +1809,14 @@ public void MultipleRootedCLNonDependency() new TaskItem(Path.Combine("TestFiles", "one1.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -1940,16 +1856,14 @@ public void MultipleRootedCLAcrossTlogs2() new TaskItem(Path.Combine("TestFiles", "one2.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -2035,7 +1949,7 @@ public void OutputMultipleCanonicalCL() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; // Prepare files Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register @@ -2067,13 +1981,13 @@ public void OutputMultipleCanonicalCLSubrootMatch() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; ITaskItem[] sources2 = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "four.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "five.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "five.cpp"))) }; // Prepare files Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register @@ -2145,22 +2059,22 @@ public void OutputMultipleCanonicalCLSubrootMisMatch() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; ITaskItem[] sources2 = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "four.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "five.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "five.cpp"))) }; ITaskItem[] sources2Match = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "four.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "five.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "five.cpp"))) }; ITaskItem[] sourcesPlusOne = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "eight.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; // Do note sources2Match and source2 is missing three.cpp. It is to test if the RootContainsAllSubRootComponents can handle the case. @@ -2221,7 +2135,7 @@ public void OutputMultipleCanonicalCLLongTempPath() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; string oldTempPath = Environment.GetEnvironmentVariable("TEMP"); string oldTmpPath = Environment.GetEnvironmentVariable("TMP"); @@ -2265,7 +2179,7 @@ public void OutputMultipleCanonicalCLAcrossTLogs() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; // Prepare files Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register @@ -2306,7 +2220,7 @@ public void OutputMultipleSingleSubRootCanonicalCL() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; // Prepare files Thread.Sleep(_sleepTimeMilliseconds); // need to wait since the timestamp check needs some time to register @@ -2413,16 +2327,14 @@ public void OutputCLMinimalRebuildOptimization() CanonicalTrackedOutputFiles outputs = new CanonicalTrackedOutputFiles(DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); // Represent our tracked and provided inputs - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), sources, null, outputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // First of all, all things should be up to date ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -2437,16 +2349,14 @@ public void OutputCLMinimalRebuildOptimization() Assert.Equal(3, outofdate.Length); // With optimization on, only the source that matches the output will need compilation - d = new CanonicalTrackedInputFiles - ( + d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), sources, null, outputs, true, /* enable minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ outofdate = d.ComputeSourcesNeedingCompilation(); Assert.Single(outofdate); @@ -2512,16 +2422,14 @@ public void OutputCLMinimalRebuildOptimizationComputed() outputs.AddComputedOutputForSourceRoot(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")), Path.GetFullPath(Path.Combine("TestFiles", "three.obj"))); // Represent our tracked and provided inputs - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), sources, null, outputs, false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // First of all, all things should be up to date ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -2536,16 +2444,14 @@ public void OutputCLMinimalRebuildOptimizationComputed() Assert.Equal(3, outofdate.Length); // With optimization on, only the source that matches the output will need compilation - d = new CanonicalTrackedInputFiles - ( + d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), sources, null, outputs, true, /* enable minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ outofdate = d.ComputeSourcesNeedingCompilation(); Assert.Single(outofdate); @@ -2623,16 +2529,14 @@ public void ReplaceOutputForSource() outputs.AddComputedOutputForSourceRoot(threeRootingMarker, Path.GetFullPath(Path.Combine("TestFiles", "three.i"))); // Represent our tracked and provided inputs - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), sources, null, outputs, true, /* minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // We should have one output for three.cpp Assert.Single(outputs.DependencyTable[threeRootingMarker]); @@ -2713,16 +2617,14 @@ public void ExcludeSpecificDirectory() CanonicalTrackedOutputFiles outputs = new CanonicalTrackedOutputFiles(DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.write.tlog")))); // Represent our tracked and provided inputs - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.read.tlog"))), sources, new[] { new TaskItem(Path.GetFullPath(Path.Combine("TeSTfiles", "Foo"))) }, outputs, true, /* minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ // All things should be up to date ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -2776,16 +2678,14 @@ public void SaveCompactedReadTlog() new TaskItem(Path.Combine("TestFiles", "two1.tlog")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -2801,16 +2701,14 @@ public void SaveCompactedReadTlog() Assert.True(Microsoft.Build.Utilities.TrackedDependencies.ItemsExist(tlogs)); // There should be no difference in the out of date files after compaction - CanonicalTrackedInputFiles d1 = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d1 = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ outofdate = d1.ComputeSourcesNeedingCompilation(); @@ -2822,16 +2720,14 @@ public void SaveCompactedReadTlog() }; // All log information should now be in the tlog[0] - CanonicalTrackedInputFiles d2 = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d2 = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs2, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "two.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "two.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ outofdate = d2.ComputeSourcesNeedingCompilation(); @@ -2840,16 +2736,14 @@ public void SaveCompactedReadTlog() Assert.False(d2.DependencyTable.ContainsKey(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp")))); // There should be no difference even if we send in all the original tlogs - CanonicalTrackedInputFiles d3 = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d3 = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "two.cpp"))), null, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "two.obj"))), false, /* no minimal rebuild optimization */ - false /* shred composite rooting markers */ - ); + false); /* shred composite rooting markers */ outofdate = d3.ComputeSourcesNeedingCompilation(); @@ -2867,7 +2761,7 @@ public void SaveCompactedWriteTlog() ITaskItem[] sources = { new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "one.cpp"))), new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "two.cpp"))), - new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp")))}; + new TaskItem(Path.GetFullPath(Path.Combine("TestFiles", "three.cpp"))) }; string rootMarker = FileTracker.FormatRootingMarker(sources); @@ -3038,16 +2932,14 @@ public void SaveCompactedReadTlog_MaintainCompositeRootingMarkers() new TaskItem(Path.Combine("TestFiles", "twothree.obj")) }; - CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, inputs, null, outputs, false, /* no minimal rebuild optimization */ - true /* keep composite rooting markers */ - ); + true); /* keep composite rooting markers */ ITaskItem[] outofdate = d.ComputeSourcesNeedingCompilation(); @@ -3060,16 +2952,14 @@ public void SaveCompactedReadTlog_MaintainCompositeRootingMarkers() d.SaveTlog(); - CanonicalTrackedInputFiles d2 = new CanonicalTrackedInputFiles - ( + CanonicalTrackedInputFiles d2 = new CanonicalTrackedInputFiles( DependencyTestHelper.MockTask, tlogs, inputs, null, outputs, false, /* no minimal rebuild optimization */ - true /* keep composite rooting markers */ - ); + true); /* keep composite rooting markers */ d2.ComputeSourcesNeedingCompilation(); @@ -3092,14 +2982,12 @@ public void InvalidFlatTrackingTLogName() DependencyTestHelper.WriteAll("TestFiles\\one.tlog", ""); MockTask task = DependencyTestHelper.MockTask; - FlatTrackingData data = new FlatTrackingData - ( + FlatTrackingData data = new FlatTrackingData( task, DependencyTestHelper.ItemArray(new TaskItem("TestFiles\\|one|.write.tlog")), - false /* don't skip missing files */ - ); + false); /* don't skip missing files */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(data.DependencyTable); // "DependencyTable should be empty." } @@ -3111,14 +2999,12 @@ public void FlatTrackingTLogWithInitialEmptyLine() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "", "^FOO" }); MockTask task = DependencyTestHelper.MockTask; - FlatTrackingData data = new FlatTrackingData - ( + FlatTrackingData data = new FlatTrackingData( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), - false /* don't skip missing files */ - ); + false); /* don't skip missing files */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(data.DependencyTable); // "DependencyTable should be empty." } @@ -3130,14 +3016,12 @@ public void FlatTrackingTLogWithEmptyLineImmediatelyAfterRoot() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "^FOO", "", "FOO" }); MockTask task = DependencyTestHelper.MockTask; - FlatTrackingData data = new FlatTrackingData - ( + FlatTrackingData data = new FlatTrackingData( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), - false /* don't skip missing files */ - ); + false); /* don't skip missing files */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(data.DependencyTable); // "DependencyTable should be empty." } @@ -3149,14 +3033,12 @@ public void FlatTrackingTLogWithEmptyLineBetweenRoots() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "^FOO", "FOO", "", "^BAR", "BAR" }); MockTask task = DependencyTestHelper.MockTask; - FlatTrackingData data = new FlatTrackingData - ( + FlatTrackingData data = new FlatTrackingData( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), - false /* don't skip missing files */ - ); + false); /* don't skip missing files */ - Assert.Equal(1, ((MockEngine) task.BuildEngine).Warnings); // "Should have a warning." + Assert.Equal(1, ((MockEngine)task.BuildEngine).Warnings); // "Should have a warning." Assert.Empty(data.DependencyTable); // "DependencyTable should be empty." } @@ -3168,14 +3050,12 @@ public void FlatTrackingTLogWithEmptyRoot() File.WriteAllLines(Path.Combine("TestFiles", "one.tlog"), new[] { "^", "FOO" }); MockTask task = DependencyTestHelper.MockTask; - FlatTrackingData data = new FlatTrackingData - ( + FlatTrackingData data = new FlatTrackingData( task, DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), - false /* don't skip missing files */ - ); + false); /* don't skip missing files */ - Assert.Equal(0, ((MockEngine) task.BuildEngine).Warnings); // "Should not warn -- root markers are ignored by default" + Assert.Equal(0, ((MockEngine)task.BuildEngine).Warnings); // "Should not warn -- root markers are ignored by default" Assert.Single(data.DependencyTable); // "DependencyTable should only contain one entry." } @@ -3575,14 +3455,12 @@ public void FlatTrackingExcludeDirectories() // Get the newest time w/o any exclude paths Dictionary sharedLastWriteTimeUtcCache = new Dictionary(StringComparer.OrdinalIgnoreCase); - FlatTrackingData data = new FlatTrackingData - ( + FlatTrackingData data = new FlatTrackingData( DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), null, DateTime.MinValue, null, - sharedLastWriteTimeUtcCache - ); + sharedLastWriteTimeUtcCache); DateTime originalNewest = data.NewestFileTimeUtc; @@ -3597,14 +3475,12 @@ public void FlatTrackingExcludeDirectories() DependencyTestHelper.WriteAll(Path.Combine("TestFiles", "ToBeExcluded", "SubdirectoryExcluded", "three.h"), ""); // Now do a flat tracker ignoring the exclude directories and make sure the time didn't change - data = new FlatTrackingData - ( + data = new FlatTrackingData( DependencyTestHelper.ItemArray(new TaskItem(Path.Combine("TestFiles", "one.tlog"))), null, DateTime.MinValue, new[] { Path.GetFullPath(Path.Combine("TestFiles", "ToBeExcluded")) }, - sharedLastWriteTimeUtcCache - ); + sharedLastWriteTimeUtcCache); Assert.Equal(originalNewest, data.NewestFileTimeUtc); // "Timestamp changed when no tracked files changed." } @@ -3680,7 +3556,7 @@ public static ITaskItem[] ItemArray(ITaskItem item) return itemList.ToArray(); } - public static MockTask MockTask => new MockTask(AssemblyResources.PrimaryResources) {BuildEngine = new MockEngine()}; + public static MockTask MockTask => new MockTask(AssemblyResources.PrimaryResources) { BuildEngine = new MockEngine() }; public static void WriteAll(string filename, string content) => File.WriteAllText(filename, content); } diff --git a/src/Utilities/ApiContract.cs b/src/Utilities/ApiContract.cs index 4023e0adb6b..854a72e7b17 100644 --- a/src/Utilities/ApiContract.cs +++ b/src/Utilities/ApiContract.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Xml; @@ -56,8 +56,7 @@ internal static void ReadContractsElement(XmlElement element, ICollection /// Assumes the itemspec passed in is escaped. /// The item-spec string. - public TaskItem - ( - string itemSpec - ) + public TaskItem( + string itemSpec) { ErrorUtilities.VerifyThrowArgumentNull(itemSpec, nameof(itemSpec)); @@ -91,11 +89,9 @@ string itemSpec /// /// The item-spec string. /// Custom metadata on the item. - public TaskItem - ( + public TaskItem( string itemSpec, - IDictionary itemMetadata - ) : + IDictionary itemMetadata) : this(itemSpec) { ErrorUtilities.VerifyThrowArgumentNull(itemMetadata, nameof(itemMetadata)); @@ -120,10 +116,8 @@ IDictionary itemMetadata /// This constructor creates a new TaskItem, using the given ITaskItem. /// /// The item to copy. - public TaskItem - ( - ITaskItem sourceItem - ) + public TaskItem( + ITaskItem sourceItem) { ErrorUtilities.VerifyThrowArgumentNull(sourceItem, nameof(sourceItem)); @@ -259,11 +253,9 @@ public void RemoveMetadata(string metadataName) /// /// Name of metadata to set or change. /// Value of metadata. - public void SetMetadata - ( + public void SetMetadata( string metadataName, - string metadataValue - ) + string metadataValue) { ErrorUtilities.VerifyThrowArgumentLength(metadataName, nameof(metadataName)); diff --git a/src/Utilities/ToolLocationHelper.cs b/src/Utilities/ToolLocationHelper.cs index 2d20b9f110b..f6911a285ac 100644 --- a/src/Utilities/ToolLocationHelper.cs +++ b/src/Utilities/ToolLocationHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections.Generic; @@ -476,8 +476,7 @@ private static IEnumerable GetTargetPlatformMonikers(string[] || ( platformSDK.TargetPlatformIdentifier.Equals(targetPlatformIdentifier, StringComparison.OrdinalIgnoreCase) - && platformSDK.TargetPlatformVersion <= targetPlatformVersion - ) || platformSDK.ContainsPlatform(targetPlatformIdentifier, targetPlatformVersionString)) + && platformSDK.TargetPlatformVersion <= targetPlatformVersion) || platformSDK.ContainsPlatform(targetPlatformIdentifier, targetPlatformVersionString)) .OrderBy(platform => platform.TargetPlatformVersion); } @@ -532,8 +531,7 @@ public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string t string.IsNullOrEmpty(platform.TargetPlatformIdentifier) || (platform.TargetPlatformIdentifier.Equals(targetPlatformIdentifier, StringComparison.OrdinalIgnoreCase) - && platform.TargetPlatformVersion <= targetPlatformVersion) - ) + && platform.TargetPlatformVersion <= targetPlatformVersion)) && platform.ExtensionSDKs.ContainsKey(sdkMoniker)) .OrderByDescending(platform => platform.TargetPlatformVersion) .DefaultIfEmpty(null).FirstOrDefault(); @@ -791,8 +789,7 @@ public static IList FilterTargetPlatformSdks(IListThe disk roots used to gather installed SDKs. /// The disk roots used to gather installed extension SDKs. /// The registry root used to gather installed extension SDKs. - public static string[] GetPlatformOrFrameworkExtensionSdkReferences - ( + public static string[] GetPlatformOrFrameworkExtensionSdkReferences( string extensionSdkMoniker, string targetSdkIdentifier, string targetSdkVersion, @@ -950,8 +946,7 @@ public static string[] GetPlatformOrFrameworkExtensionSdkReferences string extensionDiskRoots, string registryRoot, string targetPlatformIdentifier, - string targetPlatformVersion - ) + string targetPlatformVersion) { lock (s_locker) { @@ -1074,16 +1069,14 @@ private static string[] GetLegacyTargetPlatformReferences(string targetPlatformI /// Gathers the set of platform winmds for a particular {SDKI, SDKV, TPI, TPMinV, TPV} combination, /// based on the assumption that it is an SDK that has both {SDKI, SDKV} and TP* specifiers. /// - private static string[] GetTargetPlatformReferencesFromManifest - ( + private static string[] GetTargetPlatformReferencesFromManifest( string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string diskRoots, - string registryRoot - ) + string registryRoot) { ErrorUtilities.VerifyThrowArgumentLength(sdkIdentifier, nameof(sdkIdentifier)); ErrorUtilities.VerifyThrowArgumentLength(sdkVersion, nameof(sdkVersion)); @@ -1473,7 +1466,7 @@ public static string GetFoldersInVSInstallsAsString(string minVersionString = nu foldersString = string.Join(";", folders); } } - catch(Exception e) when (!ExceptionHandling.IsCriticalException(e)) + catch (Exception e) when (!ExceptionHandling.IsCriticalException(e)) { // This method will be used in vc props and we don't want to fail project load if it throws for some non critical reason. } @@ -3285,8 +3278,7 @@ public static string GetPathToDotNetFrameworkSdkFile(string fileName, TargetDotN version, visualStudioVersion, UtilitiesDotNetFrameworkArchitecture.Current, - canFallBackIfNecessary: true /* If the file is not found for the current architecture, it's OK to follow fallback mechanisms. */ - ); + canFallBackIfNecessary: true); /* If the file is not found for the current architecture, it's OK to follow fallback mechanisms. */ /// /// Get a fully qualified path to a file in the .NET Framework SDK. Error if the .NET Framework SDK can't be found. @@ -3311,8 +3303,7 @@ public static string GetPathToDotNetFrameworkSdkFile(string fileName, TargetDotN version, visualStudioVersion, architecture, - false /* Do _not_ fall back -- if the user is specifically requesting a particular architecture, they want that architecture. */ - ); + false); /* Do _not_ fall back -- if the user is specifically requesting a particular architecture, they want that architecture. */ /// /// Get a fully qualified path to a file in the .NET Framework SDK. Error if the .NET Framework SDK can't be found. @@ -3459,8 +3450,7 @@ public static string GetPathToWindowsSdkFile(string fileName, TargetDotNetFramew version, visualStudioVersion, UtilitiesDotNetFrameworkArchitecture.Current, - true /* If the file is not found for the current architecture, it's OK to follow fallback mechanisms. */ - ); + true); /* If the file is not found for the current architecture, it's OK to follow fallback mechanisms. */ /// /// Returns the path to a file in the Windows SDK for the desired .NET Framework and Visual Studio version and the desired @@ -3478,8 +3468,7 @@ public static string GetPathToWindowsSdkFile(string fileName, TargetDotNetFramew version, visualStudioVersion, architecture, - false /* Do _not_ fall back -- if the user is specifically requesting a particular architecture, they want that architecture. */ - ); + false); /* Do _not_ fall back -- if the user is specifically requesting a particular architecture, they want that architecture. */ /// /// Returns the path to a file in the Windows SDK for the desired .NET Framework and Visual Studio version and the desired @@ -3808,9 +3797,7 @@ internal static IList GetFrameworkIdentifiers(string frameworkReferenceR if (programFilesReferenceAssemblyLocationFound && ( string.Equals(folder.Name, FrameworkLocationHelper.dotNetFrameworkVersionFolderPrefixV30, StringComparison.OrdinalIgnoreCase) - || string.Equals(folder.Name, FrameworkLocationHelper.dotNetFrameworkVersionFolderPrefixV35, StringComparison.OrdinalIgnoreCase) - ) - ) + || string.Equals(folder.Name, FrameworkLocationHelper.dotNetFrameworkVersionFolderPrefixV35, StringComparison.OrdinalIgnoreCase))) { bAddDotNetFrameworkIdentifier = true; continue; diff --git a/src/Utilities/ToolTask.cs b/src/Utilities/ToolTask.cs index a275a3be4fa..2243faedfca 100644 --- a/src/Utilities/ToolTask.cs +++ b/src/Utilities/ToolTask.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// 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.Collections; @@ -566,12 +566,10 @@ private string GetTemporaryResponseFile(string responseFileCommands, out string /// /// /// The information required to start the process. - protected virtual ProcessStartInfo GetProcessStartInfo - ( + protected virtual ProcessStartInfo GetProcessStartInfo( string pathToTool, string commandLineCommands, - string responseFileSwitch - ) + string responseFileSwitch) { // Build up the command line that will be spawned. string commandLine = commandLineCommands; @@ -652,12 +650,10 @@ string responseFileSwitch /// Command line arguments that should go into a temporary response file /// Command line arguments that should be passed to the tool executable directly /// exit code from the tool - if errors were logged and the tool has an exit code of zero, then we sit it to -1 - protected virtual int ExecuteTool - ( + protected virtual int ExecuteTool( string pathToTool, string responseFileCommands, - string commandLineCommands - ) + string commandLineCommands) { if (!UseCommandProcessor) { @@ -1027,13 +1023,11 @@ private void LogMessagesFromStandardOutput() /// /// /// - private void LogMessagesFromStandardErrorOrOutput - ( + private void LogMessagesFromStandardErrorOrOutput( Queue dataQueue, ManualResetEvent dataAvailableSignal, MessageImportance messageImportance, - StandardOutputOrErrorQueueType queueType - ) + StandardOutputOrErrorQueueType queueType) { ErrorUtilities.VerifyThrow(dataQueue != null, "The data queue must be available."); diff --git a/src/Utilities/TrackedDependencies/CanonicalTrackedFilesHelper.cs b/src/Utilities/TrackedDependencies/CanonicalTrackedFilesHelper.cs index 2343b93060f..12f1c3c88b0 100644 --- a/src/Utilities/TrackedDependencies/CanonicalTrackedFilesHelper.cs +++ b/src/Utilities/TrackedDependencies/CanonicalTrackedFilesHelper.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER diff --git a/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs b/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs index 46495392855..5eb62b39979 100644 --- a/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs +++ b/src/Utilities/TrackedDependencies/CanonicalTrackedInputFiles.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -23,6 +23,7 @@ namespace Microsoft.Build.Utilities /// public class CanonicalTrackedInputFiles { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Member Data // The most recently modified output time private DateTime _outputNewestTime = DateTime.MinValue; @@ -388,8 +389,7 @@ private ITaskItem[] ComputeSourcesNeedingCompilationFromCompositeRootingMarker(b string newestSourceDependencyFile; if ( CanonicalTrackedFilesHelper.FilesExistAndRecordNewestWriteTime(sourcesNeedingCompilationList, _log, out newestSourceDependencyTime, out newestSourceDependencyFile) && - CanonicalTrackedFilesHelper.FilesExistAndRecordOldestWriteTime(_outputFileGroup, _log, out oldestOutputTime, out oldestOutputFile) - ) + CanonicalTrackedFilesHelper.FilesExistAndRecordOldestWriteTime(_outputFileGroup, _log, out oldestOutputTime, out oldestOutputFile)) { if (newestSourceDependencyTime <= oldestOutputTime) { @@ -1092,7 +1092,8 @@ private void RemoveDependenciesFromEntryIfMissing(string rootingMarker, Dictiona } } #endregion +#pragma warning restore format } } - #endif + diff --git a/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs b/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs index 550f3bc8d35..1c19b7868df 100644 --- a/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs +++ b/src/Utilities/TrackedDependencies/CanonicalTrackedOutputFiles.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -21,6 +21,7 @@ namespace Microsoft.Build.Utilities /// public class CanonicalTrackedOutputFiles { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Member Data // The .write. tracking log files private ITaskItem[] _tlogFiles; @@ -784,6 +785,7 @@ private void RemoveDependenciesFromEntryIfMissing(string rootingMarker, Dictiona } } #endregion +#pragma warning restore format } } diff --git a/src/Utilities/TrackedDependencies/DependencyTableCache.cs b/src/Utilities/TrackedDependencies/DependencyTableCache.cs index d87e3ea9507..f18ba533556 100644 --- a/src/Utilities/TrackedDependencies/DependencyTableCache.cs +++ b/src/Utilities/TrackedDependencies/DependencyTableCache.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -29,7 +29,7 @@ internal static class DependencyTableCache /// The dictionary that maps the root of the tlog filenames to the dependencytable built from their content /// internal static Dictionary DependencyTable { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); - +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Methods /// /// Determine if a cache entry is up to date @@ -227,6 +227,7 @@ public bool Equals(ITaskItem x, ITaskItem y) #endregion } +#pragma warning restore format /// /// A cache entry @@ -270,3 +271,4 @@ internal DependencyTableCacheEntry(ITaskItem[] tlogFiles, IDictionary dependency } #endif + diff --git a/src/Utilities/TrackedDependencies/FileTracker.cs b/src/Utilities/TrackedDependencies/FileTracker.cs index e2812d295ca..580921a6e51 100644 --- a/src/Utilities/TrackedDependencies/FileTracker.cs +++ b/src/Utilities/TrackedDependencies/FileTracker.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -65,12 +65,13 @@ public enum ExecutableType ManagedARM64 = 7 } +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both /// /// This class contains utility functions to encapsulate launching and logging for the Tracker /// public static class FileTracker { -#region Static Member Data + #region Static Member Data // The default path to temp, used to create explicitly short and long paths private static readonly string s_tempPath = FileUtilities.TempFileDirectory; @@ -113,11 +114,11 @@ public static class FileTracker // Static cache of the path separator character in an array for use in String.Split. private static readonly string pathSeparator = Path.PathSeparator.ToString(); -#endregion + #endregion -#region Static Member Initializers + #region Static Member Initializers - static List InitializeCommonApplicationDataPaths() + private static List InitializeCommonApplicationDataPaths() { List commonApplicationDataPaths = new(); @@ -142,9 +143,9 @@ static List InitializeCommonApplicationDataPaths() return commonApplicationDataPaths; } -#endregion + #endregion -#region Native method wrappers + #region Native method wrappers /// /// Stops tracking file accesses. @@ -209,9 +210,9 @@ public static void StartTrackingContextWithRoot(string intermediateDirectory, st [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLogs", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")] public static void WriteContextTLogs(string intermediateDirectory, string taskName) => InprocTrackingNativeMethods.WriteContextTLogs(intermediateDirectory, taskName); -#endregion // Native method wrappers + #endregion // Native method wrappers -#region Methods + #region Methods /// /// Test to see if the specified file is excluded from tracked dependencies @@ -528,8 +529,7 @@ private static string GetPath(string filename, DotNetFrameworkArchitecture bitne s_TrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase) || s_FileTrackerFilename.Equals(filename, StringComparison.OrdinalIgnoreCase), "This method should only be passed s_TrackerFilename or s_FileTrackerFilename, but was passed {0} instead!", - filename - ); + filename); // Look for FileTracker.dll/Tracker.exe in the MSBuild tools directory. They may exist elsewhere on disk, // but other copies aren't guaranteed to be compatible with the latest. @@ -640,7 +640,7 @@ public static string TrackerArguments(string command, string arguments, string d public static string TrackerArguments(string command, string arguments, string dllName, string intermediateDirectory, string rootFiles, string cancelEventName) => TrackerResponseFileArguments(dllName, intermediateDirectory, rootFiles, cancelEventName) + TrackerCommandArguments(command, arguments); -#region StartProcess methods + #region StartProcess methods /// /// Start the process; tracking the command. @@ -707,7 +707,7 @@ public static Process StartProcess(string command, string arguments, ExecutableT public static Process StartProcess(string command, string arguments, ExecutableType toolType) => StartProcess(command, arguments, toolType, null, null, null, null); -#endregion // StartProcess methods + #endregion // StartProcess methods /// /// Logs a message of the given importance using the specified resource string. To the specified Log. @@ -757,9 +757,9 @@ internal static void LogWarningWithCodeFromResources(TaskLoggingHelper Log, stri Log?.LogWarningWithCodeFromResources(messageResourceName, messageArgs); } -#endregion + #endregion } - +#pragma warning restore format /// /// Dependency filter delegate. Used during TLog saves in order for tasks to selectively remove dependencies from the written /// graph. @@ -770,3 +770,4 @@ internal static void LogWarningWithCodeFromResources(TaskLoggingHelper Log, stri } #endif + diff --git a/src/Utilities/TrackedDependencies/FlatTrackingData.cs b/src/Utilities/TrackedDependencies/FlatTrackingData.cs index 3a3b9d71130..b9c6288db79 100644 --- a/src/Utilities/TrackedDependencies/FlatTrackingData.cs +++ b/src/Utilities/TrackedDependencies/FlatTrackingData.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. #if FEATURE_FILE_TRACKER @@ -23,6 +23,7 @@ namespace Microsoft.Build.Utilities /// public class FlatTrackingData { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Constants // The maximum number of outputs that should be logged, if more than this, then no outputs are logged private const int MaxLogCount = 100; @@ -886,6 +887,7 @@ public static void FinalizeTLogs(bool trackedOperationsSucceeded, ITaskItem[] re } } #endregion +#pragma warning restore format } /// diff --git a/src/Utilities/TrackedDependencies/TrackedDependencies.cs b/src/Utilities/TrackedDependencies/TrackedDependencies.cs index ccc53acd3ae..2a2cd90e4c7 100644 --- a/src/Utilities/TrackedDependencies/TrackedDependencies.cs +++ b/src/Utilities/TrackedDependencies/TrackedDependencies.cs @@ -1,5 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.IO; @@ -17,6 +17,7 @@ namespace Microsoft.Build.Utilities /// public static class TrackedDependencies { +#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both #region Methods /// /// Expand wildcards in the item list. @@ -91,5 +92,6 @@ internal static bool ItemsExist(ITaskItem[] files) return allExist; } #endregion +#pragma warning restore format } } diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/AssemblyFixtureAttribute.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/AssemblyFixtureAttribute.cs index ab44a3e90c3..42d05e95efa 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/AssemblyFixtureAttribute.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/AssemblyFixtureAttribute.cs @@ -1,4 +1,7 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; #nullable disable diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestAssemblyRunnerWithAssemblyFixture.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestAssemblyRunnerWithAssemblyFixture.cs index 85ccedf6f8b..a74228cb0ec 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestAssemblyRunnerWithAssemblyFixture.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestAssemblyRunnerWithAssemblyFixture.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Linq; using System.Threading; @@ -12,8 +15,8 @@ namespace Xunit.NetCore.Extensions { public class XunitTestAssemblyRunnerWithAssemblyFixture : XunitTestAssemblyRunner { - readonly Dictionary assemblyFixtureMappings = new Dictionary(); - List assemblyFixtureAttributes; + private readonly Dictionary assemblyFixtureMappings = new Dictionary(); + private List assemblyFixtureAttributes; public XunitTestAssemblyRunnerWithAssemblyFixture(ITestAssembly testAssembly, IEnumerable testCases, @@ -40,7 +43,9 @@ protected override async Task AfterTestAssemblyStartingAsync() // Instantiate all the fixtures foreach (var fixtureAttr in fixturesAttrs.Where(a => a.LifetimeScope == AssemblyFixtureAttribute.Scope.Assembly)) + { assemblyFixtureMappings[fixtureAttr.FixtureType] = Activator.CreateInstance(fixtureAttr.FixtureType); + } }); } @@ -48,7 +53,9 @@ protected override Task BeforeTestAssemblyFinishedAsync() { // Make sure we clean up everybody who is disposable, and use Aggregator.Run to isolate Dispose failures foreach (var disposable in assemblyFixtureMappings.Values.OfType()) + { Aggregator.Run(disposable.Dispose); + } return base.BeforeTestAssemblyFinishedAsync(); } diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestClassRunnerWithAssemblyFixture.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestClassRunnerWithAssemblyFixture.cs index 6b64d7f4e42..44afc240a24 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestClassRunnerWithAssemblyFixture.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestClassRunnerWithAssemblyFixture.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Linq; using System.Threading; @@ -12,8 +15,8 @@ namespace Xunit.NetCore.Extensions { public class XunitTestClassRunnerWithAssemblyFixture : XunitTestClassRunner { - readonly Dictionary assemblyFixtureMappings = new Dictionary(); - readonly List assemblyFixtureAttributes; + private readonly Dictionary assemblyFixtureMappings = new Dictionary(); + private readonly List assemblyFixtureAttributes; public XunitTestClassRunnerWithAssemblyFixture( List assemblyFixtureAttributes, @@ -33,14 +36,18 @@ protected override async Task AfterTestClassStartingAsync() { // Instantiate all the fixtures foreach (var fixtureAttr in assemblyFixtureAttributes.Where(a => a.LifetimeScope == AssemblyFixtureAttribute.Scope.Class)) + { assemblyFixtureMappings[fixtureAttr.FixtureType] = Activator.CreateInstance(fixtureAttr.FixtureType); + } }); } protected override Task BeforeTestClassFinishedAsync() { // Make sure we clean up everybody who is disposable, and use Aggregator.Run to isolate Dispose failures foreach (var disposable in assemblyFixtureMappings.Values.OfType()) + { Aggregator.Run(disposable.Dispose); + } return base.BeforeTestClassFinishedAsync(); } diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestCollectionRunnerWithAssemblyFixture.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestCollectionRunnerWithAssemblyFixture.cs index 6ccda839570..6171ff3f902 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestCollectionRunnerWithAssemblyFixture.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestCollectionRunnerWithAssemblyFixture.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -11,9 +14,9 @@ namespace Xunit.NetCore.Extensions { public class XunitTestCollectionRunnerWithAssemblyFixture : XunitTestCollectionRunner { - readonly Dictionary assemblyFixtureMappings; - readonly IMessageSink diagnosticMessageSink; - readonly List assemblyFixtureAttributes; + private readonly Dictionary assemblyFixtureMappings; + private readonly IMessageSink diagnosticMessageSink; + private readonly List assemblyFixtureAttributes; public XunitTestCollectionRunnerWithAssemblyFixture(Dictionary assemblyFixtureMappings, List assemblyFixtureAttributes, @@ -37,9 +40,10 @@ protected override Task RunTestClassAsync(ITestClass testClass, IRef // so instead we'll just let collection fixtures override assembly fixtures. var combinedFixtures = new Dictionary(assemblyFixtureMappings); foreach (var kvp in CollectionFixtureMappings) + { combinedFixtures[kvp.Key] = kvp.Value; + } - return new XunitTestClassRunnerWithAssemblyFixture(assemblyFixtureAttributes, testClass, @class, testCases, diagnosticMessageSink, MessageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), CancellationTokenSource, combinedFixtures).RunAsync(); } } diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkExecutorWithAssemblyFixture.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkExecutorWithAssemblyFixture.cs index 42d906d9e97..605fa16786e 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkExecutorWithAssemblyFixture.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkExecutorWithAssemblyFixture.cs @@ -1,4 +1,7 @@ -using System.Collections.Generic; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Collections.Generic; using System.Reflection; using Xunit.Abstractions; using Xunit.Sdk; @@ -16,7 +19,9 @@ public XunitTestFrameworkExecutorWithAssemblyFixture(AssemblyName assemblyName, protected override async void RunTestCases(IEnumerable testCases, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions) { using (var assemblyRunner = new XunitTestAssemblyRunnerWithAssemblyFixture(TestAssembly, testCases, DiagnosticMessageSink, executionMessageSink, executionOptions)) + { await assemblyRunner.RunAsync(); + } } } } diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkWithAssemblyFixture.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkWithAssemblyFixture.cs index aa1fcae63de..de14792e09d 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkWithAssemblyFixture.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestFrameworkWithAssemblyFixture.cs @@ -1,4 +1,7 @@ -using System.Reflection; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Reflection; using Xunit.Abstractions; using Xunit.Sdk; diff --git a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestMethodRunnerWithAssemblyFixture.cs b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestMethodRunnerWithAssemblyFixture.cs index 29765c69e2b..84307112d1d 100644 --- a/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestMethodRunnerWithAssemblyFixture.cs +++ b/src/Xunit.NetCore.Extensions/AssemblyFixtureSupport/XunitTestMethodRunnerWithAssemblyFixture.cs @@ -1,4 +1,7 @@ -using System; +// 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.Collections.Generic; using System.Linq; using System.Threading; @@ -11,8 +14,8 @@ namespace Xunit.NetCore.Extensions { public class XunitTestMethodRunnerWithAssemblyFixture : XunitTestMethodRunner { - readonly Dictionary assemblyFixtureMappings = new Dictionary(); - readonly List assemblyFixtureAttributes; + private readonly Dictionary assemblyFixtureMappings = new Dictionary(); + private readonly List assemblyFixtureAttributes; public XunitTestMethodRunnerWithAssemblyFixture(List assemblyFixtureAttributes, ITestMethod testMethod, @@ -37,7 +40,9 @@ protected override void AfterTestMethodStarting() { // Instantiate all the fixtures foreach (var fixtureAttr in assemblyFixtureAttributes.Where(a => a.LifetimeScope == AssemblyFixtureAttribute.Scope.Method)) + { assemblyFixtureMappings[fixtureAttr.FixtureType] = Activator.CreateInstance(fixtureAttr.FixtureType); + } }); } @@ -45,7 +50,9 @@ protected override void BeforeTestMethodFinished() { // Make sure we clean up everybody who is disposable, and use Aggregator.Run to isolate Dispose failures foreach (var disposable in assemblyFixtureMappings.Values.OfType()) + { Aggregator.Run(disposable.Dispose); + } base.BeforeTestMethodFinished(); }