From d7ecf45e8d66c19c130a0a8bf1786650e8e6483f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Fri, 13 Nov 2020 14:16:06 -0800 Subject: [PATCH 001/138] Move windows package signing to use ESRP (#14060) --- .../releaseBuild/azureDevOps/releaseBuild.yml | 1 + .../templates/windows-package-signing.yml | 62 ++++++++----------- 2 files changed, 28 insertions(+), 35 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/releaseBuild.yml b/tools/releaseBuild/azureDevOps/releaseBuild.yml index 6df2fe18f09..5e87ff58ec7 100644 --- a/tools/releaseBuild/azureDevOps/releaseBuild.yml +++ b/tools/releaseBuild/azureDevOps/releaseBuild.yml @@ -16,6 +16,7 @@ resources: type: github endpoint: ComplianceGHRepo name: PowerShell/compliance + ref: master variables: - name: DOTNET_CLI_TELEMETRY_OPTOUT diff --git a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml index 571467a3fb5..3803226958a 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml @@ -8,15 +8,19 @@ jobs: ${{ parameters.parentJobs }} condition: succeeded() pool: - name: Package ES Standard Build + vmImage: windows-latest variables: - BuildConfiguration: release - BuildPlatform: any cpu + - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE + value: 1 + - group: ESRP steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: shouldSign.yml - template: SetVersionVariables.yml parameters: @@ -36,36 +40,15 @@ jobs: # Diagnostics is not critical it passes every time it runs continueOnError: true - - powershell: | - $authenticodefiles = @( - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x64.msi" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x86.msi" - ) - - $msixFiles = @( - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x86.msix" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-x64.msix" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-arm32.msix" - "$(System.ArtifactsDirectory)\signed\PowerShell-$(Version)-win-arm64.msix" - ) - - tools/releaseBuild/generatePackgeSigning.ps1 -AuthenticodeFiles $authenticodeFiles -path "$(System.ArtifactsDirectory)\package.xml" -MsixCertType $env:MSIX_TYPE -MsixFiles $msixFiles - displayName: 'Generate Package Signing Xml' - - - powershell: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture signing xml' - - - task: PkgESCodeSign@10 - displayName: 'CodeSign $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(System.ArtifactsDirectory)\signed + signOutputPath: $(Build.StagingDirectory)\signedPackages + certificateId: "CP-230012" + pattern: | + **\*.msi + **\*.msix + useMinimatch: true - powershell: | new-item -itemtype Directory -path '$(Build.StagingDirectory)\signedPackages' @@ -110,8 +93,17 @@ jobs: msi: no msix: no - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' + - task: SFP.build-tasks.custom-build-task-2.EsrpMalwareScanning@1 + displayName: 'Malware Scanning' + inputs: + ConnectedServiceName: pwshEsrpScanning + FolderPath: '$(Build.StagingDirectory)' + Pattern: | + **\*.msix + **\*.msi + **\*.zip + UseMinimatch: true + SessionTimeout: 30 - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' From 2efa1634e52b2d0258a4064c0a6a26aa832d9ab8 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2020 14:19:30 -0800 Subject: [PATCH 002/138] Bump `NJsonSchema` from `10.2.2` to `10.3.1` (#14040) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 9fcfdea2ae7..3ce6232894f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -34,7 +34,7 @@ - + From c7781d157eb529aafb05e383573af96c1b97a059 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Fri, 13 Nov 2020 17:05:09 -0800 Subject: [PATCH 003/138] Reinstate `Test-Connection` tests (#13324) --- .../Test-Connection.Tests.ps1 | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 index bcd0562af85..10f39bca320 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Test-Connection.Tests.ps1 @@ -44,6 +44,7 @@ Describe "Test-Connection" -tags "CI" { $targetAddress = "127.0.0.1" $targetAddressIPv6 = "::1" $UnreachableAddress = "10.11.12.13" + # under some environments, we can't round trip this and retrieve the real name from the address # in this case we will simply use the hostname $jobContinues = Start-Job { Test-Connection $using:targetAddress -Repeat } @@ -105,7 +106,7 @@ Describe "Test-Connection" -tags "CI" { $error[0].Exception.InnerException.ErrorCode | Should -Be $code } - It "Force IPv4 with implicit PingOptions" -Pending { + It "Force IPv4 with implicit PingOptions" { $result = Test-Connection $testAddress -Count 1 -IPv4 $result[0].Address | Should -BeExactly $testAddress @@ -116,6 +117,7 @@ Describe "Test-Connection" -tags "CI" { } # In VSTS, address is 0.0.0.0 + # This test is marked as PENDING as .NET Core does not return correct PingOptions from ping request It "Force IPv4 with explicit PingOptions" -Pending { $result1 = Test-Connection $testAddress -Count 1 -IPv4 -MaxHops 10 -DontFragment @@ -259,7 +261,7 @@ Describe "Test-Connection" -tags "CI" { Context "MTUSizeDetect" { # We skip the MtuSize detection tests when in containers, as the environments throw raw exceptions # instead of returning a PacketTooBig response cleanly. - It "MTUSizeDetect works" -Pending:($true -or $env:__INCONTAINER -eq 1) { + It "MTUSizeDetect works" -Pending:($env:__INCONTAINER -eq 1) { $result = Test-Connection $testAddress -MtuSize $result | Should -BeOfType Microsoft.PowerShell.Commands.TestConnectionCommand+PingMtuStatus @@ -282,7 +284,7 @@ Describe "Test-Connection" -tags "CI" { $result = Test-Connection $testAddress -TraceRoute -IPv4 $result[0] | Should -BeOfType Microsoft.PowerShell.Commands.TestConnectionCommand+TraceStatus - $result[0].Source | Should -BeExactly $hostName + $result[0].Source | Should -BeExactly $testAddress $result[0].TargetAddress | Should -BeExactly $testAddress $result[0].Target | Should -BeExactly $testAddress $result[0].Hop | Should -Be 1 From f13d27ba3e8081dc6eef389d89a34ea71115b3c2 Mon Sep 17 00:00:00 2001 From: Christopher Yeleighton Date: Sat, 14 Nov 2020 02:20:15 +0100 Subject: [PATCH 004/138] Update hyperlink for `DefaultPromptFunctionText` (#13176) --- .../engine/InitialSessionState.cs | 16 +++++++++++++++- .../engine/Help/assets/HelpURI/V2Cmdlets.csv | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 8d9b01ad134..bf7748924f8 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4762,8 +4762,22 @@ internal static SessionStateAliasEntry[] BuiltInAliases internal const string DefaultPromptFunctionText = @" ""PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ""; +# .ForwardHelpTargetName about_Prompts +# .SYNOPSIS +# The PowerShell command prompt indicates +# that PowerShell is ready to run a command. +# .DESCRIPTION +# To customize the prompt, write a new Prompt function. +# The function is not protected, so you can overwrite it. +# .OUTPUTS +# The Prompt function must return an object. +# As a best practice, return a string +# or an object that is formatted as a string. +# The maximum recommended length is 80 characters. # .Link -# https://go.microsoft.com/fwlink/?LinkID=225750 +# https://go.microsoft.com/fwlink/?LinkId=2136843 +# .Link +# about_Prompts # .ExternalHelp System.Management.Automation.dll-help.xml "; diff --git a/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv b/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv index a88e715c347..5e4a34b592c 100644 --- a/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv +++ b/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv @@ -151,7 +151,7 @@ Out-Null,https://go.microsoft.com/fwlink/?linkid=2096792 Out-Printer,https://go.microsoft.com/fwlink/?LinkID=2109553 Out-String,https://go.microsoft.com/fwlink/?linkid=2097024 Pop-Location,https://go.microsoft.com/fwlink/?linkid=2096907 -Prompt,https://go.microsoft.com/fwlink/?LinkID=225750 +Prompt,https://go.microsoft.com/fwlink/?LinkId=2136843 Push-Location,https://go.microsoft.com/fwlink/?linkid=2097105 Read-Host,https://go.microsoft.com/fwlink/?linkid=2096610 Receive-Job,https://go.microsoft.com/fwlink/?linkid=2096965 From d9090b4a4989037a64a7a4a440fbd0e6d6a7edcd Mon Sep 17 00:00:00 2001 From: Ilya Date: Sat, 14 Nov 2020 06:22:26 +0500 Subject: [PATCH 005/138] Write better error message if config file is broken (#13496) --- .../engine/PSConfiguration.cs | 4 + .../resources/PSConfigurationStrings.resx | 123 ++++++++++++++++++ test/xUnit/csharp/test_PSConfiguration.cs | 26 ++++ 3 files changed, 153 insertions(+) create mode 100644 src/System.Management.Automation/resources/PSConfigurationStrings.resx diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index ade427b2154..e6388f291c3 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -402,6 +402,10 @@ private T ReadValueFromFile(ConfigScope scope, string key, T defaultValue = d configData = serializer.Deserialize(jsonReader) ?? emptyConfig; } + catch (Exception exc) + { + throw PSTraceSource.NewInvalidOperationException(exc, PSConfigurationStrings.CanNotConfigurationFile, args: fileName); + } finally { fileLock.ExitReadLock(); diff --git a/src/System.Management.Automation/resources/PSConfigurationStrings.resx b/src/System.Management.Automation/resources/PSConfigurationStrings.resx new file mode 100644 index 00000000000..a1671d7f9e8 --- /dev/null +++ b/src/System.Management.Automation/resources/PSConfigurationStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + PowerShell has stopped working because of a security issue: Cannot read the configuration file: {0} + + diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 6237f453335..f16614c85ee 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -362,6 +362,22 @@ private void CreateEmptyFile(string fileName) File.Create(fileName).Dispose(); } + public void SetupConfigFile5() + { + CleanupConfigFiles(); + + // System wide config file is broken + CreateBrokenConfigFile(systemWideConfigFile); + + // Current user config file is broken + CreateBrokenConfigFile(currentUserConfigFile); + } + + private void CreateBrokenConfigFile(string fileName) + { + File.WriteAllText(fileName, "[abbra"); + } + internal void ForceReadingFromFile() { // Reset the cached roots. @@ -952,5 +968,15 @@ public void Utils_GetPolicySetting_BothConfigFilesNotExist() consoleSessionConfiguration = Utils.GetPolicySetting(Utils.CurrentUserThenSystemWideConfig); fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null); } + + [Fact, TestPriority(11)] + public void PowerShellConfig_GetPowerShellPolicies_BrokenSystemConfig() + { + fixture.SetupConfigFile5(); + fixture.ForceReadingFromFile(); + + Assert.Throws(() => PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.AllUsers)); + Assert.Throws(() => PowerShellConfig.Instance.GetPowerShellPolicies(ConfigScope.CurrentUser)); + } } } From e7232b89c9f6952ec01b8052c14c2a54fa52a18d Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Sun, 15 Nov 2020 11:31:50 +0000 Subject: [PATCH 006/138] Fix PriorityAttribute name (#14094) Fix regression after #13496 --- test/xUnit/csharp/test_PSConfiguration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index f16614c85ee..430e920ace9 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -969,7 +969,7 @@ public void Utils_GetPolicySetting_BothConfigFilesNotExist() fixture.CompareConsoleSessionConfiguration(consoleSessionConfiguration, null); } - [Fact, TestPriority(11)] + [Fact, Priority(11)] public void PowerShellConfig_GetPowerShellPolicies_BrokenSystemConfig() { fixture.SetupConfigFile5(); From fcd9e373410f771b6bbe5ad7cc3d9be710181625 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 16 Nov 2020 14:54:05 +0000 Subject: [PATCH 007/138] Remove unnecessary usings part 4 (#14023) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0005 --- .../commands/utility/ConvertFrom-SddlString.cs | 2 -- .../commands/utility/ConvertFromMarkdownCommand.cs | 3 --- .../commands/utility/ConvertTo-Html.cs | 1 - .../commands/utility/CsvCommands.cs | 2 -- .../commands/utility/CustomSerialization.cs | 1 - .../FormatAndOutput/OutGridView/ExpressionColumnInfo.cs | 3 --- .../FormatAndOutput/common/WriteFormatDataCommand.cs | 1 - .../utility/FormatAndOutput/format-wide/Format-Wide.cs | 1 - .../utility/FormatAndOutput/out-file/Out-File.cs | 2 -- .../utility/FormatAndOutput/out-string/Out-String.cs | 2 -- .../commands/utility/GetHostCmdlet.cs | 2 -- .../commands/utility/GetMember.cs | 1 - .../commands/utility/GetVerbCommand.cs | 1 - .../commands/utility/Group-Object.cs | 1 - .../commands/utility/MarkdownOptionCommands.cs | 4 ---- .../commands/utility/Measure-Object.cs | 2 -- .../commands/utility/New-Object.cs | 4 ++++ .../commands/utility/NewAliasCommand.cs | 1 - .../commands/utility/NewTemporaryFileCommand.cs | 1 - .../commands/utility/PSBreakpointAccessorCommandBase.cs | 3 --- .../commands/utility/ReadConsoleCmdlet.cs | 1 - .../commands/utility/RegisterObjectEventCommand.cs | 1 - .../commands/utility/RemoveAliasCommand.cs | 1 - .../commands/utility/SetAliasCommand.cs | 1 - .../commands/utility/ShowMarkdownCommand.cs | 2 -- .../commands/utility/UnblockFile.cs | 9 +++++---- .../commands/utility/UtilityCommon.cs | 1 - .../commands/utility/Var.cs | 1 - .../Common/BasicHtmlWebResponseObject.Common.cs | 2 -- .../utility/WebCmdlet/Common/ContentHelper.Common.cs | 1 - .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 3 --- .../commands/utility/WriteAliasCommandBase.cs | 3 --- .../commands/utility/WriteConsoleCmdlet.cs | 1 - .../commands/utility/WriteProgressCmdlet.cs | 2 -- .../commands/utility/trace/MshHostTraceListener.cs | 1 - .../commands/utility/trace/TraceCommandBase.cs | 3 --- .../commands/utility/trace/TraceExpressionCommand.cs | 2 -- .../commands/utility/trace/TraceListenerCommandBase.cs | 2 -- 38 files changed, 9 insertions(+), 66 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index 1e64dfe7754..1562697975c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -5,8 +5,6 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; using System.Management.Automation; using System.Security.AccessControl; using System.Security.Principal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs index dfa6bd6c4b0..1a87067b9b4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; @@ -12,8 +11,6 @@ using Microsoft.PowerShell.MarkdownRender; -using Dbg = System.Management.Automation; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index e118aeaf41b..5f3a3e3c140 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -4,7 +4,6 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 0f414433191..7e9c34531ec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -11,8 +11,6 @@ using System.Management.Automation; using System.Text; -using Dbg = System.Management.Automation.Diagnostics; - #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index bb9de345b5b..61c0ab2c146 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections; using System.Collections.Generic; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs index 0e529004aec..e905f5d64b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections.Generic; using System.Management.Automation; -using Microsoft.PowerShell.Commands.Internal.Format; - namespace Microsoft.PowerShell.Commands { internal class ExpressionColumnInfo : ColumnInfo diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs index 457418b30fc..5f0db5dfe8a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index fe9a9f687ad..459dabf9555 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index 9885cbcaa47..cfa0c86c226 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -1,10 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.IO; using System.Management.Automation; -using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Text; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs index e76d90af8b5..4199ef0dd68 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs @@ -1,9 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Management.Automation; -using System.Management.Automation.Host; using System.Text; using Microsoft.PowerShell.Commands.Internal.Format; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs index 444e085591f..fec8bafe34a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs @@ -3,8 +3,6 @@ using System.Management.Automation; -using Dbg = System.Management.Automation.Diagnostics; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index 2789aaafe61..a47cf0352e9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -6,7 +6,6 @@ using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; -using System.Reflection; namespace Microsoft.PowerShell.Commands { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs index 766b38116c0..6794e15c1d1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Reflection; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs index 131c27e417e..3a8117858bd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -5,7 +5,6 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Collections.Specialized; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs index 57a3bd59653..d1e1b73c173 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -3,13 +3,9 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; -using System.Threading.Tasks; using Microsoft.PowerShell.MarkdownRender; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 46c1f7062c7..9a6edeb3bb6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -8,8 +8,6 @@ using System.Management.Automation; using System.Management.Automation.Internal; -using Microsoft.PowerShell.Commands.Internal.Format; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index a8b4b69aa1f..b40b53952f0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -10,10 +10,14 @@ using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Language; +#if !UNIX using System.Management.Automation.Security; +#endif using System.Reflection; using System.Runtime.InteropServices; +#if !UNIX using System.Threading; +#endif using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs index 3c95ebbc7de..8726cece2b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs index f8bb3d4e6ea..c807b61d6d2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.IO; using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs index 88b3cde9acf..d3dfd30f9e5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointAccessorCommandBase.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Management.Automation; -using System.Management.Automation.Runspaces; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index 2eb71f1ca5d..0b70e9308d0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs index ce72dac51fe..d4e7dc784c1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Management.Automation; namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs index 7b44a0c2664..a342c8e9461 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs index b2746625375..060f309e447 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Management.Automation; using System.Management.Automation.Internal; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs index 2203fbb20a7..302c7bacd2f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -2,8 +2,6 @@ // Licensed under the MIT License. using System; -using System.Collections; -using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index fad330212ed..b13d310771b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -6,14 +6,15 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +#if UNIX using System.Globalization; -using System.IO; using System.Management.Automation; -using System.Management.Automation.Internal; using System.Runtime.InteropServices; +#else +using System.Management.Automation; +using System.Management.Automation.Internal; +#endif #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index 37a18ef1080..f2cf7bfb672 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -5,7 +5,6 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; -using System.Management.Automation.Runspaces; using System.Text; [module: SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Scope = "type", Target = "Microsoft.PowerShell.Commands.ByteCollection")] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index 1f18ee1b954..6f379462cfe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System; -using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 1d33957d624..f3e04e76462 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -1,12 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Management.Automation; -using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 8e28c630e17..7e48b97a86b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using System; -using System.Linq; using System.Management.Automation; using System.Net.Http; using System.Net.Http.Headers; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 0809b686e1b..d13cecdf543 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -7,7 +7,6 @@ using System.Collections.ObjectModel; using System.Globalization; using System.IO; -using System.Linq; using System.Management.Automation; using System.Net; using System.Net.Http; @@ -22,8 +21,6 @@ using System.Threading.Tasks; using System.Xml; -using Microsoft.Win32; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs index 3dbb2e378ad..82c9c9f6557 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs @@ -1,11 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Management.Automation; -using Dbg = System.Management.Automation; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 7c2f2e44bf9..6bfad511406 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections; using System.Management.Automation; using System.Text; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index 070c1275aa8..93a1c392c11 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -4,8 +4,6 @@ using System; using System.Management.Automation; -using Dbg = System.Management.Automation.Diagnostics; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index d479b4d32c0..0488fb9710f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -4,7 +4,6 @@ using System; using System.Management.Automation; using System.Management.Automation.Internal.Host; -using System.Security.Permissions; using System.Text; namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs index a2e04f79ae1..4cdee2a1517 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs @@ -1,13 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; -using Dbg = System.Management.Automation.Diagnostics; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index f6677752a91..97a398425d1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -10,8 +10,6 @@ using System.Management.Automation.Runspaces; using System.Threading; -using Dbg = System.Management.Automation.Diagnostics; - namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs index 984ce18c731..d57c117ce43 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -10,8 +10,6 @@ using System.Management.Automation.Internal; using System.Security; -using Dbg = System.Management.Automation.Diagnostics; - namespace Microsoft.PowerShell.Commands { /// From 006fe4d2dd1b6575ab2e412f29a92fbc8ff34173 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 16 Nov 2020 14:56:07 +0000 Subject: [PATCH 008/138] Enable IDE0082: ConvertTypeOfToNameOf (#14042) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0082 --- .globalconfig | 2 +- .../host/msh/ConsoleHost.cs | 2 +- src/System.Management.Automation/engine/Attributes.cs | 2 +- src/System.Management.Automation/engine/CmdletInfo.cs | 2 +- src/System.Management.Automation/engine/CommandMetadata.cs | 2 +- .../engine/CompiledCommandParameter.cs | 2 +- .../engine/MshObjectTypeDescriptor.cs | 4 ++-- .../engine/debugger/debugger.cs | 2 +- .../engine/hostifaces/InternalHostUserInterface.cs | 4 ++-- .../engine/remoting/client/remoterunspace.cs | 6 +++--- test/xUnit/csharp/test_AstDefaultVisit.cs | 2 +- 11 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.globalconfig b/.globalconfig index c22cb5a96c8..73ee17272bf 100644 --- a/.globalconfig +++ b/.globalconfig @@ -971,7 +971,7 @@ dotnet_diagnostic.IDE0080.severity = silent dotnet_diagnostic.IDE0081.severity = silent # IDE0082: ConvertTypeOfToNameOf -dotnet_diagnostic.IDE0082.severity = silent +dotnet_diagnostic.IDE0082.severity = warning # IDE0083: UseNotPattern dotnet_diagnostic.IDE0083.severity = silent diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 98e5ff2b1b4..c1a66e81475 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -2741,7 +2741,7 @@ private bool IsIncompleteParseException(Exception e) return false; } - return remoteException.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name; + return remoteException.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException); } private void EvaluateSuggestions(ConsoleHostUserInterface ui) diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 347eb4c7cd5..3ed6ea89380 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -1092,7 +1092,7 @@ private void ValidateRange(object element, ValidateRangeKind rangeKind) innerException: null, Metadata.ValidateRangeElementType, element.GetType().Name, - typeof(int).Name); + nameof(Int32)); } object resultValue; diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 43e255b1549..c10d8b48fad 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -548,7 +548,7 @@ internal override bool ImplementsDynamicParameters { if (ImplementingType != null) { - return (ImplementingType.GetInterface(typeof(IDynamicParameters).Name, true) != null); + return (ImplementingType.GetInterface(nameof(IDynamicParameters), true) != null); } else { diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 5056f2afbb0..aa3db8a3740 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -680,7 +680,7 @@ private void ConstructCmdletMetadataUsingReflection() // Determine if the cmdlet implements dynamic parameters by looking for the interface - Type dynamicParametersType = CommandType.GetInterface(typeof(IDynamicParameters).Name, true); + Type dynamicParametersType = CommandType.GetInterface(nameof(IDynamicParameters), true); if (dynamicParametersType != null) { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index 90011fbde74..dc74210bda5 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -625,7 +625,7 @@ internal ParameterCollectionTypeInformation(Type type) return; } - bool implementsIList = (type.GetInterface(typeof(IList).Name) != null); + bool implementsIList = (type.GetInterface(nameof(IList)) != null); // Look for class Collection. Collection implements IList, and also IList // is more efficient to bind than ICollection. This optimization diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 9a36e04140b..5d3fb3483ac 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -222,8 +222,8 @@ private static PSObject GetComponentPSObject(object component) { throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent, "component", - typeof(PSObject).Name, - typeof(PSObjectTypeDescriptor).Name); + nameof(PSObject), + nameof(PSObjectTypeDescriptor)); } mshObj = descriptor.Instance; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index a32276bcc79..c993f2ecfe8 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -4138,7 +4138,7 @@ internal void TraceVariableSet(string varName, object value) // because 'ToStringParser' would iterate through the enumerator to get the individual elements, which will // make irreversible changes to the enumerator. bool isValueAnIEnumerator = PSObject.Base(value) is IEnumerator; - string valAsString = isValueAnIEnumerator ? typeof(IEnumerator).Name : PSObject.ToStringParser(_context, value); + string valAsString = isValueAnIEnumerator ? nameof(IEnumerator) : PSObject.ToStringParser(_context, value); int msgLength = 60 - varName.Length; if (valAsString.Length > msgLength) diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 4dbc7acb855..6b6a099e5c3 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -680,12 +680,12 @@ internal static Type GetFieldType(FieldDescription field) internal static bool IsSecuritySensitiveType(string typeName) { - if (typeName.Equals(typeof(PSCredential).Name, StringComparison.OrdinalIgnoreCase)) + if (typeName.Equals(nameof(PSCredential), StringComparison.OrdinalIgnoreCase)) { return true; } - if (typeName.Equals(typeof(SecureString).Name, StringComparison.OrdinalIgnoreCase)) + if (typeName.Equals(nameof(SecureString), StringComparison.OrdinalIgnoreCase)) { return true; } diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 7824c350c78..4c209a3c05a 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -1936,7 +1936,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { // Allow the IncompleteParseException to throw so that the console // can handle here strings and continued parsing. - if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name) + if (re.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException)) { throw new IncompleteParseException( (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null, @@ -1945,8 +1945,8 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC // Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can // clean up the debug session. - if ((re.ErrorRecord.CategoryInfo.Reason == typeof(InvalidRunspacePoolStateException).Name) || - (re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name)) + if ((re.ErrorRecord.CategoryInfo.Reason == nameof(InvalidRunspacePoolStateException)) || + (re.ErrorRecord.CategoryInfo.Reason == nameof(RemoteException))) { throw new PSRemotingTransportException( (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty); diff --git a/test/xUnit/csharp/test_AstDefaultVisit.cs b/test/xUnit/csharp/test_AstDefaultVisit.cs index 925f2c6be53..283c1f73071 100644 --- a/test/xUnit/csharp/test_AstDefaultVisit.cs +++ b/test/xUnit/csharp/test_AstDefaultVisit.cs @@ -44,7 +44,7 @@ public static class AstDefaultVisitTests public static void TestCustomAstVisitor() { var ast = Parser.ParseInput("a | b", out _, out _); - var expected = typeof(NamedBlockAst).Name; + var expected = nameof(NamedBlockAst); var myVisitor1 = new MyICustomAstVisitor2(); var result1 = ast.EndBlock.Accept(myVisitor1); From a0e9d7b04069da2de2cfa844459c2c859e363088 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 16 Nov 2020 14:57:48 +0000 Subject: [PATCH 009/138] Enable IDE0041: UseIsNullCheck (#14041) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0041 --- .globalconfig | 2 +- src/System.Management.Automation/engine/MshMemberInfo.cs | 2 +- src/System.Management.Automation/engine/PSVersionInfo.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.globalconfig b/.globalconfig index 73ee17272bf..af8d90c09d6 100644 --- a/.globalconfig +++ b/.globalconfig @@ -848,7 +848,7 @@ dotnet_diagnostic.IDE0039.severity = silent dotnet_diagnostic.IDE0040.severity = warning # IDE0041: UseIsNullCheck -dotnet_diagnostic.IDE0041.severity = silent +dotnet_diagnostic.IDE0041.severity = warning # IDE0042: UseDeconstruction dotnet_diagnostic.IDE0042.severity = silent diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 50d036a1bdd..88379f261d2 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -1971,7 +1971,7 @@ public bool Equals(PSMethodInvocationConstraints other) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) { return false; } diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 529374a58db..289f105987e 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -859,7 +859,7 @@ public int CompareTo(object version) /// public int CompareTo(SemanticVersion value) { - if ((object)value == null) + if (value is null) return 1; if (Major != value.Major) From 9ca6be1d6343334f948b710ed6d01ddd9d442419 Mon Sep 17 00:00:00 2001 From: "James Truher [MSFT]" Date: Tue, 17 Nov 2020 09:50:59 -0800 Subject: [PATCH 010/138] Revert "Update hyperlink for `DefaultPromptFunctionText` (#13176)" (#14107) --- .../engine/InitialSessionState.cs | 16 +--------------- .../engine/Help/assets/HelpURI/V2Cmdlets.csv | 2 +- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index bf7748924f8..8d9b01ad134 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4762,22 +4762,8 @@ internal static SessionStateAliasEntry[] BuiltInAliases internal const string DefaultPromptFunctionText = @" ""PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ""; -# .ForwardHelpTargetName about_Prompts -# .SYNOPSIS -# The PowerShell command prompt indicates -# that PowerShell is ready to run a command. -# .DESCRIPTION -# To customize the prompt, write a new Prompt function. -# The function is not protected, so you can overwrite it. -# .OUTPUTS -# The Prompt function must return an object. -# As a best practice, return a string -# or an object that is formatted as a string. -# The maximum recommended length is 80 characters. # .Link -# https://go.microsoft.com/fwlink/?LinkId=2136843 -# .Link -# about_Prompts +# https://go.microsoft.com/fwlink/?LinkID=225750 # .ExternalHelp System.Management.Automation.dll-help.xml "; diff --git a/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv b/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv index 5e4a34b592c..a88e715c347 100644 --- a/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv +++ b/test/powershell/engine/Help/assets/HelpURI/V2Cmdlets.csv @@ -151,7 +151,7 @@ Out-Null,https://go.microsoft.com/fwlink/?linkid=2096792 Out-Printer,https://go.microsoft.com/fwlink/?LinkID=2109553 Out-String,https://go.microsoft.com/fwlink/?linkid=2097024 Pop-Location,https://go.microsoft.com/fwlink/?linkid=2096907 -Prompt,https://go.microsoft.com/fwlink/?LinkId=2136843 +Prompt,https://go.microsoft.com/fwlink/?LinkID=225750 Push-Location,https://go.microsoft.com/fwlink/?linkid=2097105 Read-Host,https://go.microsoft.com/fwlink/?linkid=2096610 Receive-Job,https://go.microsoft.com/fwlink/?linkid=2096965 From 44a701fb51b348f8cdeba323659abe2b625a3716 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 18 Nov 2020 18:13:09 +0000 Subject: [PATCH 011/138] Add StyleCop.Analyzers package (#13963) * Add StyleCop.Analyzers with all rules disabled * Downgrade to 1.2.0-beta.205 * Enable SA1518: Use line endings correctly at end of file https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1518.md --- .globalconfig | 546 ++++++++++++++++++++++++++++++++++++++++ Analyzers.props | 5 + PowerShell.Common.props | 1 + test/Test.Common.props | 2 + 4 files changed, 554 insertions(+) create mode 100644 Analyzers.props diff --git a/.globalconfig b/.globalconfig index af8d90c09d6..ced5ff22453 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1002,3 +1002,549 @@ dotnet_diagnostic.IDE1007.severity = silent # IDE1008: UnboundConstructor dotnet_diagnostic.IDE1008.severity = silent + +# SA0001: XML comment analysis disabled +dotnet_diagnostic.SA0001.severity = none + +# SA0002: Invalid settings file +dotnet_diagnostic.SA0002.severity = none + +# SA1000: Keywords should be spaced correctly +dotnet_diagnostic.SA1000.severity = none + +# SA1001: Commas should be spaced correctly +dotnet_diagnostic.SA1001.severity = none + +# SA1002: Semicolons should be spaced correctly +dotnet_diagnostic.SA1002.severity = none + +# SA1003: Symbols should be spaced correctly +dotnet_diagnostic.SA1003.severity = none + +# SA1004: Documentation lines should begin with single space +dotnet_diagnostic.SA1004.severity = none + +# SA1005: Single line comments should begin with single space +dotnet_diagnostic.SA1005.severity = none + +# SA1006: Preprocessor keywords should not be preceded by space +dotnet_diagnostic.SA1006.severity = none + +# SA1007: Operator keyword should be followed by space +dotnet_diagnostic.SA1007.severity = none + +# SA1008: Opening parenthesis should be spaced correctly +dotnet_diagnostic.SA1008.severity = none + +# SA1009: Closing parenthesis should be spaced correctly +dotnet_diagnostic.SA1009.severity = none + +# SA1010: Opening square brackets should be spaced correctly +dotnet_diagnostic.SA1010.severity = none + +# SA1011: Closing square brackets should be spaced correctly +dotnet_diagnostic.SA1011.severity = none + +# SA1012: Opening braces should be spaced correctly +dotnet_diagnostic.SA1012.severity = none + +# SA1013: Closing braces should be spaced correctly +dotnet_diagnostic.SA1013.severity = none + +# SA1014: Opening generic brackets should be spaced correctly +dotnet_diagnostic.SA1014.severity = none + +# SA1015: Closing generic brackets should be spaced correctly +dotnet_diagnostic.SA1015.severity = none + +# SA1016: Opening attribute brackets should be spaced correctly +dotnet_diagnostic.SA1016.severity = none + +# SA1017: Closing attribute brackets should be spaced correctly +dotnet_diagnostic.SA1017.severity = none + +# SA1018: Nullable type symbols should be spaced correctly +dotnet_diagnostic.SA1018.severity = none + +# SA1019: Member access symbols should be spaced correctly +dotnet_diagnostic.SA1019.severity = none + +# SA1020: Increment decrement symbols should be spaced correctly +dotnet_diagnostic.SA1020.severity = none + +# SA1021: Negative signs should be spaced correctly +dotnet_diagnostic.SA1021.severity = none + +# SA1022: Positive signs should be spaced correctly +dotnet_diagnostic.SA1022.severity = none + +# SA1023: Dereference and access of symbols should be spaced correctly +dotnet_diagnostic.SA1023.severity = none + +# SA1024: Colons Should Be Spaced Correctly +dotnet_diagnostic.SA1024.severity = none + +# SA1025: Code should not contain multiple whitespace in a row +dotnet_diagnostic.SA1025.severity = none + +# SA1026: Code should not contain space after new or stackalloc keyword in implicitly typed array allocation +dotnet_diagnostic.SA1026.severity = none + +# SA1027: Use tabs correctly +dotnet_diagnostic.SA1027.severity = none + +# SA1028: Code should not contain trailing whitespace +dotnet_diagnostic.SA1028.severity = none + +# SA1100: Do not prefix calls with base unless local implementation exists +dotnet_diagnostic.SA1100.severity = none + +# SA1101: Prefix local calls with this +dotnet_diagnostic.SA1101.severity = none + +# SA1102: Query clause should follow previous clause +dotnet_diagnostic.SA1102.severity = none + +# SA1103: Query clauses should be on separate lines or all on one line +dotnet_diagnostic.SA1103.severity = none + +# SA1104: Query clause should begin on new line when previous clause spans multiple lines +dotnet_diagnostic.SA1104.severity = none + +# SA1105: Query clauses spanning multiple lines should begin on own line +dotnet_diagnostic.SA1105.severity = none + +# SA1106: Code should not contain empty statements +dotnet_diagnostic.SA1106.severity = none + +# SA1107: Code should not contain multiple statements on one line +dotnet_diagnostic.SA1107.severity = none + +# SA1108: Block statements should not contain embedded comments +dotnet_diagnostic.SA1108.severity = none + +# SA1110: Opening parenthesis or bracket should be on declaration line +dotnet_diagnostic.SA1110.severity = none + +# SA1111: Closing parenthesis should be on line of last parameter +dotnet_diagnostic.SA1111.severity = none + +# SA1112: Closing parenthesis should be on line of opening parenthesis +dotnet_diagnostic.SA1112.severity = none + +# SA1113: Comma should be on the same line as previous parameter +dotnet_diagnostic.SA1113.severity = none + +# SA1114: Parameter list should follow declaration +dotnet_diagnostic.SA1114.severity = none + +# SA1115: Parameter should follow comma +dotnet_diagnostic.SA1115.severity = none + +# SA1116: Split parameters should start on line after declaration +dotnet_diagnostic.SA1116.severity = none + +# SA1117: Parameters should be on same line or separate lines +dotnet_diagnostic.SA1117.severity = none + +# SA1118: Parameter should not span multiple lines +dotnet_diagnostic.SA1118.severity = none + +# SA1119: Statement should not use unnecessary parenthesis +dotnet_diagnostic.SA1119.severity = none + +# SA1120: Comments should contain text +dotnet_diagnostic.SA1120.severity = none + +# SA1121: Use built-in type alias +dotnet_diagnostic.SA1121.severity = none + +# SA1122: Use string.Empty for empty strings +dotnet_diagnostic.SA1122.severity = none + +# SA1123: Do not place regions within elements +dotnet_diagnostic.SA1123.severity = none + +# SA1124: Do not use regions +dotnet_diagnostic.SA1124.severity = none + +# SA1125: Use shorthand for nullable types +dotnet_diagnostic.SA1125.severity = none + +# SA1127: Generic type constraints should be on their own line +dotnet_diagnostic.SA1127.severity = none + +# SA1128: Put constructor initializers on their own line +dotnet_diagnostic.SA1128.severity = none + +# SA1129: Do not use default value type constructor +dotnet_diagnostic.SA1129.severity = none + +# SA1130: Use lambda syntax +dotnet_diagnostic.SA1130.severity = none + +# SA1131: Use readable conditions +dotnet_diagnostic.SA1131.severity = none + +# SA1132: Do not combine fields +dotnet_diagnostic.SA1132.severity = none + +# SA1133: Do not combine attributes +dotnet_diagnostic.SA1133.severity = none + +# SA1134: Attributes should not share line +dotnet_diagnostic.SA1134.severity = none + +# SA1135: Using directives should be qualified +dotnet_diagnostic.SA1135.severity = none + +# SA1136: Enum values should be on separate lines +dotnet_diagnostic.SA1136.severity = none + +# SA1137: Elements should have the same indentation +dotnet_diagnostic.SA1137.severity = none + +# SA1139: Use literal suffix notation instead of casting +dotnet_diagnostic.SA1139.severity = none + +# SA1141: Use tuple syntax +dotnet_diagnostic.SA1141.severity = none + +# SA1142: Refer to tuple fields by name +dotnet_diagnostic.SA1142.severity = none + +# SA1200: Using directives should be placed correctly +dotnet_diagnostic.SA1200.severity = none + +# SA1201: Elements should appear in the correct order +dotnet_diagnostic.SA1201.severity = none + +# SA1202: Elements should be ordered by access +dotnet_diagnostic.SA1202.severity = none + +# SA1203: Constants should appear before fields +dotnet_diagnostic.SA1203.severity = none + +# SA1204: Static elements should appear before instance elements +dotnet_diagnostic.SA1204.severity = none + +# SA1205: Partial elements should declare access +dotnet_diagnostic.SA1205.severity = none + +# SA1206: Declaration keywords should follow order +dotnet_diagnostic.SA1206.severity = none + +# SA1207: Protected should come before internal +dotnet_diagnostic.SA1207.severity = none + +# SA1208: System using directives should be placed before other using directives +dotnet_diagnostic.SA1208.severity = none + +# SA1209: Using alias directives should be placed after other using directives +dotnet_diagnostic.SA1209.severity = none + +# SA1210: Using directives should be ordered alphabetically by namespace +dotnet_diagnostic.SA1210.severity = none + +# SA1211: Using alias directives should be ordered alphabetically by alias name +dotnet_diagnostic.SA1211.severity = none + +# SA1212: Property accessors should follow order +dotnet_diagnostic.SA1212.severity = none + +# SA1213: Event accessors should follow order +dotnet_diagnostic.SA1213.severity = none + +# SA1214: Readonly fields should appear before non-readonly fields +dotnet_diagnostic.SA1214.severity = none + +# SA1216: Using static directives should be placed at the correct location +dotnet_diagnostic.SA1216.severity = none + +# SA1217: Using static directives should be ordered alphabetically +dotnet_diagnostic.SA1217.severity = none + +# SA1300: Element should begin with upper-case letter +dotnet_diagnostic.SA1300.severity = none + +# SA1302: Interface names should begin with I +dotnet_diagnostic.SA1302.severity = none + +# SA1303: Const field names should begin with upper-case letter +dotnet_diagnostic.SA1303.severity = none + +# SA1304: Non-private readonly fields should begin with upper-case letter +dotnet_diagnostic.SA1304.severity = none + +# SA1305: Field names should not use Hungarian notation +dotnet_diagnostic.SA1305.severity = none + +# SA1306: Field names should begin with lower-case letter +dotnet_diagnostic.SA1306.severity = none + +# SA1307: Accessible fields should begin with upper-case letter +dotnet_diagnostic.SA1307.severity = none + +# SA1308: Variable names should not be prefixed +dotnet_diagnostic.SA1308.severity = none + +# SA1309: Field names should not begin with underscore +dotnet_diagnostic.SA1309.severity = none + +# SA1310: Field names should not contain underscore +dotnet_diagnostic.SA1310.severity = none + +# SA1311: Static readonly fields should begin with upper-case letter +dotnet_diagnostic.SA1311.severity = none + +# SA1312: Variable names should begin with lower-case letter +dotnet_diagnostic.SA1312.severity = none + +# SA1313: Parameter names should begin with lower-case letter +dotnet_diagnostic.SA1313.severity = none + +# SA1314: Type parameter names should begin with T +dotnet_diagnostic.SA1314.severity = none + +# SA1316: Tuple element names should use correct casing +dotnet_diagnostic.SA1316.severity = none + +# SA1400: Access modifier should be declared +dotnet_diagnostic.SA1400.severity = none + +# SA1401: Fields should be private +dotnet_diagnostic.SA1401.severity = none + +# SA1402: File may only contain a single type +dotnet_diagnostic.SA1402.severity = none + +# SA1403: File may only contain a single namespace +dotnet_diagnostic.SA1403.severity = none + +# SA1404: Code analysis suppression should have justification +dotnet_diagnostic.SA1404.severity = none + +# SA1405: Debug.Assert should provide message text +dotnet_diagnostic.SA1405.severity = none + +# SA1406: Debug.Fail should provide message text +dotnet_diagnostic.SA1406.severity = none + +# SA1407: Arithmetic expressions should declare precedence +dotnet_diagnostic.SA1407.severity = none + +# SA1408: Conditional expressions should declare precedence +dotnet_diagnostic.SA1408.severity = none + +# SA1410: Remove delegate parenthesis when possible +dotnet_diagnostic.SA1410.severity = none + +# SA1411: Attribute constructor should not use unnecessary parenthesis +dotnet_diagnostic.SA1411.severity = none + +# SA1412: Store files as UTF-8 with byte order mark +dotnet_diagnostic.SA1412.severity = none + +# SA1413: Use trailing comma in multi-line initializers +dotnet_diagnostic.SA1413.severity = none + +# SA1414: Tuple types in signatures should have element names +dotnet_diagnostic.SA1414.severity = none + +# SA1500: Braces for multi-line statements should not share line +dotnet_diagnostic.SA1500.severity = none + +# SA1501: Statement should not be on a single line +dotnet_diagnostic.SA1501.severity = none + +# SA1502: Element should not be on a single line +dotnet_diagnostic.SA1502.severity = none + +# SA1503: Braces should not be omitted +dotnet_diagnostic.SA1503.severity = none + +# SA1504: All accessors should be single-line or multi-line +dotnet_diagnostic.SA1504.severity = none + +# SA1505: Opening braces should not be followed by blank line +dotnet_diagnostic.SA1505.severity = none + +# SA1506: Element documentation headers should not be followed by blank line +dotnet_diagnostic.SA1506.severity = none + +# SA1507: Code should not contain multiple blank lines in a row +dotnet_diagnostic.SA1507.severity = none + +# SA1508: Closing braces should not be preceded by blank line +dotnet_diagnostic.SA1508.severity = none + +# SA1509: Opening braces should not be preceded by blank line +dotnet_diagnostic.SA1509.severity = none + +# SA1510: Chained statement blocks should not be preceded by blank line +dotnet_diagnostic.SA1510.severity = none + +# SA1511: While-do footer should not be preceded by blank line +dotnet_diagnostic.SA1511.severity = none + +# SA1512: Single-line comments should not be followed by blank line +dotnet_diagnostic.SA1512.severity = none + +# SA1513: Closing brace should be followed by blank line +dotnet_diagnostic.SA1513.severity = none + +# SA1514: Element documentation header should be preceded by blank line +dotnet_diagnostic.SA1514.severity = none + +# SA1515: Single-line comment should be preceded by blank line +dotnet_diagnostic.SA1515.severity = none + +# SA1516: Elements should be separated by blank line +dotnet_diagnostic.SA1516.severity = none + +# SA1517: Code should not contain blank lines at start of file +dotnet_diagnostic.SA1517.severity = none + +# SA1518: Use line endings correctly at end of file +dotnet_diagnostic.SA1518.severity = warning + +# SA1519: Braces should not be omitted from multi-line child statement +dotnet_diagnostic.SA1519.severity = none + +# SA1520: Use braces consistently +dotnet_diagnostic.SA1520.severity = none + +# SA1600: Elements should be documented +dotnet_diagnostic.SA1600.severity = none + +# SA1601: Partial elements should be documented +dotnet_diagnostic.SA1601.severity = none + +# SA1602: Enumeration items should be documented +dotnet_diagnostic.SA1602.severity = none + +# SA1604: Element documentation should have summary +dotnet_diagnostic.SA1604.severity = none + +# SA1605: Partial element documentation should have summary +dotnet_diagnostic.SA1605.severity = none + +# SA1606: Element documentation should have summary text +dotnet_diagnostic.SA1606.severity = none + +# SA1607: Partial element documentation should have summary text +dotnet_diagnostic.SA1607.severity = none + +# SA1608: Element documentation should not have default summary +dotnet_diagnostic.SA1608.severity = none + +# SA1609: Property documentation should have value +dotnet_diagnostic.SA1609.severity = none + +# SA1610: Property documentation should have value text +dotnet_diagnostic.SA1610.severity = none + +# SA1611: Element parameters should be documented +dotnet_diagnostic.SA1611.severity = none + +# SA1612: Element parameter documentation should match element parameters +dotnet_diagnostic.SA1612.severity = none + +# SA1613: Element parameter documentation should declare parameter name +dotnet_diagnostic.SA1613.severity = none + +# SA1614: Element parameter documentation should have text +dotnet_diagnostic.SA1614.severity = none + +# SA1615: Element return value should be documented +dotnet_diagnostic.SA1615.severity = none + +# SA1616: Element return value documentation should have text +dotnet_diagnostic.SA1616.severity = none + +# SA1617: Void return value should not be documented +dotnet_diagnostic.SA1617.severity = none + +# SA1618: Generic type parameters should be documented +dotnet_diagnostic.SA1618.severity = none + +# SA1619: Generic type parameters should be documented partial class +dotnet_diagnostic.SA1619.severity = none + +# SA1620: Generic type parameter documentation should match type parameters +dotnet_diagnostic.SA1620.severity = none + +# SA1621: Generic type parameter documentation should declare parameter name +dotnet_diagnostic.SA1621.severity = none + +# SA1622: Generic type parameter documentation should have text +dotnet_diagnostic.SA1622.severity = none + +# SA1623: Property summary documentation should match accessors +dotnet_diagnostic.SA1623.severity = none + +# SA1624: Property summary documentation should omit accessor with restricted access +dotnet_diagnostic.SA1624.severity = none + +# SA1625: Element documentation should not be copied and pasted +dotnet_diagnostic.SA1625.severity = none + +# SA1626: Single-line comments should not use documentation style slashes +dotnet_diagnostic.SA1626.severity = none + +# SA1627: Documentation text should not be empty +dotnet_diagnostic.SA1627.severity = none + +# SA1629: Documentation text should end with a period +dotnet_diagnostic.SA1629.severity = none + +# SA1633: File should have header +dotnet_diagnostic.SA1633.severity = none + +# SA1634: File header should show copyright +dotnet_diagnostic.SA1634.severity = none + +# SA1635: File header should have copyright text +dotnet_diagnostic.SA1635.severity = none + +# SA1636: File header copyright text should match +dotnet_diagnostic.SA1636.severity = none + +# SA1637: File header should contain file name +dotnet_diagnostic.SA1637.severity = none + +# SA1638: File header file name documentation should match file name +dotnet_diagnostic.SA1638.severity = none + +# SA1639: File header should have summary +dotnet_diagnostic.SA1639.severity = none + +# SA1640: File header should have valid company text +dotnet_diagnostic.SA1640.severity = none + +# SA1641: File header company name text should match +dotnet_diagnostic.SA1641.severity = none + +# SA1642: Constructor summary documentation should begin with standard text +dotnet_diagnostic.SA1642.severity = none + +# SA1643: Destructor summary documentation should begin with standard text +dotnet_diagnostic.SA1643.severity = none + +# SA1648: inheritdoc should be used with inheriting class +dotnet_diagnostic.SA1648.severity = none + +# SA1649: File name should match first type name +dotnet_diagnostic.SA1649.severity = none + +# SA1651: Do not use placeholder elements +dotnet_diagnostic.SA1651.severity = none + +# SX1101: Do not prefix local calls with 'this.' +dotnet_diagnostic.SX1101.severity = none + +# SX1309: Field names should begin with underscore +dotnet_diagnostic.SX1309.severity = none + +# SX1309S: Static field names should begin with underscore +dotnet_diagnostic.SX1309S.severity = none diff --git a/Analyzers.props b/Analyzers.props new file mode 100644 index 00000000000..a6188d481fc --- /dev/null +++ b/Analyzers.props @@ -0,0 +1,5 @@ + + + + + diff --git a/PowerShell.Common.props b/PowerShell.Common.props index e03bf2cd1a9..2e9f8e6f63b 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -1,4 +1,5 @@ + - + From 0e0cd0b6dfa417870480bc8cb052a542e3f86272 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 24 Nov 2020 10:44:09 +0000 Subject: [PATCH 059/138] Fix IDE0032: UseAutoProperty part 2 (#14244) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0032 --- .../CimBaseAction.cs | 15 +- .../CimCommandBase.cs | 139 ++------- .../CimGetCimClass.cs | 38 +-- .../CimIndicationWatcher.cs | 12 +- .../CimInvokeCimMethod.cs | 24 +- .../CimPromptUser.cs | 16 +- .../CimRegisterCimIndication.cs | 46 +-- .../CimResultObserver.cs | 32 +- .../CimSessionOperations.cs | 100 ++----- .../CimSessionProxy.cs | 277 +++++++----------- .../CimSetCimInstance.cs | 36 +-- .../CimWriteError.cs | 62 +--- .../CimWriteMessage.cs | 28 +- .../CimWriteProgress.cs | 88 ++---- .../CimWriteResultObject.cs | 14 +- .../GetCimAssociatedInstanceCommand.cs | 56 +--- .../GetCimClassCommand.cs | 54 +--- .../GetCimInstanceCommand.cs | 33 +-- .../InvokeCimMethodCommand.cs | 29 +- .../NewCimInstanceCommand.cs | 18 +- .../NewCimSessionCommand.cs | 63 +--- .../NewCimSessionOptionCommand.cs | 18 +- .../RegisterCimIndicationCommand.cs | 18 +- .../RemoveCimInstanceCommand.cs | 20 +- .../SetCimInstanceCommand.cs | 35 +-- .../Utils.cs | 23 +- 26 files changed, 292 insertions(+), 1002 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index 939f6c047a5..a635e5ae765 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -44,20 +44,7 @@ public virtual void Execute(CmdletOperationBase cmdlet) /// , object. /// /// - protected XOperationContextBase Context - { - get - { - return this.context; - } - - set - { - this.context = value; - } - } - - private XOperationContextBase context; + protected XOperationContextBase Context { get; set; } } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index b138c01b806..4744e319c3e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -31,35 +31,19 @@ internal class ParameterDefinitionEntry /// internal ParameterDefinitionEntry(string parameterSetName, bool mandatory) { - this.mandatory = mandatory; - this.parameterSetName = parameterSetName; + this.IsMandatory = mandatory; + this.ParameterSetName = parameterSetName; } /// /// Property ParameterSetName. /// - internal string ParameterSetName - { - get - { - return this.parameterSetName; - } - } - - private readonly string parameterSetName = null; + internal string ParameterSetName { get; } = null; /// /// Whether the parameter is mandatory to the set. /// - internal bool IsMandatory - { - get - { - return this.mandatory; - } - } - - private readonly bool mandatory = false; + internal bool IsMandatory { get; } = false; } /// @@ -75,8 +59,8 @@ internal class ParameterSetEntry /// internal ParameterSetEntry(UInt32 mandatoryParameterCount) { - this.mandatoryParameterCount = mandatoryParameterCount; - this.isDefaultParameterSet = false; + this.MandatoryParameterCount = mandatoryParameterCount; + this.IsDefaultParameterSet = false; reset(); } @@ -86,8 +70,8 @@ internal ParameterSetEntry(UInt32 mandatoryParameterCount) /// internal ParameterSetEntry(ParameterSetEntry toClone) { - this.mandatoryParameterCount = toClone.MandatoryParameterCount; - this.isDefaultParameterSet = toClone.IsDefaultParameterSet; + this.MandatoryParameterCount = toClone.MandatoryParameterCount; + this.IsDefaultParameterSet = toClone.IsDefaultParameterSet; reset(); } @@ -98,8 +82,8 @@ internal ParameterSetEntry(ParameterSetEntry toClone) /// internal ParameterSetEntry(UInt32 mandatoryParameterCount, bool isDefault) { - this.mandatoryParameterCount = mandatoryParameterCount; - this.isDefaultParameterSet = isDefault; + this.MandatoryParameterCount = mandatoryParameterCount; + this.IsDefaultParameterSet = isDefault; reset(); } @@ -108,107 +92,39 @@ internal ParameterSetEntry(UInt32 mandatoryParameterCount, bool isDefault) /// internal void reset() { - this.setMandatoryParameterCount = this.setMandatoryParameterCountAtBeginProcess; - this.isValueSet = this.isValueSetAtBeginProcess; + this.SetMandatoryParameterCount = this.SetMandatoryParameterCountAtBeginProcess; + this.IsValueSet = this.IsValueSetAtBeginProcess; } /// /// Property DefaultParameterSet /// - internal bool IsDefaultParameterSet - { - get - { - return this.isDefaultParameterSet; - } - } - - private readonly bool isDefaultParameterSet = false; + internal bool IsDefaultParameterSet { get; } = false; /// /// Property MandatoryParameterCount /// - internal UInt32 MandatoryParameterCount - { - get - { - return this.mandatoryParameterCount; - } - } - - private readonly UInt32 mandatoryParameterCount = 0; + internal UInt32 MandatoryParameterCount { get; } = 0; /// /// Property IsValueSet /// - internal bool IsValueSet - { - get - { - return this.isValueSet; - } - - set - { - this.isValueSet = value; - } - } - - private bool isValueSet = false; + internal bool IsValueSet { get; set; } = false; /// /// Property IsValueSetAtBeginProcess /// - internal bool IsValueSetAtBeginProcess - { - get - { - return this.isValueSetAtBeginProcess; - } - - set - { - this.isValueSetAtBeginProcess = value; - } - } - - private bool isValueSetAtBeginProcess = false; + internal bool IsValueSetAtBeginProcess { get; set; } = false; /// /// Property SetMandatoryParameterCount /// - internal UInt32 SetMandatoryParameterCount - { - get - { - return this.setMandatoryParameterCount; - } - - set - { - this.setMandatoryParameterCount = value; - } - } - - private UInt32 setMandatoryParameterCount = 0; + internal UInt32 SetMandatoryParameterCount { get; set; } = 0; /// /// Property SetMandatoryParameterCountAtBeginProcess /// - internal UInt32 SetMandatoryParameterCountAtBeginProcess - { - get - { - return this.setMandatoryParameterCountAtBeginProcess; - } - - set - { - this.setMandatoryParameterCountAtBeginProcess = value; - } - } - - private UInt32 setMandatoryParameterCountAtBeginProcess = 0; + internal UInt32 SetMandatoryParameterCountAtBeginProcess { get; set; } = 0; } /// @@ -531,7 +447,7 @@ internal void CheckParameterSet() { try { - this.parameterSetName = this.parameterBinder.GetParameterSet(); + this.ParameterSetName = this.parameterBinder.GetParameterSet(); } finally { @@ -539,7 +455,7 @@ internal void CheckParameterSet() } } - DebugHelper.WriteLog("current parameterset is: " + this.parameterSetName, 4); + DebugHelper.WriteLog("current parameterset is: " + this.ParameterSetName, 4); } /// @@ -689,13 +605,6 @@ protected virtual void DisposeInternal() /// private readonly object myLock = new(); - /// - /// - /// parameter set name - /// - /// - private string parameterSetName; - /// /// This flag is introduced to resolve the parameter set name /// during process record @@ -747,13 +656,7 @@ internal CimAsyncOperation AsyncOperation /// Get current ParameterSetName of the cmdlet /// /// - internal string ParameterSetName - { - get - { - return this.parameterSetName; - } - } + internal string ParameterSetName { get; private set; } /// /// Gets/Sets cmdlet operation wrapper object. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index dbb50a779c4..7cd9657eed8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -30,10 +30,10 @@ internal CimGetCimClassContext( string thePropertyName, string theQualifierName) { - this.className = theClassName; - this.methodName = theMethodName; - this.propertyName = thePropertyName; - this.qualifierName = theQualifierName; + this.ClassName = theClassName; + this.MethodName = theMethodName; + this.PropertyName = thePropertyName; + this.QualifierName = theQualifierName; } /// @@ -44,14 +44,7 @@ internal CimGetCimClassContext( /// Wildcard expansion should be allowed. /// /// - public string ClassName - { - get { return className; } - - set { className = value; } - } - - private string className; + public string ClassName { get; set; } /// /// @@ -60,12 +53,7 @@ public string ClassName /// Then Filter the by given methodname /// /// - internal string MethodName - { - get { return methodName; } - } - - private readonly string methodName; + internal string MethodName { get; } /// /// @@ -74,12 +62,7 @@ internal string MethodName /// Filter the by given property name. /// /// - internal string PropertyName - { - get { return propertyName; } - } - - private readonly string propertyName; + internal string PropertyName { get; } /// /// @@ -88,12 +71,7 @@ internal string PropertyName /// Filter the by given methodname /// /// - internal string QualifierName - { - get { return qualifierName; } - } - - private readonly string qualifierName; + internal string QualifierName { get; } } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index f64316bd6c7..88f7cd3e89c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -45,15 +45,7 @@ public class CimIndicationEventExceptionEventArgs : CimIndicationEventArgs /// Returns an exception /// /// - public Exception Exception - { - get - { - return exception; - } - } - - private readonly Exception exception; + public Exception Exception { get; } /// /// @@ -64,7 +56,7 @@ public Exception Exception public CimIndicationEventExceptionEventArgs(Exception theException) { context = null; - this.exception = theException; + this.Exception = theException; } } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index 75dbcf317d3..caac54d654f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -40,36 +40,20 @@ internal CimInvokeCimMethodContext(string theNamespace, CimSessionProxy theProxy) { this.proxy = theProxy; - this.methodName = theMethodName; - this.collection = theCollection; + this.MethodName = theMethodName; + this.ParametersCollection = theCollection; this.nameSpace = theNamespace; } /// /// namespace /// - internal string MethodName - { - get - { - return this.methodName; - } - } - - private readonly string methodName; + internal string MethodName { get; } /// /// parameters collection /// - internal CimMethodParametersCollection ParametersCollection - { - get - { - return this.collection; - } - } - - private readonly CimMethodParametersCollection collection; + internal CimMethodParametersCollection ParametersCollection { get; } } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs index 98fb4ed3fc8..c70de0029b6 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs @@ -27,7 +27,7 @@ internal sealed class CimPromptUser : CimSyncAction public CimPromptUser(string message, CimPromptType prompt) { - this.message = message; + this.Message = message; this.prompt = prompt; } @@ -54,7 +54,7 @@ public override void Execute(CmdletOperationBase cmdlet) // NOTES: prepare the whatif message and caption try { - result = cmdlet.ShouldContinue(message, "caption", ref yestoall, ref notoall); + result = cmdlet.ShouldContinue(Message, "caption", ref yestoall, ref notoall); if (yestoall) { this.responseType = CimResponseType.YesToAll; @@ -87,7 +87,7 @@ public override void Execute(CmdletOperationBase cmdlet) case CimPromptType.Normal: try { - result = cmdlet.ShouldProcess(message); + result = cmdlet.ShouldProcess(Message); if (result) { this.responseType = CimResponseType.Yes; @@ -121,15 +121,7 @@ public override void Execute(CmdletOperationBase cmdlet) /// /// Prompt message. /// - public string Message - { - get - { - return message; - } - } - - private readonly string message; + public string Message { get; } /// /// Prompt type -Normal or Critical. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index ed547444adc..8dd054698a8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -47,15 +47,7 @@ internal class CimSubscriptionResultEventArgs : CimSubscriptionEventArgs /// subscription result /// /// - public CimSubscriptionResult Result - { - get - { - return result; - } - } - - private readonly CimSubscriptionResult result; + public CimSubscriptionResult Result { get; } /// /// Constructor @@ -65,7 +57,7 @@ public CimSubscriptionResultEventArgs( CimSubscriptionResult theResult) { this.context = null; - this.result = theResult; + this.Result = theResult; } } @@ -81,15 +73,7 @@ internal class CimSubscriptionExceptionEventArgs : CimSubscriptionEventArgs /// subscription result /// /// - public Exception Exception - { - get - { - return exception; - } - } - - private readonly Exception exception; + public Exception Exception { get; } /// /// Constructor @@ -99,7 +83,7 @@ public CimSubscriptionExceptionEventArgs( Exception theException) { this.context = null; - this.exception = theException; + this.Exception = theException; } } @@ -219,7 +203,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio CimWriteError cimWriteError = actionArgs.Action as CimWriteError; if (cimWriteError != null) { - this.exception = cimWriteError.Exception; + this.Exception = cimWriteError.Exception; if (!this.ackedEvent.IsSet) { // an exception happened @@ -233,10 +217,10 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio { DebugHelper.WriteLog("Raise an exception event", 2); - temp(this, new CimSubscriptionExceptionEventArgs(this.exception)); + temp(this, new CimSubscriptionExceptionEventArgs(this.Exception)); } - DebugHelper.WriteLog("Got an exception: {0}", 2, exception); + DebugHelper.WriteLog("Got an exception: {0}", 2, Exception); } CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject; @@ -276,7 +260,7 @@ private void WaitForAckMessage() { DebugHelper.WriteLogEx(); this.ackedEvent.Wait(); - if (this.exception != null) + if (this.Exception != null) { DebugHelper.WriteLogEx("error happened", 0); if (this.Cmdlet != null) @@ -285,14 +269,14 @@ private void WaitForAckMessage() // throw terminating error ErrorRecord errorRecord = ErrorToErrorRecord.ErrorRecordFromAnyException( - new InvocationContext(this.TargetComputerName, null), this.exception, null); + new InvocationContext(this.TargetComputerName, null), this.Exception, null); this.Cmdlet.ThrowTerminatingError(errorRecord); } else { DebugHelper.WriteLogEx("Throw exception", 1); // throw exception out - throw this.exception; + throw this.Exception; } } @@ -363,15 +347,7 @@ private CimSessionProxy CreateSessionProxy( /// /// Exception occurred while start the subscription. /// - internal Exception Exception - { - get - { - return exception; - } - } - - private Exception exception; + internal Exception Exception { get; private set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index 19040bfa3e4..72f14982f2e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -37,21 +37,13 @@ internal class CimResultContext /// internal CimResultContext(object ErrorSource) { - this.errorSource = ErrorSource; + this.ErrorSource = ErrorSource; } /// /// ErrorSource property. /// - internal object ErrorSource - { - get - { - return this.errorSource; - } - } - - private readonly object errorSource; + internal object ErrorSource { get; } } #endregion @@ -228,7 +220,7 @@ internal class CimResultObserver : IObserver /// Operation that can be observed. public CimResultObserver(CimSession session, IObservable observable) { - this.session = session; + this.CurrentSession = session; this.observable = observable; } @@ -241,7 +233,7 @@ public CimResultObserver(CimSession session, IObservable observable, CimResultContext cimResultContext) { - this.session = session; + this.CurrentSession = session; this.observable = observable; this.context = cimResultContext; } @@ -260,7 +252,7 @@ public virtual void OnCompleted() try { AsyncResultCompleteEventArgs completeArgs = new( - this.session, this.observable); + this.CurrentSession, this.observable); this.OnNewResult(this, completeArgs); } catch (Exception ex) @@ -281,7 +273,7 @@ public virtual void OnError(Exception error) try { AsyncResultErrorEventArgs errorArgs = new( - this.session, this.observable, error, this.context); + this.CurrentSession, this.observable, error, this.context); this.OnNewResult(this, errorArgs); } catch (Exception ex) @@ -301,7 +293,7 @@ protected void OnNextCore(object value) try { AsyncResultObjectEventArgs resultArgs = new( - this.session, this.observable, value); + this.CurrentSession, this.observable, value); this.OnNewResult(this, resultArgs); } catch (Exception ex) @@ -334,15 +326,7 @@ public virtual void OnNext(T value) /// /// Session object of the operation. /// - protected CimSession CurrentSession - { - get - { - return session; - } - } - - private readonly CimSession session; + protected CimSession CurrentSession { get; } /// /// Async operation that can be observed. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 97886e831e4..57a3ce6e99e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -24,67 +24,27 @@ internal class CimSessionWrapper /// /// Id of the cimsession. /// - public uint SessionId - { - get - { - return this.sessionId; - } - } - - private readonly uint sessionId; + public uint SessionId { get; } /// /// InstanceId of the cimsession. /// - public Guid InstanceId - { - get - { - return this.instanceId; - } - } - - private readonly Guid instanceId; + public Guid InstanceId { get; } /// /// Name of the cimsession. /// - public string Name - { - get - { - return this.name; - } - } - - private readonly string name; + public string Name { get; } /// /// Computer name of the cimsession. /// - public string ComputerName - { - get - { - return this.computerName; - } - } - - private readonly string computerName; + public string ComputerName { get; } /// /// Wrapped cimsession object. /// - public CimSession CimSession - { - get - { - return this.cimSession; - } - } - - private readonly CimSession cimSession; + public CimSession CimSession { get; } /// /// Computer name of the cimsession. @@ -127,11 +87,11 @@ internal CimSessionWrapper( CimSession theCimSession, ProtocolType theProtocol) { - this.sessionId = theSessionId; - this.instanceId = theInstanceId; - this.name = theName; - this.computerName = theComputerName; - this.cimSession = theCimSession; + this.SessionId = theSessionId; + this.InstanceId = theInstanceId; + this.Name = theName; + this.ComputerName = theComputerName; + this.CimSession = theCimSession; this.psObject = null; this.protocol = theProtocol; } @@ -140,18 +100,18 @@ internal PSObject GetPSObject() { if (psObject == null) { - psObject = new PSObject(this.cimSession); - psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.sessionId)); - psObject.Properties.Add(new PSNoteProperty(CimSessionState.namePropName, this.name)); - psObject.Properties.Add(new PSNoteProperty(CimSessionState.instanceidPropName, this.instanceId)); + psObject = new PSObject(this.CimSession); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.idPropName, this.SessionId)); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.namePropName, this.Name)); + psObject.Properties.Add(new PSNoteProperty(CimSessionState.instanceidPropName, this.InstanceId)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.computernamePropName, this.ComputerName)); psObject.Properties.Add(new PSNoteProperty(CimSessionState.protocolPropName, this.Protocol)); } else { psObject.Properties[CimSessionState.idPropName].Value = this.SessionId; - psObject.Properties[CimSessionState.namePropName].Value = this.name; - psObject.Properties[CimSessionState.instanceidPropName].Value = this.instanceId; + psObject.Properties[CimSessionState.namePropName].Value = this.Name; + psObject.Properties[CimSessionState.instanceidPropName].Value = this.InstanceId; psObject.Properties[CimSessionState.computernamePropName].Value = this.ComputerName; psObject.Properties[CimSessionState.protocolPropName].Value = this.Protocol; } @@ -919,22 +879,14 @@ internal CimTestCimSessionContext( CimSessionWrapper wrapper) { this.proxy = theProxy; - this.cimSessionWrapper = wrapper; + this.CimSessionWrapper = wrapper; this.nameSpace = null; } /// /// Namespace /// - internal CimSessionWrapper CimSessionWrapper - { - get - { - return this.cimSessionWrapper; - } - } - - private readonly CimSessionWrapper cimSessionWrapper; + internal CimSessionWrapper CimSessionWrapper { get; } } /// @@ -945,7 +897,7 @@ internal CimSessionWrapper CimSessionWrapper internal CimNewSession() : base() { this.cimTestSession = new CimTestSession(); - this._disposed = false; + this.Disposed = false; } /// @@ -1062,15 +1014,7 @@ public void ProcessRemainActions(CmdletOperationBase cmdletOperation) /// Indicates whether this object was disposed or not. /// /// - protected bool Disposed - { - get - { - return _disposed; - } - } - - private bool _disposed; + protected bool Disposed { get; private set; } /// /// @@ -1104,13 +1048,13 @@ public void Dispose() /// Whether it is directly called. protected virtual void Dispose(bool disposing) { - if (!this._disposed) + if (!this.Disposed) { if (disposing) { // free managed resources this.cimTestSession.Dispose(); - this._disposed = true; + this.Disposed = true; } // free native resources if there are any } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index 87c6f278fa4..4badfd387c5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -325,7 +325,7 @@ public CimSessionProxy(CimSessionProxy proxy) DebugHelper.WriteLogEx("protocol = {0}", 1, proxy.Protocol); CreateSetSession(null, proxy.CimSession, null, proxy.OperationOptions, proxy.IsTemporaryCimSession); - this.protocol = proxy.Protocol; + this.Protocol = proxy.Protocol; this.OperationTimeout = proxy.OperationTimeout; this.isDefaultSession = proxy.isDefaultSession; } @@ -463,19 +463,19 @@ private void CreateSetSession( } InitOption(operOptions); - this.protocol = ProtocolType.Wsman; - this.isTemporaryCimSession = temporaryCimSession; + this.Protocol = ProtocolType.Wsman; + this.IsTemporaryCimSession = temporaryCimSession; if (cimSession != null) { - this.session = cimSession; + this.CimSession = cimSession; CimSessionState state = CimSessionBase.GetCimSessionState(); if (state != null) { CimSessionWrapper wrapper = state.QuerySession(cimSession); if (wrapper != null) { - this.protocol = wrapper.GetProtocolType(); + this.Protocol = wrapper.GetProtocolType(); } } } @@ -486,29 +486,29 @@ private void CreateSetSession( if (sessionOptions is DComSessionOptions) { string defaultComputerName = ConstValue.IsDefaultComputerName(computerName) ? ConstValue.NullComputerName : computerName; - this.session = CimSession.Create(defaultComputerName, sessionOptions); - this.protocol = ProtocolType.Dcom; + this.CimSession = CimSession.Create(defaultComputerName, sessionOptions); + this.Protocol = ProtocolType.Dcom; } else { - this.session = CimSession.Create(computerName, sessionOptions); + this.CimSession = CimSession.Create(computerName, sessionOptions); } } else { - this.session = CreateCimSessionByComputerName(computerName); + this.CimSession = CreateCimSessionByComputerName(computerName); } - this.isTemporaryCimSession = true; + this.IsTemporaryCimSession = true; } - if (this.isTemporaryCimSession) + if (this.IsTemporaryCimSession) { - AddCimSessionToTemporaryCache(this.session); + AddCimSessionToTemporaryCache(this.CimSession); } this.invocationContextObject = new InvocationContext(this); - DebugHelper.WriteLog("Protocol {0}, Is temporary session ? {1}", 1, this.protocol, this.isTemporaryCimSession); + DebugHelper.WriteLog("Protocol {0}, Is temporary session ? {1}", 1, this.Protocol, this.IsTemporaryCimSession); } #endregion @@ -522,14 +522,14 @@ public UInt32 OperationTimeout { get { - return (UInt32)this.options.Timeout.TotalSeconds; + return (UInt32)this.OperationOptions.Timeout.TotalSeconds; } set { DebugHelper.WriteLogEx("OperationTimeout {0},", 0, value); - this.options.Timeout = TimeSpan.FromSeconds((double)value); + this.OperationOptions.Timeout = TimeSpan.FromSeconds((double)value); } } @@ -540,14 +540,14 @@ public Uri ResourceUri { get { - return this.options.ResourceUri; + return this.OperationOptions.ResourceUri; } set { DebugHelper.WriteLogEx("ResourceUri {0},", 0, value); - this.options.ResourceUri = value; + this.OperationOptions.ResourceUri = value; } } @@ -559,13 +559,13 @@ public bool EnableMethodResultStreaming { get { - return this.options.EnableMethodResultStreaming; + return this.OperationOptions.EnableMethodResultStreaming; } set { DebugHelper.WriteLogEx("EnableMethodResultStreaming {0}", 0, value); - this.options.EnableMethodResultStreaming = value; + this.OperationOptions.EnableMethodResultStreaming = value; } } @@ -580,7 +580,7 @@ public bool EnablePromptUser DebugHelper.WriteLogEx("EnablePromptUser {0}", 0, value); if (value) { - this.options.PromptUser = this.PromptUser; + this.OperationOptions.PromptUser = this.PromptUser; } } } @@ -594,15 +594,15 @@ private void EnablePSSemantics() // this.options.PromptUserForceFlag... // this.options.WriteErrorMode - this.options.WriteErrorMode = CimCallbackMode.Inquire; + this.OperationOptions.WriteErrorMode = CimCallbackMode.Inquire; // !!!NOTES: Does not subscribe to PromptUser for CimCmdlets now // since cmdlet does not provider an approach // to let user select how to handle prompt message // this can be enabled later if needed. - this.options.WriteError = this.WriteError; - this.options.WriteMessage = this.WriteMessage; - this.options.WriteProgress = this.WriteProgress; + this.OperationOptions.WriteError = this.WriteError; + this.OperationOptions.WriteMessage = this.WriteMessage; + this.OperationOptions.WriteProgress = this.WriteProgress; } /// @@ -610,7 +610,7 @@ private void EnablePSSemantics() /// public SwitchParameter KeyOnly { - set { this.options.KeysOnly = value.IsPresent; } + set { this.OperationOptions.KeysOnly = value.IsPresent; } } /// @@ -622,11 +622,11 @@ public SwitchParameter Shallow { if (value.IsPresent) { - this.options.Flags = CimOperationFlags.PolymorphismShallow; + this.OperationOptions.Flags = CimOperationFlags.PolymorphismShallow; } else { - this.options.Flags = CimOperationFlags.None; + this.OperationOptions.Flags = CimOperationFlags.None; } } } @@ -640,11 +640,11 @@ private void InitOption(CimOperationOptions operOptions) if (operOptions != null) { - this.options = new CimOperationOptions(operOptions); + this.OperationOptions = new CimOperationOptions(operOptions); } - else if (this.options == null) + else if (this.OperationOptions == null) { - this.options = new CimOperationOptions(); + this.OperationOptions = new CimOperationOptions(); } this.EnableMethodResultStreaming = true; @@ -665,10 +665,10 @@ public CimSession Detach() DebugHelper.WriteLogEx(); // Remove the CimSession from cache but don't dispose it - RemoveCimSessionFromTemporaryCache(this.session, false); - CimSession sessionToReturn = this.session; - this.session = null; - this.isTemporaryCimSession = false; + RemoveCimSessionFromTemporaryCache(this.CimSession, false); + CimSession sessionToReturn = this.CimSession; + this.CimSession = null; + this.IsTemporaryCimSession = false; return sessionToReturn; } @@ -707,7 +707,7 @@ private void RemoveOperation(IObservable operation) this.operation = null; } - if (this.session != null && this.ContextObject == null) + if (this.CimSession != null && this.ContextObject == null) { DebugHelper.WriteLog("Dispose this proxy object @ RemoveOperation"); this.Dispose(); @@ -734,7 +734,7 @@ protected void FireNewActionEvent(CimBaseAction action) EventHandler temp = this.OnNewCmdletAction; if (temp != null) { - temp(this.session, actionArgs); + temp(this.CimSession, actionArgs); } else { @@ -759,7 +759,7 @@ private void FireOperationCreatedEvent( OperationEventArgs args = new( cancelOperation, operation, false); - this.OnOperationCreated?.Invoke(this.session, args); + this.OnOperationCreated?.Invoke(this.CimSession, args); this.PostOperationCreateEvent(args); } @@ -779,7 +779,7 @@ private void FireOperationDeletedEvent( OperationEventArgs args = new( null, operation, success); PreOperationDeleteEvent(args); - this.OnOperationDeleted?.Invoke(this.session, args); + this.OnOperationDeleted?.Invoke(this.CimSession, args); this.PostOperationDeleteEvent(args); this.RemoveOperation(operation); @@ -1065,15 +1065,15 @@ private static object PostProcessCimInstance(object resultObject) public void CreateInstanceAsync(string namespaceName, CimInstance instance) { Debug.Assert(instance != null, "Caller should verify that instance != NULL."); - DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); + DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.OperationOptions.EnableMethodResultStreaming); this.CheckAvailability(); - this.targetCimInstance = instance; + this.TargetCimInstance = instance; this.operationName = CimCmdletStrings.CimOperationNameCreateInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncResult asyncResult = this.session.CreateInstanceAsync(namespaceName, instance, this.options); + CimAsyncResult asyncResult = this.CimSession.CreateInstanceAsync(namespaceName, instance, this.OperationOptions); ConsumeCimInstanceAsync(asyncResult, new CimResultContext(instance)); } @@ -1087,13 +1087,13 @@ public void DeleteInstanceAsync(string namespaceName, CimInstance instance) Debug.Assert(instance != null, "Caller should verify that instance != NULL."); DebugHelper.WriteLogEx("namespace = {0}; classname = {1};", 0, namespaceName, instance.CimSystemProperties.ClassName); this.CheckAvailability(); - this.targetCimInstance = instance; + this.TargetCimInstance = instance; this.operationName = CimCmdletStrings.CimOperationNameDeleteInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncStatus asyncResult = this.session.DeleteInstanceAsync(namespaceName, instance, this.options); + CimAsyncStatus asyncResult = this.CimSession.DeleteInstanceAsync(namespaceName, instance, this.OperationOptions); ConsumeObjectAsync(asyncResult, new CimResultContext(instance)); } @@ -1105,15 +1105,15 @@ public void DeleteInstanceAsync(string namespaceName, CimInstance instance) public void GetInstanceAsync(string namespaceName, CimInstance instance) { Debug.Assert(instance != null, "Caller should verify that instance != NULL."); - DebugHelper.WriteLogEx("namespace = {0}; classname = {1}; keyonly = {2}", 0, namespaceName, instance.CimSystemProperties.ClassName, this.options.KeysOnly); + DebugHelper.WriteLogEx("namespace = {0}; classname = {1}; keyonly = {2}", 0, namespaceName, instance.CimSystemProperties.ClassName, this.OperationOptions.KeysOnly); this.CheckAvailability(); - this.targetCimInstance = instance; + this.TargetCimInstance = instance; this.operationName = CimCmdletStrings.CimOperationNameGetInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncResult asyncResult = this.session.GetInstanceAsync(namespaceName, instance, this.options); + CimAsyncResult asyncResult = this.CimSession.GetInstanceAsync(namespaceName, instance, this.OperationOptions); ConsumeCimInstanceAsync(asyncResult, new CimResultContext(instance)); } @@ -1127,13 +1127,13 @@ public void ModifyInstanceAsync(string namespaceName, CimInstance instance) Debug.Assert(instance != null, "Caller should verify that instance != NULL."); DebugHelper.WriteLogEx("namespace = {0}; classname = {1}", 0, namespaceName, instance.CimSystemProperties.ClassName); this.CheckAvailability(); - this.targetCimInstance = instance; + this.TargetCimInstance = instance; this.operationName = CimCmdletStrings.CimOperationNameModifyInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncResult asyncResult = this.session.ModifyInstanceAsync(namespaceName, instance, this.options); + CimAsyncResult asyncResult = this.CimSession.ModifyInstanceAsync(namespaceName, instance, this.OperationOptions); ConsumeObjectAsync(asyncResult, new CimResultContext(instance)); } @@ -1158,7 +1158,7 @@ public void EnumerateAssociatedInstancesAsync( Debug.Assert(sourceInstance != null, "Caller should verify that sourceInstance != NULL."); DebugHelper.WriteLogEx("Instance class {0}, association class {1}", 0, sourceInstance.CimSystemProperties.ClassName, associationClassName); this.CheckAvailability(); - this.targetCimInstance = sourceInstance; + this.TargetCimInstance = sourceInstance; this.operationName = CimCmdletStrings.CimOperationNameEnumerateAssociatedInstances; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); @@ -1168,7 +1168,7 @@ public void EnumerateAssociatedInstancesAsync( this.operationParameters.Add(@"sourceRole", sourceRole); this.operationParameters.Add(@"resultRole", resultRole); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.EnumerateAssociatedInstancesAsync(namespaceName, sourceInstance, associationClassName, resultClassName, sourceRole, resultRole, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateAssociatedInstancesAsync(namespaceName, sourceInstance, associationClassName, resultClassName, sourceRole, resultRole, this.OperationOptions); ConsumeCimInstanceAsync(asyncResult, new CimResultContext(sourceInstance)); } @@ -1179,15 +1179,15 @@ public void EnumerateAssociatedInstancesAsync( /// public void EnumerateInstancesAsync(string namespaceName, string className) { - DebugHelper.WriteLogEx("KeyOnly {0}", 0, this.options.KeysOnly); + DebugHelper.WriteLogEx("KeyOnly {0}", 0, this.OperationOptions.KeysOnly); this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameEnumerateInstances; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.EnumerateInstancesAsync(namespaceName, className, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateInstancesAsync(namespaceName, className, this.OperationOptions); string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); ConsumeCimInstanceAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1224,16 +1224,16 @@ public void QueryInstancesAsync( string queryDialect, string queryExpression) { - DebugHelper.WriteLogEx("KeyOnly = {0}", 0, this.options.KeysOnly); + DebugHelper.WriteLogEx("KeyOnly = {0}", 0, this.OperationOptions.KeysOnly); this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameQueryInstances; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"queryDialect", queryDialect); this.operationParameters.Add(@"queryExpression", queryExpression); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.QueryInstancesAsync(namespaceName, queryDialect, queryExpression, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.QueryInstancesAsync(namespaceName, queryDialect, queryExpression, this.OperationOptions); ConsumeCimInstanceAsync(asyncResult, null); } @@ -1246,12 +1246,12 @@ public void EnumerateClassesAsync(string namespaceName) { DebugHelper.WriteLogEx("namespace {0}", 0, namespaceName); this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameEnumerateClasses; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.EnumerateClassesAsync(namespaceName, null, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, null, this.OperationOptions); ConsumeCimClassAsync(asyncResult, null); } @@ -1263,13 +1263,13 @@ public void EnumerateClassesAsync(string namespaceName) public void EnumerateClassesAsync(string namespaceName, string className) { this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameEnumerateClasses; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.EnumerateClassesAsync(namespaceName, className, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, className, this.OperationOptions); string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1283,13 +1283,13 @@ public void GetClassAsync(string namespaceName, string className) { DebugHelper.WriteLogEx("namespace = {0}, className = {1}", 0, namespaceName, className); this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameGetClass; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncResult asyncResult = this.session.GetClassAsync(namespaceName, className, this.options); + CimAsyncResult asyncResult = this.CimSession.GetClassAsync(namespaceName, className, this.OperationOptions); string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1308,16 +1308,16 @@ public void InvokeMethodAsync( CimMethodParametersCollection methodParameters) { Debug.Assert(instance != null, "Caller should verify that instance != NULL."); - DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); + DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.OperationOptions.EnableMethodResultStreaming); this.CheckAvailability(); - this.targetCimInstance = instance; + this.TargetCimInstance = instance; this.operationName = CimCmdletStrings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); this.operationParameters.Add(@"methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.InvokeMethodAsync(namespaceName, instance, methodName, methodParameters, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.InvokeMethodAsync(namespaceName, instance, methodName, methodParameters, this.OperationOptions); ConsumeCimInvokeMethodResultAsync(asyncResult, instance.CimSystemProperties.ClassName, methodName, new CimResultContext(instance)); } @@ -1334,16 +1334,16 @@ public void InvokeMethodAsync( string methodName, CimMethodParametersCollection methodParameters) { - DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); + DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.OperationOptions.EnableMethodResultStreaming); this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); this.operationParameters.Add(@"methodName", methodName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - CimAsyncMultipleResults asyncResult = this.session.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.options); + CimAsyncMultipleResults asyncResult = this.CimSession.InvokeMethodAsync(namespaceName, className, methodName, methodParameters, this.OperationOptions); string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); ConsumeCimInvokeMethodResultAsync(asyncResult, className, methodName, new CimResultContext(errorSource)); } @@ -1363,7 +1363,7 @@ public void SubscribeAsync( { DebugHelper.WriteLogEx("QueryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); this.CheckAvailability(); - this.targetCimInstance = null; + this.TargetCimInstance = null; this.operationName = CimCmdletStrings.CimOperationNameSubscribeIndication; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); @@ -1371,8 +1371,8 @@ public void SubscribeAsync( this.operationParameters.Add(@"queryExpression", queryExpression); this.WriteOperationStartMessage(this.operationName, this.operationParameters); - this.options.Flags |= CimOperationFlags.ReportOperationStarted; - CimAsyncMultipleResults asyncResult = this.session.SubscribeAsync(namespaceName, queryDialect, queryExpression, this.options); + this.OperationOptions.Flags |= CimOperationFlags.ReportOperationStarted; + CimAsyncMultipleResults asyncResult = this.CimSession.SubscribeAsync(namespaceName, queryDialect, queryExpression, this.OperationOptions); ConsumeCimSubscriptionResultAsync(asyncResult, null); } @@ -1385,8 +1385,8 @@ public void TestConnectionAsync() { DebugHelper.WriteLogEx("Start test connection", 0); this.CheckAvailability(); - this.targetCimInstance = null; - CimAsyncResult asyncResult = this.session.TestConnectionAsync(); + this.TargetCimInstance = null; + CimAsyncResult asyncResult = this.CimSession.TestConnectionAsync(); // ignore the test connection result objects ConsumeCimInstanceAsync(asyncResult, true, null); } @@ -1451,42 +1451,15 @@ protected virtual void PostOperationDeleteEvent(OperationEventArgs args) /// The session will be closed while disposing this proxy object /// if it is created by constuctor. /// - internal CimSession CimSession - { - get - { - return this.session; - } - } - - private CimSession session; + internal CimSession CimSession { get; private set; } /// /// The current CimInstance object, against which issued /// current operation, it could be null. /// - internal CimInstance TargetCimInstance - { - get - { - return this.targetCimInstance; - } - } + internal CimInstance TargetCimInstance { get; private set; } = null; - private CimInstance targetCimInstance = null; - - /// - /// Flag controls whether session object should be closed or not. - /// - private bool isTemporaryCimSession; - - internal bool IsTemporaryCimSession - { - get - { - return isTemporaryCimSession; - } - } + internal bool IsTemporaryCimSession { get; private set; } /// /// The CimOperationOptions object, which specifies the options @@ -1496,15 +1469,7 @@ internal bool IsTemporaryCimSession /// The setting MUST be set before start new operation on the /// this proxy object. /// - internal CimOperationOptions OperationOptions - { - get - { - return this.options; - } - } - - private CimOperationOptions options; + internal CimOperationOptions OperationOptions { get; private set; } /// /// All operations completed. @@ -1584,33 +1549,12 @@ private IDisposable CancelOperation /// Current protocol name /// DCOM or WSMAN. /// - internal ProtocolType Protocol - { - get - { - return protocol; - } - } - - private ProtocolType protocol; + internal ProtocolType Protocol { get; private set; } /// /// Cross operation context object. /// - internal XOperationContextBase ContextObject - { - get - { - return this.contextObject; - } - - set - { - this.contextObject = value; - } - } - - private XOperationContextBase contextObject; + internal XOperationContextBase ContextObject { get; set; } /// /// Invocation context object. @@ -1621,20 +1565,7 @@ internal XOperationContextBase ContextObject /// A preprocess object to pre-processing the result object, /// for example, adding PSTypeName, etc. /// - internal IObjectPreProcess ObjectPreProcess - { - get - { - return this.objectPreprocess; - } - - set - { - this.objectPreprocess = value; - } - } - - private IObjectPreProcess objectPreprocess; + internal IObjectPreProcess ObjectPreProcess { get; set; } /// /// is if this was @@ -1684,10 +1615,10 @@ protected virtual void Dispose(bool disposing) // Dispose managed resources. this.DisposeCancelOperation(); - if (this.options != null) + if (this.OperationOptions != null) { - this.options.Dispose(); - this.options = null; + this.OperationOptions.Dispose(); + this.OperationOptions = null; } DisposeTemporaryCimSession(); @@ -1710,12 +1641,12 @@ public bool IsDisposed /// private void DisposeTemporaryCimSession() { - if (this.isTemporaryCimSession && this.session != null) + if (this.IsTemporaryCimSession && this.CimSession != null) { // remove the cimsession from temporary cache - RemoveCimSessionFromTemporaryCache(this.session); - this.isTemporaryCimSession = false; - this.session = null; + RemoveCimSessionFromTemporaryCache(this.CimSession); + this.IsTemporaryCimSession = false; + this.CimSession = null; } } #endregion @@ -1751,11 +1682,11 @@ protected void ConsumeCimInstanceAsync( CimResultObserver observer; if (ignoreResultObjects) { - observer = new IgnoreResultObserver(this.session, asyncResult); + observer = new IgnoreResultObserver(this.CimSession, asyncResult); } else { - observer = new CimResultObserver(this.session, asyncResult, cimResultContext); + observer = new CimResultObserver(this.CimSession, asyncResult, cimResultContext); } observer.OnNewResult += this.ResultEventHandler; @@ -1776,7 +1707,7 @@ protected void ConsumeObjectAsync(IObservable asyncResult, CimResultContext cimResultContext) { CimResultObserver observer = new( - this.session, asyncResult, cimResultContext); + this.CimSession, asyncResult, cimResultContext); observer.OnNewResult += this.ResultEventHandler; this.operationID = Interlocked.Increment(ref gOperationCounter); @@ -1797,7 +1728,7 @@ protected void ConsumeCimClassAsync(IObservable asyncResult, CimResultContext cimResultContext) { CimResultObserver observer = new( - this.session, asyncResult, cimResultContext); + this.CimSession, asyncResult, cimResultContext); observer.OnNewResult += this.ResultEventHandler; this.operationID = Interlocked.Increment(ref gOperationCounter); @@ -1818,7 +1749,7 @@ protected void ConsumeCimSubscriptionResultAsync( CimResultContext cimResultContext) { CimSubscriptionResultObserver observer = new( - this.session, asyncResult, cimResultContext); + this.CimSession, asyncResult, cimResultContext); observer.OnNewResult += this.ResultEventHandler; this.operationID = Interlocked.Increment(ref gOperationCounter); this.AddOperation(asyncResult); @@ -1841,7 +1772,7 @@ protected void ConsumeCimInvokeMethodResultAsync( string methodName, CimResultContext cimResultContext) { - CimMethodResultObserver observer = new(this.session, asyncResult, cimResultContext) + CimMethodResultObserver observer = new(this.CimSession, asyncResult, cimResultContext) { ClassName = className, MethodName = methodName @@ -1872,7 +1803,7 @@ private void CheckAvailability() } } - DebugHelper.WriteLog("KeyOnly {0},", 1, this.options.KeysOnly); + DebugHelper.WriteLog("KeyOnly {0},", 1, this.OperationOptions.KeysOnly); } /// @@ -1882,9 +1813,9 @@ private void CheckAvailability() /// private void AssertSession() { - if (this.IsDisposed || (this.session == null)) + if (this.IsDisposed || (this.CimSession == null)) { - DebugHelper.WriteLogEx("Invalid CimSessionProxy object, disposed? {0}; session object {1}", 1, this.IsDisposed, this.session); + DebugHelper.WriteLogEx("Invalid CimSessionProxy object, disposed? {0}; session object {1}", 1, this.IsDisposed, this.CimSession); throw new ObjectDisposedException(this.ToString()); } } @@ -1903,7 +1834,7 @@ private CimSession CreateCimSessionByComputerName(string computerName) if (option is DComSessionOptions) { DebugHelper.WriteLog("Create dcom cimSession"); - this.protocol = ProtocolType.Dcom; + this.Protocol = ProtocolType.Dcom; return CimSession.Create(ConstValue.NullComputerName, option); } else @@ -2176,7 +2107,7 @@ internal class CimSessionProxyNewCimInstance : CimSessionProxy public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance operation) : base(computerName) { - this.newCimInstance = operation; + this.NewCimInstanceOperation = operation; } /// @@ -2189,7 +2120,7 @@ public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance oper public CimSessionProxyNewCimInstance(CimSession session, CimNewCimInstance operation) : base(session) { - this.newCimInstance = operation; + this.NewCimInstanceOperation = operation; } #endregion @@ -2223,15 +2154,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) #region private members - private readonly CimNewCimInstance newCimInstance = null; - - internal CimNewCimInstance NewCimInstanceOperation - { - get - { - return this.newCimInstance; - } - } + internal CimNewCimInstance NewCimInstanceOperation { get; } = null; #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index 0a8c49dfb50..1ad72e46c79 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -33,50 +33,26 @@ internal CimSetCimInstanceContext(string theNamespace, bool passThru) { this.proxy = theProxy; - this.property = theProperty; + this.Property = theProperty; this.nameSpace = theNamespace; - this.parameterSetName = theParameterSetName; - this.passThru = passThru; + this.ParameterSetName = theParameterSetName; + this.PassThru = passThru; } /// /// property value /// - internal IDictionary Property - { - get - { - return this.property; - } - } - - private readonly IDictionary property; + internal IDictionary Property { get; } /// /// parameter set name /// - internal string ParameterSetName - { - get - { - return this.parameterSetName; - } - } - - private readonly string parameterSetName; + internal string ParameterSetName { get; } /// /// PassThru value /// - internal bool PassThru - { - get - { - return this.passThru; - } - } - - private readonly bool passThru; + internal bool PassThru { get; } } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index 0f64aad70c9..cf922aea143 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -322,8 +322,8 @@ internal sealed class CimWriteError : CimSyncAction /// public CimWriteError(CimInstance error, InvocationContext context) { - this.error = error; - this.invocationContext = context; + this.Error = error; + this.CimInvocationContext = context; } /// @@ -332,9 +332,9 @@ public CimWriteError(CimInstance error, InvocationContext context) /// public CimWriteError(Exception exception, InvocationContext context, CimResultContext cimResultContext) { - this.exception = exception; - this.invocationContext = context; - this.cimResultContext = cimResultContext; + this.Exception = exception; + this.CimInvocationContext = context; + this.ResultContext = cimResultContext; } /// @@ -348,10 +348,10 @@ public override void Execute(CmdletOperationBase cmdlet) Debug.Assert(cmdlet != null, "Caller should verify that cmdlet != null"); try { - Exception errorException = (error != null) ? new CimException(error) : this.Exception; + Exception errorException = (Error != null) ? new CimException(Error) : this.Exception; // PS engine takes care of handling error action - cmdlet.WriteError(ErrorToErrorRecord.ErrorRecordFromAnyException(this.invocationContext, errorException, this.cimResultContext)); + cmdlet.WriteError(ErrorToErrorRecord.ErrorRecordFromAnyException(this.CimInvocationContext, errorException, this.ResultContext)); // if user wants to continue, we will get here this.responseType = CimResponseType.Yes; @@ -375,59 +375,19 @@ public override void Execute(CmdletOperationBase cmdlet) /// Error instance /// /// - private readonly CimInstance error; - internal CimInstance Error - { - get - { - return error; - } - } + internal CimInstance Error { get; } /// /// /// Exception object /// /// - internal Exception Exception - { - get - { - return exception; - } - } - - private readonly Exception exception; + internal Exception Exception { get; } - /// - /// - /// object that contains - /// the information while issuing the current operation - /// - /// - private readonly InvocationContext invocationContext; + internal InvocationContext CimInvocationContext { get; } - internal InvocationContext CimInvocationContext - { - get - { - return invocationContext; - } - } - - /// - /// - /// - private readonly CimResultContext cimResultContext; - - internal CimResultContext ResultContext - { - get - { - return cimResultContext; - } - } + internal CimResultContext ResultContext { get; } #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs index 9a556b68c5e..0b64f9b56a1 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -22,25 +22,13 @@ internal sealed class CimWriteMessage : CimBaseAction /// /// Channel id. /// - private readonly UInt32 channel; - - /// - /// Message to write to the channel. - /// - private readonly string message; #endregion #region Properties - internal UInt32 Channel - { - get { return channel; } - } + internal UInt32 Channel { get; } - internal string Message - { - get { return message; } - } + internal string Message { get; } #endregion @@ -50,8 +38,8 @@ internal string Message public CimWriteMessage(UInt32 channel, string message) { - this.channel = channel; - this.message = message; + this.Channel = channel; + this.Message = message; } /// @@ -64,16 +52,16 @@ public override void Execute(CmdletOperationBase cmdlet) { ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); - switch ((CimWriteMessageChannel)channel) + switch ((CimWriteMessageChannel)Channel) { case CimWriteMessageChannel.Verbose: - cmdlet.WriteVerbose(message); + cmdlet.WriteVerbose(Message); break; case CimWriteMessageChannel.Warning: - cmdlet.WriteWarning(message); + cmdlet.WriteWarning(Message); break; case CimWriteMessageChannel.Debug: - cmdlet.WriteDebug(message); + cmdlet.WriteDebug(Message); break; default: break; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index 94b82e47c29..bda41668b80 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -43,20 +43,20 @@ public CimWriteProgress( UInt32 thePercentageCompleted, UInt32 theSecondsRemaining) { - this.activity = theActivity; - this.activityID = theActivityID; - this.currentOperation = theCurrentOperation; + this.Activity = theActivity; + this.ActivityID = theActivityID; + this.CurrentOperation = theCurrentOperation; if (string.IsNullOrEmpty(theStatusDescription)) { - this.statusDescription = CimCmdletStrings.DefaultStatusDescription; + this.StatusDescription = CimCmdletStrings.DefaultStatusDescription; } else { - this.statusDescription = theStatusDescription; + this.StatusDescription = theStatusDescription; } - this.percentageCompleted = thePercentageCompleted; - this.secondsRemaining = theSecondsRemaining; + this.PercentageCompleted = thePercentageCompleted; + this.SecondsRemaining = theSecondsRemaining; } /// @@ -70,84 +70,54 @@ public override void Execute(CmdletOperationBase cmdlet) DebugHelper.WriteLog( "...Activity {0}: id={1}, remain seconds ={2}, percentage completed = {3}", 4, - this.activity, - this.activityID, - this.secondsRemaining, - this.percentageCompleted); + this.Activity, + this.ActivityID, + this.SecondsRemaining, + this.PercentageCompleted); ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); ProgressRecord record = new( - this.activityID, - this.activity, - this.statusDescription); - record.Activity = this.activity; + this.ActivityID, + this.Activity, + this.StatusDescription); + record.Activity = this.Activity; record.ParentActivityId = 0; - record.SecondsRemaining = (int)this.secondsRemaining; - record.PercentComplete = (int)this.percentageCompleted; + record.SecondsRemaining = (int)this.SecondsRemaining; + record.PercentComplete = (int)this.PercentageCompleted; cmdlet.WriteProgress(record); } #region members /// - /// Activity of the given activity. + /// Gets the activity of the given activity. /// - private readonly string activity; + internal string Activity { get; } /// - /// Activity identifier of the given activity. + /// Gets the activity identifier of the given activity. /// - private readonly int activityID; + internal int ActivityID { get; } /// - /// Current operation text of the given activity. + /// Gets the current operation text of the given activity. /// - private readonly string currentOperation; + internal string CurrentOperation { get; } /// - /// Status description of the given activity. + /// Gets the status description of the given activity. /// - private readonly string statusDescription; + internal string StatusDescription { get; } /// - /// Percentage completed of the given activity. + /// Gets the percentage completed of the given activity. /// - private readonly UInt32 percentageCompleted; + internal UInt32 PercentageCompleted { get; } /// - /// How many seconds remained for the given activity. + /// Gets the number of seconds remaining for the given activity. /// - private readonly UInt32 secondsRemaining; - - internal string Activity - { - get { return activity; } - } - - internal int ActivityID - { - get { return activityID; } - } - - internal string CurrentOperation - { - get { return currentOperation; } - } - - internal string StatusDescription - { - get { return statusDescription; } - } - - internal UInt32 PercentageCompleted - { - get { return percentageCompleted; } - } - - internal UInt32 SecondsRemaining - { - get { return secondsRemaining; } - } + internal UInt32 SecondsRemaining { get; } #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs index 492819c6535..95bf7432291 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs @@ -19,7 +19,7 @@ internal sealed class CimWriteResultObject : CimBaseAction /// public CimWriteResultObject(object result, XOperationContextBase theContext) { - this.result = result; + this.Result = result; this.Context = theContext; } @@ -32,22 +32,14 @@ public CimWriteResultObject(object result, XOperationContextBase theContext) public override void Execute(CmdletOperationBase cmdlet) { ValidationHelper.ValidateNoNullArgument(cmdlet, "cmdlet"); - cmdlet.WriteObject(result, this.Context); + cmdlet.WriteObject(Result, this.Context); } #region members /// /// Result object. /// - internal object Result - { - get - { - return result; - } - } - - private readonly object result; + internal object Result { get; } #endregion } } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index a8a69e187a0..ace8d9ef563 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -53,14 +53,7 @@ public GetCimAssociatedInstanceCommand() [Parameter( Position = 1, ValueFromPipelineByPropertyName = true)] - public string Association - { - get { return association; } - - set { association = value; } - } - - private string association; + public string Association { get; set; } /// /// The following is the definition of the input parameter "ResultClassName". @@ -68,14 +61,7 @@ public string Association /// the given instance. /// [Parameter] - public string ResultClassName - { - get { return resultClassName; } - - set { resultClassName = value; } - } - - private string resultClassName; + public string ResultClassName { get; set; } /// /// @@ -90,11 +76,11 @@ public string ResultClassName [Alias(CimBaseCommand.AliasCimInstance)] public CimInstance InputObject { - get { return cimInstance; } + get { return CimInstance; } set { - cimInstance = value; + CimInstance = value; base.SetParameter(value, nameCimInstance); } } @@ -102,12 +88,7 @@ public CimInstance InputObject /// /// Property for internal usage purpose. /// - internal CimInstance CimInstance - { - get { return cimInstance; } - } - - private CimInstance cimInstance; + internal CimInstance CimInstance { get; private set; } /// /// The following is the definition of the input parameter "Namespace". @@ -115,14 +96,7 @@ internal CimInstance CimInstance /// is registered. /// [Parameter(ValueFromPipelineByPropertyName = true)] - public string Namespace - { - get { return nameSpace; } - - set { nameSpace = value; } - } - - private string nameSpace; + public string Namespace { get; set; } /// /// The following is the definition of the input parameter "OperationTimeoutSec". @@ -133,14 +107,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// @@ -220,14 +187,7 @@ public Microsoft.Management.Infrastructure.CimSession[] CimSession /// /// [Parameter] - public SwitchParameter KeyOnly - { - get { return keyOnly; } - - set { keyOnly = value; } - } - - private SwitchParameter keyOnly; + public SwitchParameter KeyOnly { get; set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index 30290a1f7ba..c80596ed7a1 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -54,14 +54,7 @@ public GetCimClassCommand() [Parameter( Position = 0, ValueFromPipelineByPropertyName = true)] - public string ClassName - { - get { return className; } - - set { className = value; } - } - - private string className; + public string ClassName { get; set; } /// /// @@ -77,14 +70,7 @@ public string ClassName [Parameter( Position = 1, ValueFromPipelineByPropertyName = true)] - public string Namespace - { - get { return nameSpace; } - - set { nameSpace = value; } - } - - private string nameSpace; + public string Namespace { get; set; } /// /// The following is the definition of the input parameter "OperationTimeoutSec". @@ -93,14 +79,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "Session". @@ -158,14 +137,7 @@ public string[] ComputerName /// /// [Parameter(ValueFromPipelineByPropertyName = true)] - public string MethodName - { - get { return methodName; } - - set { methodName = value; } - } - - private string methodName; + public string MethodName { get; set; } /// /// @@ -175,14 +147,7 @@ public string MethodName /// /// [Parameter(ValueFromPipelineByPropertyName = true)] - public string PropertyName - { - get { return propertyName; } - - set { propertyName = value; } - } - - private string propertyName; + public string PropertyName { get; set; } /// /// @@ -192,14 +157,7 @@ public string PropertyName /// /// [Parameter(ValueFromPipelineByPropertyName = true)] - public string QualifierName - { - get { return qualifierName; } - - set { qualifierName = value; } - } - - private string qualifierName; + public string QualifierName { get; set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index 0ed548da052..d22f8cdc693 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -241,14 +241,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". @@ -276,11 +269,11 @@ public UInt32 OperationTimeoutSec [Alias(CimBaseCommand.AliasCimInstance)] public CimInstance InputObject { - get { return cimInstance; } + get { return CimInstance; } set { - cimInstance = value; + CimInstance = value; base.SetParameter(value, nameCimInstance); } } @@ -288,12 +281,7 @@ public CimInstance InputObject /// /// Property for internal usage purpose. /// - internal CimInstance CimInstance - { - get { return cimInstance; } - } - - private CimInstance cimInstance; + internal CimInstance CimInstance { get; private set; } /// /// The following is the definition of the input parameter "Query". @@ -421,23 +409,18 @@ public string Filter [Alias("SelectProperties")] public string[] Property { - get { return property; } + get { return SelectProperties; } set { - property = value; + SelectProperties = value; base.SetParameter(value, nameSelectProperties); } } /// /// Property for internal usage. /// - internal string[] SelectProperties - { - get { return property; } - } - - private string[] property; + internal string[] SelectProperties { get; private set; } #endregion @@ -519,7 +502,7 @@ private void CheckArgument() case CimBaseCommand.ClassNameSessionSet: // validate the classname & property this.className = ValidationHelper.ValidateArgumentIsValidName(nameClassName, this.className); - this.property = ValidationHelper.ValidateArgumentIsValidName(nameSelectProperties, this.property); + this.SelectProperties = ValidationHelper.ValidateArgumentIsValidName(nameSelectProperties, this.SelectProperties); break; default: break; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index 9e7c35d11b3..2c245b8d2b2 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -182,11 +182,11 @@ public string QueryDialect [Alias(CimBaseCommand.AliasCimInstance)] public CimInstance InputObject { - get { return cimInstance; } + get { return CimInstance; } set { - cimInstance = value; + CimInstance = value; base.SetParameter(value, nameCimInstance); } } @@ -194,12 +194,7 @@ public CimInstance InputObject /// /// Property for internal usage purpose. /// - internal CimInstance CimInstance - { - get { return cimInstance; } - } - - private CimInstance cimInstance; + internal CimInstance CimInstance { get; private set; } /// /// The following is the definition of the input parameter "ComputerName". @@ -287,14 +282,7 @@ public CimSession[] CimSession /// [Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] - public IDictionary Arguments - { - get { return arguments; } - - set { arguments = value; } - } - - private IDictionary arguments; + public IDictionary Arguments { get; set; } /// /// The following is the definition of the input parameter "MethodName". @@ -355,14 +343,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index 7ceb91a5559..d524f6b5102 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -169,14 +169,7 @@ public CimClass CimClass ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("Arguments")] - public IDictionary Property - { - get { return property; } - - set { property = value; } - } - - private IDictionary property; + public IDictionary Property { get; set; } /// /// The following is the definition of the input parameter "Namespace". @@ -215,14 +208,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index 5d25ec5b0dc..d0431ccb860 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -52,14 +52,7 @@ public PasswordAuthenticationMechanism Authentication /// [Parameter(Position = 1, ParameterSetName = CredentialParameterSet)] [Credential()] - public PSCredential Credential - { - get { return credential; } - - set { credential = value; } - } - - private PSCredential credential; + public PSCredential Credential { get; set; } /// /// The following is the definition of the input parameter "CertificateThumbprint". @@ -67,14 +60,7 @@ public PSCredential Credential /// [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = CertificateParameterSet)] - public string CertificateThumbprint - { - get { return certificatethumbprint; } - - set { certificatethumbprint = value; } - } - - private string certificatethumbprint; + public string CertificateThumbprint { get; set; } /// /// The following is the definition of the input parameter "ComputerName". @@ -87,14 +73,7 @@ public string CertificateThumbprint ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] ComputerName - { - get { return computername; } - - set { computername = value; } - } - - private string[] computername; + public string[] ComputerName { get; set; } /// /// @@ -108,14 +87,7 @@ public string[] ComputerName /// /// [Parameter(ValueFromPipelineByPropertyName = true)] - public string Name - { - get { return name; } - - set { name = value; } - } - - private string name; + public string Name { get; set; } /// /// @@ -150,17 +122,7 @@ public UInt32 OperationTimeoutSec /// /// [Parameter(ValueFromPipelineByPropertyName = true)] - public SwitchParameter SkipTestConnection - { - get { return skipTestConnection; } - - set - { - skipTestConnection = value; - } - } - - private SwitchParameter skipTestConnection; + public SwitchParameter SkipTestConnection { get; set; } /// /// The following is the definition of the input parameter "Port". @@ -196,14 +158,7 @@ public UInt32 Port /// object is passed, then connection is made using WsMan. /// [Parameter(ValueFromPipelineByPropertyName = true)] - public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption - { - get { return sessionOption; } - - set { sessionOption = value; } - } - - private Microsoft.Management.Infrastructure.Options.CimSessionOptions sessionOption; + public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption { get; set; } #endregion @@ -256,11 +211,11 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr // clone the sessionOption object if (this.SessionOption is WSManSessionOptions) { - options = new WSManSessionOptions(this.sessionOption as WSManSessionOptions); + options = new WSManSessionOptions(this.SessionOption as WSManSessionOptions); } else { - options = new DComSessionOptions(this.sessionOption as DComSessionOptions); + options = new DComSessionOptions(this.SessionOption as DComSessionOptions); } } @@ -319,7 +274,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr } } - if (this.authenticationSet || (this.credential != null)) + if (this.authenticationSet || (this.Credential != null)) { PasswordAuthenticationMechanism authentication = this.authenticationSet ? this.Authentication : PasswordAuthenticationMechanism.Default; if (this.authenticationSet) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index ed80787e06f..063b477e2e7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -416,28 +416,14 @@ public ProtocolType Protocol /// Specifies the UI Culture to use. i.e. en-us, ar-sa. /// [Parameter(ValueFromPipelineByPropertyName = true)] - public CultureInfo UICulture - { - get { return uiculture; } - - set { uiculture = value; } - } - - private CultureInfo uiculture; + public CultureInfo UICulture { get; set; } /// /// The following is the definition of the input parameter "Culture". /// Specifies the culture to use. i.e. en-us, ar-sa. /// [Parameter(ValueFromPipelineByPropertyName = true)] - public CultureInfo Culture - { - get { return culture; } - - set { culture = value; } - } - - private CultureInfo culture; + public CultureInfo Culture { get; set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index 758296f7d56..159a75ed3ef 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -35,14 +35,7 @@ public class RegisterCimIndicationCommand : ObjectEventRegistrationBase /// /// [Parameter] - public string Namespace - { - get { return nameSpace; } - - set { nameSpace = value; } - } - - private string nameSpace; + public string Namespace { get; set; } /// /// The following is the definition of the input parameter "ClassName". @@ -122,14 +115,7 @@ public string QueryDialect /// [Alias(CimBaseCommand.AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "Session". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index 2e258c3bf3f..113a31ba93f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -142,14 +142,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". @@ -168,11 +161,11 @@ public UInt32 OperationTimeoutSec [Alias(CimBaseCommand.AliasCimInstance)] public CimInstance InputObject { - get { return cimInstance; } + get { return CimInstance; } set { - cimInstance = value; + CimInstance = value; base.SetParameter(value, nameCimInstance); } } @@ -180,12 +173,7 @@ public CimInstance InputObject /// /// Property for internal usage purpose. /// - internal CimInstance CimInstance - { - get { return cimInstance; } - } - - private CimInstance cimInstance; + internal CimInstance CimInstance { get; private set; } /// /// The following is the definition of the input parameter "Query". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index d5d6e831944..3e22eb9c6a5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -139,14 +139,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec - { - get { return operationTimeout; } - - set { operationTimeout = value; } - } - - private UInt32 operationTimeout; + public UInt32 OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". @@ -165,11 +158,11 @@ public UInt32 OperationTimeoutSec [Alias(CimBaseCommand.AliasCimInstance)] public CimInstance InputObject { - get { return cimInstance; } + get { return CimInstance; } set { - cimInstance = value; + CimInstance = value; base.SetParameter(value, nameCimInstance); } } @@ -177,12 +170,7 @@ public CimInstance InputObject /// /// Property for internal usage purpose. /// - internal CimInstance CimInstance - { - get { return cimInstance; } - } - - private CimInstance cimInstance; + internal CimInstance CimInstance { get; private set; } /// /// The following is the definition of the input parameter "Query". @@ -277,20 +265,7 @@ public IDictionary Property /// [Parameter] [ValidateNotNull] - public SwitchParameter PassThru - { - get - { - return this.passThru; - } - - set - { - this.passThru = value; - } - } - - private SwitchParameter passThru; + public SwitchParameter PassThru { get; set; } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 4042f79f130..bab5c092894 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -138,31 +138,14 @@ internal static class DebugHelper /// /// Flag used to control generating log message into file. /// - private static bool generateLog = true; - - internal static bool GenerateLog - { - get { return generateLog; } - - set { generateLog = value; } - } + internal static bool GenerateLog { get; set; } = true; /// /// Whether the log been initialized. /// private static bool logInitialized = false; - /// - /// Flag used to control generating message into powershell. - /// - private static bool generateVerboseMessage = true; - - internal static bool GenerateVerboseMessage - { - get { return generateVerboseMessage; } - - set { generateVerboseMessage = value; } - } + internal static bool GenerateVerboseMessage { get; set; } = true; /// /// Flag used to control generating message into powershell. @@ -337,7 +320,7 @@ private static void WriteLogInternal(string message, int indent, int depth) } } - if (generateLog) + if (GenerateLog) { if (indent < 0) { From c7bdb24ff3160b69285202f30a079e4c589f26f4 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 24 Nov 2020 15:06:16 +0000 Subject: [PATCH 060/138] Mark local variable as const (#13217) RCS1118: Mark local variable as const https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/RCS1118.md --- .../CimInvokeCimMethod.cs | 2 +- .../CommonUtils.cs | 16 +++---- .../PdhHelper.cs | 4 +- .../commands/management/CIMHelper.cs | 4 +- .../commands/management/ComputerUnix.cs | 4 +- .../commands/utility/AddType.cs | 3 +- .../FormatAndOutput/OutGridView/TableView.cs | 2 +- .../FormatAndOutput/format-hex/Format-Hex.cs | 4 +- .../out-printer/PrinterLineOutput.cs | 6 +-- .../utility/ImplicitRemotingCommands.cs | 16 +++---- .../utility/ImportPowerShellDataFile.cs | 6 +-- .../commands/utility/UnblockFile.cs | 2 +- .../Common/WebRequestPSCmdlet.Common.cs | 2 +- .../WindowsTaskbarJumpList/TaskbarJumpList.cs | 4 +- .../host/msh/ConsoleControl.cs | 2 +- .../host/msh/ConsoleHost.cs | 4 +- .../msh/ConsoleHostUserInterfacePrompt.cs | 38 +++++++++++----- ...ConsoleHostUserInterfacePromptForChoice.cs | 2 +- .../host/msh/PendingProgress.cs | 4 +- .../Eventing/Reader/NativeWrapper.cs | 4 +- .../security/CertificateProvider.cs | 32 +++++++------- .../ConfigProvider.cs | 2 +- src/Microsoft.WSMan.Management/CredSSP.cs | 8 ++-- .../DscSupport/CimDSCParser.cs | 2 +- .../common/BaseOutputtingCommand.cs | 2 +- .../common/DisplayDatabase/XmlLoaderBase.cs | 4 +- .../common/FormatViewGenerator_Table.cs | 2 +- .../common/FormatViewManager.cs | 2 +- .../PseudoParameterBinder.cs | 3 +- .../engine/EnumMinimumDisambiguation.cs | 4 +- .../engine/EventManager.cs | 4 +- .../ExperimentalFeature.cs | 6 +-- .../engine/Modules/ModuleCmdletBase.cs | 2 +- .../engine/Modules/ModuleIntrinsics.cs | 4 +- .../engine/Modules/RemoteDiscoveryHelper.cs | 4 +- .../engine/MshCommandRuntime.cs | 9 +++- .../engine/SessionStateContainer.cs | 8 ++-- .../engine/debugger/debugger.cs | 4 +- .../hostifaces/InternalHostUserInterface.cs | 4 +- .../engine/parser/TypeInferenceVisitor.cs | 2 +- .../remoting/client/remoterunspaceinfo.cs | 4 +- .../remoting/commands/CustomShellCommands.cs | 2 +- .../remoting/commands/DisconnectPSSession.cs | 2 +- .../commands/NewPSSessionConfigurationFile.cs | 4 +- .../remoting/commands/PushRunspaceCommand.cs | 43 +++++++++---------- .../remoting/commands/remotingcommandutil.cs | 2 +- .../remoting/common/RemoteSessionNamedPipe.cs | 17 +++----- .../remoting/common/RunspaceConnectionInfo.cs | 24 ++++------- .../common/WireDataFormat/EncodeAndDecode.cs | 21 ++++----- .../engine/remoting/common/fragmentor.cs | 8 ++-- .../remoting/fanin/PriorityCollection.cs | 4 +- .../remoting/server/ServerMethodExecutor.cs | 2 +- .../server/ServerRunspacePoolDriver.cs | 4 +- .../remoting/server/serverremotesession.cs | 2 +- .../engine/runtime/ScriptBlockToPowerShell.cs | 3 +- .../help/CommandHelpProvider.cs | 2 +- .../help/HelpCommands.cs | 2 +- .../help/HelpCommentsParser.cs | 2 +- .../help/PSClassHelpProvider.cs | 9 +--- .../help/UpdatableHelpCommandBase.cs | 6 +-- .../help/UpdatableHelpSystem.cs | 22 +++++----- .../namespaces/FileSystemProvider.cs | 28 ++++++------ .../namespaces/RegistryProvider.cs | 25 +++++------ .../security/CatalogHelper.cs | 4 +- .../utils/IObjectWriter.cs | 2 +- src/powershell/Program.cs | 4 +- test/xUnit/csharp/test_NamedPipe.cs | 2 +- test/xUnit/csharp/test_Utils.cs | 4 +- 68 files changed, 244 insertions(+), 247 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index caac54d654f..c90e7800c2d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -357,7 +357,7 @@ private CimMethodParametersCollection CreateParametersCollection( { string parameterName = enumerator.Key.ToString(); - CimFlags parameterFlags = CimFlags.In; + const CimFlags parameterFlags = CimFlags.In; object parameterValue = GetBaseObject(enumerator.Value); DebugHelper.WriteLog(@"Create parameter name= {0}, value= {1}, flags= {2}.", 4, diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index cffc347c38f..fb788b4d26c 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -55,7 +55,6 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou try { - uint dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE; uint LANGID = (uint)GetUserDefaultLangID(); uint langError = (uint)Marshal.GetLastWin32Error(); if (langError != 0) @@ -64,13 +63,14 @@ public static uint FormatMessageFromModule(uint lastError, string moduleName, ou } StringBuilder outStringBuilder = new(1024); - uint nChars = FormatMessage(dwFormatFlags, - moduleHandle, - lastError, - LANGID, - outStringBuilder, - (uint)outStringBuilder.Capacity, - IntPtr.Zero); + uint nChars = FormatMessage( + dwFlags: FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE, + lpSource: moduleHandle, + dwMessageId: lastError, + dwLanguageId: LANGID, + lpBuffer: outStringBuilder, + nSize: (uint)outStringBuilder.Capacity, + Arguments: IntPtr.Zero); if (nChars == 0) { diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index bfc56e8b172..97eff22db0d 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1057,8 +1057,6 @@ public uint GetValidPaths(string machineName, ref StringCollection instances, ref StringCollection validPaths) { - uint res = PdhResults.PDH_CSTATUS_VALID_DATA; - PDH_COUNTER_PATH_ELEMENTS pathElts = new(); pathElts.MachineName = machineName; pathElts.ObjectName = objectName; @@ -1091,7 +1089,7 @@ public uint GetValidPaths(string machineName, } } - return res; + return PdhResults.PDH_CSTATUS_VALID_DATA; } public uint AddCounters(ref StringCollection validPaths, bool bFlushOldCounters) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index 559af13127b..b954e502ff8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -85,7 +85,7 @@ internal static string WqlQueryAll(string from) try { var type = typeof(T); - var binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; + const BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; T rv = new T(); using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName))) @@ -144,7 +144,7 @@ internal static string WqlQueryAll(string from) if (instances != null) { var type = typeof(T); - var binding = BindingFlags.Public | BindingFlags.Instance; + const BindingFlags binding = BindingFlags.Public | BindingFlags.Instance; foreach (var instance in instances) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index 425acabe7f4..fb01823790f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -154,14 +154,12 @@ protected override void StopProcessing() /// Run a command. /// protected void RunCommand(String command, String args) { - String cmd = string.Empty; - _process = new Process() { StartInfo = new ProcessStartInfo { FileName = "/sbin/shutdown", - Arguments = cmd, + Arguments = string.Empty, RedirectStandardOutput = false, UseShellExecute = false, CreateNoWindow = true, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 242e5b1c5c5..a2ffec58392 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -914,12 +914,11 @@ private CommandLineArguments ParseCompilerOption(IEnumerable args) { string sdkDirectory = s_defaultSdkDirectory; string baseDirectory = this.SessionState.Path.CurrentLocation.Path; - string additionalReferenceDirectories = null; switch (Language) { case Language.CSharp: - return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); + return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory); default: throw PSTraceSource.NewNotSupportedException(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 0c2481b8eee..0523e2e0c35 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -197,7 +197,7 @@ private static void FilterActiveAssociationList(List nMax) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index 3628a36fdff..4c7fd83ce73 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -486,7 +486,7 @@ private byte[] ConvertToBytes(object inputObject) /// Offset in the file. private void WriteHexadecimal(Span inputBytes, string path, long offset) { - var bytesPerObject = 16; + const int bytesPerObject = 16; for (int index = 0; index < inputBytes.Length; index += bytesPerObject) { var count = inputBytes.Length - index < bytesPerObject @@ -508,7 +508,7 @@ private void WriteHexadecimal(Span inputBytes, string path, long offset) /// private void WriteHexadecimal(Span inputBytes, long offset, string label) { - var bytesPerObject = 16; + const int bytesPerObject = 16; for (int index = 0; index < inputBytes.Length; index += bytesPerObject) { var count = inputBytes.Length - index < bytesPerObject diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index e218ac9d6dd..2b1aab06ae9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -188,9 +188,9 @@ private void VerifyFont(Graphics g) // we compute the length of two strings, one made of "large" characters // one made of "narrow" ones. If they are the same length, we assume that // the font is fixed pitch. - string large = "ABCDEF"; + const string large = "ABCDEF"; float wLarge = g.MeasureString(large, _printFont).Width / large.Length; - string narrow = ".;'}l|"; + const string narrow = ".;'}l|"; float wNarrow = g.MeasureString(narrow, _printFont).Width / narrow.Length; if (Math.Abs((float)(wLarge - wNarrow)) < 0.001F) @@ -230,7 +230,7 @@ private void pd_PrintPage(object sender, PrintPageEventArgs ev) // on the first page we have to initialize the metrics for LineOutput // work out the number of columns per page assuming fixed pitch font - string s = "ABCDEF"; + const string s = "ABCDEF"; float w = ev.Graphics.MeasureString(s, _printFont).Width / s.Length; float columnsPerPage = ev.MarginBounds.Width / w; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index d14ffbfc2e8..b32ed855e60 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -559,7 +559,7 @@ internal ErrorDetails GetErrorDetails(string errorId, params object[] args) private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() { - string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; + const string errorId = "ErrorNoCommandsImportedBecauseOfSkipping"; ErrorDetails details = this.GetErrorDetails(errorId); @@ -580,7 +580,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorMalformedDataFromRemoteCommand"; + const string errorId = "ErrorMalformedDataFromRemoteCommand"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -601,7 +601,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames throw PSTraceSource.NewArgumentNullException(nameof(commandNames)); } - string errorId = "ErrorCommandSkippedBecauseOfShadowing"; + const string errorId = "ErrorCommandSkippedBecauseOfShadowing"; ErrorDetails details = this.GetErrorDetails(errorId, commandNames); @@ -622,7 +622,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorSkippedNonRequestedCommand"; + const string errorId = "ErrorSkippedNonRequestedCommand"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -643,7 +643,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } - string errorId = "ErrorSkippedNonRequestedTypeDefinition"; + const string errorId = "ErrorSkippedNonRequestedTypeDefinition"; ErrorDetails details = this.GetErrorDetails(errorId, typeName); @@ -664,7 +664,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorSkippedUnsafeCommandName"; + const string errorId = "ErrorSkippedUnsafeCommandName"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); @@ -771,7 +771,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) throw PSTraceSource.NewArgumentNullException(nameof(aliasName)); } - string errorId = "ErrorCouldntResolveAlias"; + const string errorId = "ErrorCouldntResolveAlias"; ErrorDetails details = this.GetErrorDetails(errorId, aliasName); @@ -792,7 +792,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } - string errorId = "ErrorNoResultsFromRemoteEnd"; + const string errorId = "ErrorNoResultsFromRemoteEnd"; ErrorDetails details = this.GetErrorDetails(errorId, commandName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 694e82686be..9195e49052b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -78,8 +78,8 @@ protected override void ProcessRecord() private void WritePathNotFoundError(string path) { - var errorId = "PathNotFound"; - var errorCategory = ErrorCategory.InvalidArgument; + const string errorId = "PathNotFound"; + const ErrorCategory errorCategory = ErrorCategory.InvalidArgument; var errorMessage = string.Format(UtilityCommonStrings.PathDoesNotExist, path); var exception = new ArgumentException(errorMessage); var errorRecord = new ErrorRecord(exception, errorId, errorCategory, path); @@ -88,7 +88,7 @@ private void WritePathNotFoundError(string path) private void WriteInvalidDataFileError(string resolvedPath, string errorId) { - var errorCategory = ErrorCategory.InvalidData; + const ErrorCategory errorCategory = ErrorCategory.InvalidData; var errorMessage = string.Format(UtilityCommonStrings.CouldNotParseAsPowerShellDataFile, resolvedPath); var exception = new InvalidOperationException(errorMessage); var errorRecord = new ErrorRecord(exception, errorId, errorCategory, resolvedPath); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index ba5a8f8a532..78160785d98 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -199,7 +199,7 @@ private bool IsValidFileForUnblocking(string resolvedpath) #if UNIX private static bool IsBlocked(string path) { - uint valueSize = 1024; + const uint valueSize = 1024; IntPtr value = Marshal.AllocHGlobal((int)valueSize); try { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 2005d587b97..f540fa67636 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1831,7 +1831,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr // we only support the URL in angle brackets and `rel`, other attributes are ignored // user can still parse it themselves via the Headers property - string pattern = "<(?.*?)>;\\s*rel=(\"?)(?.*?)\\1[^\\w -.]?"; + const string pattern = "<(?.*?)>;\\s*rel=(\"?)(?.*?)\\1[^\\w -.]?"; IEnumerable links; if (response.Headers.TryGetValues("Link", out links)) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 5b7572c94b2..6ac50fa0e3e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -59,8 +59,8 @@ private static void CreateElevatedEntry(string title) // Check startupInfo first to know if the current shell is interactive and owns a window before proceeding // This check is fast (less than 1ms) and allows for quick-exit GetStartupInfo(out StartUpInfo startupInfo); - var STARTF_USESHOWWINDOW = 0x00000001; - var SW_HIDE = 0; + const uint STARTF_USESHOWWINDOW = 0x00000001; + const ushort SW_HIDE = 0; if (((startupInfo.dwFlags & STARTF_USESHOWWINDOW) == 1) && (startupInfo.wShowWindow != SW_HIDE)) { string cmdPath = Assembly.GetEntryAssembly().Location.Replace(".dll", ".exe"); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 448bcb5f586..c2458fabb5e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -2477,7 +2477,7 @@ internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle) internal static string GetConsoleWindowTitle() { const int MaxWindowTitleLength = 1024; - DWORD bufferSize = MaxWindowTitleLength; + const DWORD bufferSize = MaxWindowTitleLength; DWORD result; StringBuilder consoleTitle = new StringBuilder((int)bufferSize); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 55b3a04c3e6..8b0ee08f5aa 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1779,7 +1779,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, } else { - string shellId = "Microsoft.PowerShell"; + const string shellId = "Microsoft.PowerShell"; // If the system lockdown policy says "Enforce", do so. Do this after types / formatting, default functions, etc // are loaded so that they are trusted. (Validation of their signatures is done in F&O) @@ -2029,7 +2029,7 @@ internal static string EscapeSingleQuotes(string str) private void WriteErrorLine(string line) { - ConsoleColor fg = ConsoleColor.Red; + const ConsoleColor fg = ConsoleColor.Red; ConsoleColor bg = UI.RawUI.BackgroundColor; UI.WriteLine(fg, bg, line); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 89b9303b856..6d7caefec36 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -147,8 +147,6 @@ public override string fieldPrompt = null; fieldPrompt = desc.Name; - bool fieldEchoOnPrompt = true; - // FieldDescription.ParameterAssemblyFullName never returns null. But this is // defense in depth. if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) @@ -207,12 +205,22 @@ public override { fieldPromptList.Append( string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); - bool inputListEnd = false; + bool endListInput = false; object convertedObj = null; - string inputString = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message, - desc, fieldEchoOnPrompt, true, out inputListEnd, out cancelInput, out convertedObj); - - if (cancelInput || inputListEnd) + _ = PromptForSingleItem( + elementType, + fieldPromptList.ToString(), + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: true, + out endListInput, + out cancelInput, + out convertedObj); + + if (cancelInput || endListInput) { break; } @@ -243,10 +251,20 @@ public override fieldPrompt); // field is not a list object convertedObj = null; - bool dummy = false; - PromptForSingleItem(fieldType, printFieldPrompt, fieldPrompt, caption, message, desc, - fieldEchoOnPrompt, false, out dummy, out cancelInput, out convertedObj); + _ = PromptForSingleItem( + fieldType, + printFieldPrompt, + fieldPrompt, + caption, + message, + desc, + fieldEchoOnPrompt: true, + listInput: false, + endListInput: out _, + out cancelInput, + out convertedObj); + if (!cancelInput) { inputPSObject = PSObject.AsPSObject(convertedObj); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index a3711200971..da9d5689105 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -297,7 +297,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, int lineLenMax = RawUI.WindowSize.Width - 1; int lineLen = 0; - string choiceTemplate = "[{0}] {1} "; + const string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 1588efe6b0e..89901b18126 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -825,11 +825,9 @@ internal override { nodesCompressed = 0; - int age = 0; - while (true) { - ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, age, priorStyle); + ProgressNode node = FindOldestNodeOfGivenStyle(_topLevelNodes, oldestSoFar: 0, priorStyle); if (node == null) { // We've compressed every node of the prior style already. diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 2286b6465a5..720af780642 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -958,7 +958,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl IntPtr pointer = IntPtr.Zero; int bufferNeeded; int propCount; - UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; + const UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderEventValues; try { @@ -1124,7 +1124,7 @@ public static string EvtRenderBookmark(EventLogHandle eventHandle) IntPtr buffer = IntPtr.Zero; int bufferNeeded; int propCount; - UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; + const UnsafeNativeMethods.EvtRenderFlags flag = UnsafeNativeMethods.EvtRenderFlags.EvtRenderBookmark; try { diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 0bb8c049d03..fdbac1ca8d2 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -635,7 +635,7 @@ private static Regex CertPathRegex { if (s_certPathRegex == null) { - RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; + const RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled; s_certPathRegex = new Regex(certPathPattern, options); } } @@ -721,7 +721,7 @@ protected override void RemoveItem( string.Equals(pathElements[1], "ROOT", StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.UINotAllowed; - string errorId = "UINotAllowed"; + const string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); } @@ -746,7 +746,7 @@ protected override void RemoveItem( if (fUserContext) { string message = CertificateProviderStrings.CannotDeleteUserStore; - string errorId = "CannotDeleteUserStore"; + const string errorId = "CannotDeleteUserStore"; ThrowInvalidOperation(errorId, message); } @@ -756,7 +756,7 @@ protected override void RemoveItem( else // other container than a store { string message = CertificateProviderStrings.CannotRemoveContainer; - string errorId = "CannotRemoveContainer"; + const string errorId = "CannotRemoveContainer"; ThrowInvalidOperation(errorId, message); } } @@ -827,7 +827,7 @@ protected override void MoveItem( if (isContainer) { string message = CertificateProviderStrings.CannotMoveContainer; - string errorId = "CannotMoveContainer"; + const string errorId = "CannotMoveContainer"; ThrowInvalidOperation(errorId, message); } @@ -844,7 +844,7 @@ protected override void MoveItem( else { string message = CertificateProviderStrings.InvalidDestStore; - string errorId = "InvalidDestStore"; + const string errorId = "InvalidDestStore"; ThrowInvalidOperation(errorId, message); } } @@ -856,14 +856,14 @@ protected override void MoveItem( if (!string.Equals(pathElements[0], destElements[0], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveCrossContext; - string errorId = "CannotMoveCrossContext"; + const string errorId = "CannotMoveCrossContext"; ThrowInvalidOperation(errorId, message); } if (string.Equals(pathElements[1], destElements[1], StringComparison.OrdinalIgnoreCase)) { string message = CertificateProviderStrings.CannotMoveToSameStore; - string errorId = "CannotMoveToSameStore"; + const string errorId = "CannotMoveToSameStore"; ThrowInvalidOperation(errorId, message); } @@ -877,7 +877,7 @@ protected override void MoveItem( string.Equals(destElements[1], "ROOT", StringComparison.OrdinalIgnoreCase))) { string message = CertificateProviderStrings.UINotAllowed; - string errorId = "UINotAllowed"; + const string errorId = "UINotAllowed"; ThrowInvalidOperation(errorId, message); } } @@ -961,7 +961,7 @@ protected override void NewItem( if (pathElements.Length != 2) { string message = CertificateProviderStrings.CannotCreateItem; - string errorId = "CannotCreateItem"; + const string errorId = "CannotCreateItem"; ThrowInvalidOperation(errorId, message); } @@ -971,11 +971,11 @@ protected override void NewItem( if (fUserContext) { string message = CertificateProviderStrings.CannotCreateUserStore; - string errorId = "CannotCreateUserStore"; + const string errorId = "CannotCreateUserStore"; ThrowInvalidOperation(errorId, message); } - Security.NativeMethods.CertOpenStoreFlags StoreFlags = + const Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; @@ -1415,7 +1415,7 @@ protected override void InvokeDefaultAction(string path) { path = NormalizePath(path); string action = CertificateProviderStrings.Action_Invoke; - string certmgr = "certmgr.msc"; + const string certmgr = "certmgr.msc"; string certPath = System.IO.Path.Combine( System.Environment.ExpandEnvironmentVariables("%windir%"), "system32"); @@ -1773,7 +1773,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat certContext = store.GetNextCert(certContext); } // remove the cert store - Security.NativeMethods.CertOpenStoreFlags StoreFlags = + const Security.NativeMethods.CertOpenStoreFlags StoreFlags = Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | @@ -1794,7 +1794,7 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat CultureInfo.CurrentCulture, CertificateProviderStrings.RemoveStoreTemplate, storeName); - string errorId = "CannotRemoveSystemStore"; + const string errorId = "CannotRemoveSystemStore"; ThrowInvalidOperation(errorId, message); } } @@ -2828,7 +2828,7 @@ internal static bool CertContainsEku(X509Certificate2 cert, List 0) diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 60d8795ac54..cd5e6d3fc4d 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -227,7 +227,7 @@ private void DeleteUserDelegateSettings() GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; - string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { @@ -508,7 +508,7 @@ private void EnableClientSideSettings() return; } - string newxmlcontent = @"true"; + const string newxmlcontent = @"true"; try { XmlDocument xmldoc = new XmlDocument(); @@ -626,7 +626,7 @@ private void UpdateCurrentUserRegistrySettings() GPO.OpenLocalMachineGPO(1); KeyHandle = GPO.GetRegistryKey(2); RegistryKey rootKey = Registry.CurrentUser; - string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; + const string GPOpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy Objects"; RegistryKey GPOKey = rootKey.OpenSubKey(GPOpath, true); foreach (string keyname in GPOKey.GetSubKeyNames()) { @@ -827,7 +827,7 @@ protected override void BeginProcessing() } // The application name MUST be "wsman" as wsman got approval from security // folks who suggested to register the SPN with name "wsman". - string applicationname = "wsman"; + const string applicationname = "wsman"; string credsspResult = GetDelegateSettings(applicationname); if (string.IsNullOrEmpty(credsspResult)) { diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 98d9c2feb24..525717164a9 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -41,7 +41,7 @@ public static object ConvertCimInstanceToObject(Type targetType, CimInstance ins using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) { - string script = "param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } "; + const string script = "param($targetType,$moduleName) & (Microsoft.PowerShell.Core\\Get-Module $moduleName) { New-Object $targetType } "; powerShell.AddScript(script); powerShell.AddArgument(targetType); diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index e3ff3608b9d..48ab1307681 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -181,7 +181,7 @@ private FormatShape ActiveFormattingShape { // we assume that the format context // contains the information - FormatShape shape = FormatShape.Table; // default + const FormatShape shape = FormatShape.Table; // default FormatOutputContext foc = this.FormatContext; if (foc == null || foc.Data.shapeInfo == null) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 9c0fbc90b66..742f9936ea8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -378,7 +378,7 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) // we differ only in case: flag this as an ERROR for the time being // and accept the comparison - string fmtString = "XML tag differ in case only {0} {1}"; + const string fmtString = "XML tag differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, n.Name, s)); match = true; @@ -420,7 +420,7 @@ internal bool MatchAttributeName(XmlAttribute a, string s) // we differ only in case: flag this as an ERROR for the time being // and accept the comparison - string fmtString = "XML attribute differ in case only {0} {1}"; + const string fmtString = "XML attribute differ in case only {0} {1}"; ReportTrace(string.Format(CultureInfo.InvariantCulture, fmtString, a.Name, s)); return true; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index 7394589bb95..bfd3291dd46 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -137,7 +137,7 @@ private void FilterActiveAssociationList() // make sure we do not have too many properties // NOTE: this is an arbitrary number, chosen to be a sensitive default - int nMax = 10; + const int nMax = 10; if (activeAssociationList.Count > nMax) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index c158583e25b..0737e43476e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -234,7 +234,7 @@ private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string msg = null; bool foundValidViews = false; string formatTypeName = null; - string separator = ", "; + const string separator = ", "; StringBuilder validViewFormats = new StringBuilder(); if (so != null && so.BaseObject != null && diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index e5d456eb854..c86fc34cfaf 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -261,8 +261,7 @@ public static class StaticParameterBinder /// The StaticBindingResult that represents the binding. public static StaticBindingResult BindCommand(CommandAst commandAst) { - bool resolve = true; - return BindCommand(commandAst, resolve); + return BindCommand(commandAst, resolve: true); } /// diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 18332cc37c6..5c166c69a63 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -85,7 +85,7 @@ internal static string EnumDisambiguate(string text, Type enumType) } // No special cases match, throw error for multiple matches. StringBuilder matchListSB = new StringBuilder(namesWithMatchingPrefix[0]); - string separator = ", "; + const string separator = ", "; for (int i = 1; i < namesWithMatchingPrefix.Count; i++) { matchListSB.Append(separator); @@ -106,7 +106,7 @@ internal static string EnumDisambiguate(string text, Type enumType) internal static string EnumAllValues(Type enumType) { string[] names = Enum.GetNames(enumType); - string separator = ", "; + const string separator = ", "; StringBuilder returnValue = new StringBuilder(); if (names.Length != 0) { diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 578a832e34a..94fc57ea0d7 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -680,7 +680,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s } // Retrieve the event from the object - BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(eventName, bindingFlags); // If we can't find the event, throw an exception @@ -844,7 +844,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) Type sourceType = subscriber.SourceObject as Type ?? subscriber.SourceObject.GetType(); - BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; + const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.IgnoreCase; eventInfo = sourceType.GetEvent(subscriber.EventName, bindingFlags); if ((eventInfo != null) && (existingSubscriber != null)) diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 5d1451a3971..86ff0666e2c 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -345,14 +345,14 @@ internal static void ValidateArguments(string experimentName, ExperimentAction e { if (string.IsNullOrEmpty(experimentName)) { - string paramName = nameof(experimentName); + const string paramName = nameof(experimentName); throw PSTraceSource.NewArgumentNullException(paramName, Metadata.ArgumentNullOrEmpty, paramName); } if (experimentAction == ExperimentAction.None) { - string paramName = nameof(experimentAction); - string invalidMember = nameof(ExperimentAction.None); + const string paramName = nameof(experimentAction); + const string invalidMember = nameof(ExperimentAction.None); string validMembers = StringUtil.Format("{0}, {1}", ExperimentAction.Hide, ExperimentAction.Show); throw PSTraceSource.NewArgumentException(paramName, Metadata.InvalidEnumArgument, invalidMember, paramName, validMembers); } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 5e6b44b9ada..c132db5dfba 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -1141,7 +1141,7 @@ internal static Version GetMaximumVersion(string stringVersion) else { // If first conversion fails, try to convert * to maximum version - string maxRange = "999999999"; + const string maxRange = "999999999"; if (stringVersion[stringVersion.Length - 1] == '*') { stringVersion = stringVersion.Substring(0, stringVersion.Length - 1); diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 71f86332861..cd354719660 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -703,9 +703,9 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) } #if UNIX - StringComparison strcmp = StringComparison.Ordinal; + const StringComparison strcmp = StringComparison.Ordinal; #else - StringComparison strcmp = StringComparison.OrdinalIgnoreCase; + const StringComparison strcmp = StringComparison.OrdinalIgnoreCase; #endif // We must check modulePath (e.g. /path/to/module/module.psd1) against several possibilities: diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index b87a14c8f26..9ece4af620f 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -31,7 +31,7 @@ internal class RemoteDiscoveryHelper private static Collection RehydrateHashtableKeys(PSObject pso, string propertyName) { - var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | + const DeserializingTypeConverter.RehydrationFlags rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; Hashtable hashtable = DeserializingTypeConverter.GetPropertyValue(pso, propertyName, rehydrationFlags); if (hashtable == null) @@ -53,7 +53,7 @@ private static Collection RehydrateHashtableKeys(PSObject pso, string pr internal static PSModuleInfo RehydratePSModuleInfo(PSObject deserializedModuleInfo) { - var rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | + const DeserializingTypeConverter.RehydrationFlags rehydrationFlags = DeserializingTypeConverter.RehydrationFlags.NullValueOk | DeserializingTypeConverter.RehydrationFlags.MissingPropertyOk; string name = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Name", rehydrationFlags); string path = DeserializingTypeConverter.GetPropertyValue(deserializedModuleInfo, "Path", rehydrationFlags); diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index cc1b38d7d0d..92238db5e31 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1735,8 +1735,13 @@ public bool ShouldContinue(string query, string caption) { bool yesToAll = false; bool noToAll = false; - bool hasSecurityImpact = false; - return DoShouldContinue(query, caption, hasSecurityImpact, false, ref yesToAll, ref noToAll); + return DoShouldContinue( + query, + caption, + hasSecurityImpact: false, + supportsToAllOptions: false, + ref yesToAll, + ref noToAll); } /// diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index a2b6f3baffa..76bb2d54a6f 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -4790,9 +4790,8 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses if (languageMode.HasValue && (languageMode.Value == PSLanguageMode.ConstrainedLanguage || languageMode.Value == PSLanguageMode.NoLanguage)) { - var psRemoteUtilsName = CopyFileRemoteUtils.PSCopyRemoteUtilsName; ps.Runspace = session.Runspace; - ps.AddCommand("Get-Command").AddArgument(psRemoteUtilsName); + ps.AddCommand("Get-Command").AddArgument(CopyFileRemoteUtils.PSCopyRemoteUtilsName); var result = ps.Invoke(); if (result.Count == 0) @@ -4816,12 +4815,11 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses ps.Commands.Clear(); ps.Streams.ClearStreams(); - ps.AddCommand(psRemoteUtilsName); + ps.AddCommand(CopyFileRemoteUtils.PSCopyRemoteUtilsName); } else { - string remoteScript = CopyFileRemoteUtils.PSValidatePathDefinition; - ps.AddScript(remoteScript); + ps.AddScript(CopyFileRemoteUtils.PSValidatePathDefinition); } ps.AddParameter("pathToValidate", path); diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 331629f086e..d015cd3e45f 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -4451,13 +4451,13 @@ protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection]: [RunspaceName]: PS C:\> string computerName = _runspace.ConnectionInfo?.ComputerName; - string processPartPattern = "{0}[{1}:{2}]:{3}"; + const string processPartPattern = "{0}[{1}:{2}]:{3}"; string processPart = StringUtil.Format(processPartPattern, @"""", DebuggerStrings.NestedRunspaceDebuggerPromptProcessName, @"$($PID)", @""""); - string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; + const string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """; string promptScript = "'[DBG]: '" + " + " + processPart + " + " + "' [" + CodeGeneration.EscapeSingleQuotedStringContent(_runspace.Name) + "]: '" + " + " + locationPart; // Get the command prompt from the wrapped debugger. diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 6b6a099e5c3..dcfe06245af 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -912,7 +912,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); - char newLine = '\n'; + const char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); @@ -928,7 +928,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); - string choiceTemplate = "[{0}] {1} "; + const string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 2543c5273d0..ce61c645233 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1217,7 +1217,7 @@ bool IsInPropertyArgument(object o) } var previousPipelineElement = GetPreviousPipelineCommand(commandAst); - var typeName = "Microsoft.PowerShell.Commands.GroupInfo"; + const string typeName = "Microsoft.PowerShell.Commands.GroupInfo"; var members = new List(); foreach (var prevType in InferTypes(previousPipelineElement)) { diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs index ea90e87390b..1fa03edf25b 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs @@ -208,7 +208,7 @@ public Runspace Runspace public override string ToString() { // PSSession is a PowerShell type name and so should not be localized. - string formatString = "[PSSession]{0}"; + const string formatString = "[PSSession]{0}"; return StringUtil.Format(formatString, Name); } @@ -349,7 +349,7 @@ private string GetTransportName() /// Display shell name. private static string GetDisplayShellName(string shell) { - string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; + const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = shell.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); return (index == 0) ? shell.Substring(shellPrefix.Length) : shell; diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index 7dd4209a782..c9202190221 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -798,7 +798,7 @@ private string ConstructPluginContent(out string srcConfigFilePath, out string d destConfigFilePath = null; StringBuilder initParameters = new StringBuilder(); - bool assemblyAndTypeTokensSet = false; + const bool assemblyAndTypeTokensSet = false; // DISC endpoint if (Path != null) diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 82459fdab92..b309fe142a7 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -346,7 +346,7 @@ private bool ValidateIdleTimeout(PSSession session) { int idleTimeout = session.Runspace.ConnectionInfo.IdleTimeout; int maxIdleTimeout = session.Runspace.ConnectionInfo.MaxIdleTimeout; - int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout; + const int minIdleTimeout = BaseTransportManager.MinimumIdleTimeout; if (idleTimeout != BaseTransportManager.UseServerDefaultIdleTimeout && (idleTimeout > maxIdleTimeout || idleTimeout < minIdleTimeout)) diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 02115bb2f47..f306246e289 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -857,7 +857,7 @@ protected override void ProcessRecord() { if (Full) { - string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; + const string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); } } @@ -1621,7 +1621,7 @@ protected override void ProcessRecord() // Modules to import if (_modulesToImport == null) { - string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; + const string exampleModulesToImport = "'MyCustomModule', @{ ModuleName = 'MyCustomModule'; ModuleVersion = '1.0.0.0'; GUID = '4d30d5f0-cb16-4898-812d-f20a6c596bdf' }"; result.Append(SessionConfigurationUtils.ConfigFragment(ConfigFileConstants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, exampleModulesToImport, streamWriter, true)); } else diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index 656b439f8a0..cbc5f82742b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -791,12 +791,13 @@ private RemoteRunspace GetRunspaceMatchingCondition( /// private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) { - Predicate condition = (PSSession info) => info.InstanceId == remoteRunspaceId; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, remoteRunspaceId); + return GetRunspaceMatchingCondition( + condition: info => info.InstanceId == remoteRunspaceId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedRunspaceId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId, + errorArgument: remoteRunspaceId); } /// @@ -804,12 +805,13 @@ private RemoteRunspace GetRunspaceMatchingRunspaceId(Guid remoteRunspaceId) /// private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) { - Predicate condition = (PSSession info) => info.Id == sessionId; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, sessionId); + return GetRunspaceMatchingCondition( + condition: info => info.Id == sessionId, + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedSessionId, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId, + errorArgument: sessionId); } /// @@ -817,16 +819,13 @@ private RemoteRunspace GetRunspaceMatchingSessionId(int sessionId) /// private RemoteRunspace GetRunspaceMatchingName(string name) { - Predicate condition = (PSSession info) => - { - // doing case-insensitive match for session name - return info.Name.Equals(name, StringComparison.OrdinalIgnoreCase); - }; - PSRemotingErrorId tooFew = PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName; - PSRemotingErrorId tooMany = PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - string tooFewResourceString = RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName; - string tooManyResourceString = RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName; - return GetRunspaceMatchingCondition(condition, tooFew, tooMany, tooFewResourceString, tooManyResourceString, name); + return GetRunspaceMatchingCondition( + condition: info => info.Name.Equals(name, StringComparison.OrdinalIgnoreCase), + tooFew: PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedName, + tooMany: PSRemotingErrorId.RemoteRunspaceHasMultipleMatchesForSpecifiedName, + tooFewResourceString: RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedName, + tooManyResourceString: RemotingErrorIdStrings.RemoteRunspaceHasMultipleMatchesForSpecifiedName, + errorArgument: name); } private Job FindJobForRunspace(Guid id) diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 2537abe6369..094dcedc6ad 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -87,7 +87,7 @@ internal static void CheckRemotingCmdletPrerequisites() return; #else bool notSupported = true; - string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; + const string WSManKeyPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WSMAN\\"; CheckHostRemotingPrerequisites(); diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 07d17ae3e51..6f520e0ac26 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -1291,9 +1291,6 @@ public ContainerSessionNamedPipeClient( /// protected override NamedPipeClientStream DoConnect(int timeout) { - // Create pipe flags. - uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; - // // WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly // attempt connection to pipe server until timeout expires. @@ -1306,13 +1303,13 @@ protected override NamedPipeClientStream DoConnect(int timeout) { // Get handle to pipe. pipeHandle = NamedPipeNative.CreateFile( - _pipeName, - NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - 0, - IntPtr.Zero, - NamedPipeNative.OPEN_EXISTING, - pipeFlags, - IntPtr.Zero); + lpFileName: _pipeName, + dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, + dwShareMode: 0, + SecurityAttributes: IntPtr.Zero, + dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, + dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, + hTemplateFile: IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (pipeHandle.IsInvalid) diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index e577ba67187..9debc89ce76 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -2050,9 +2050,9 @@ internal int StartSSHProcess( { string filePath = string.Empty; #if UNIX - string sshCommand = "ssh"; + const string sshCommand = "ssh"; #else - string sshCommand = "ssh.exe"; + const string sshCommand = "ssh.exe"; #endif var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (context != null) @@ -2625,21 +2625,15 @@ private static Process CreateProcessWithRedirectedStd( private static SafePipeHandle GetNamedPipeHandle(string pipeName) { - // Create pipe flags for asynchronous pipes. - uint pipeFlags = NamedPipeNative.FILE_FLAG_OVERLAPPED; - - // We want an inheritable handle. - PlatformInvokes.SECURITY_ATTRIBUTES securityAttributes = new PlatformInvokes.SECURITY_ATTRIBUTES(); - // Get handle to pipe. var fileHandle = PlatformInvokes.CreateFileW( - pipeName, - NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - 0, - securityAttributes, - NamedPipeNative.OPEN_EXISTING, - pipeFlags, - IntPtr.Zero); + lpFileName: pipeName, + dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, + dwShareMode: 0, + lpSecurityAttributes: new PlatformInvokes.SECURITY_ATTRIBUTES(), // Create an inheritable handle. + dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, + dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, // Open in asynchronous mode. + hTemplateFile: IntPtr.Zero); int lastError = Marshal.GetLastWin32Error(); if (fileHandle == PlatformInvokes.INVALID_HANDLE_VALUE) diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index febb87721cc..03a3cd51a87 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1196,10 +1196,10 @@ internal static RemoteDataObject GenerateRunspacePoolStateInfo( // Add Reason property if (stateInfo.Reason != null) { - // If Reason is of not type IContainsErrorRecord, a new ErrorRecord is - // created using this errorId - string errorId = "RemoteRunspaceStateInfoReason"; - PSNoteProperty exceptionProperty = GetExceptionProperty(stateInfo.Reason, errorId, ErrorCategory.NotSpecified); + PSNoteProperty exceptionProperty = GetExceptionProperty( + exception: stateInfo.Reason, + errorId: "RemoteRunspaceStateInfoReason", + category: ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1515,12 +1515,10 @@ internal static RemoteDataObject GeneratePowerShellStateInfo(PSInvocationStateIn // Add exception property if (stateInfo.Reason != null) { - // If Reason is of not type IContainsErrorRecord, - // a new ErrorRecord is created using this errorId - string errorId = "RemotePSInvocationStateInfoReason"; - PSNoteProperty exceptionProperty = - GetExceptionProperty(stateInfo.Reason, errorId, - ErrorCategory.NotSpecified); + PSNoteProperty exceptionProperty = GetExceptionProperty( + exception: stateInfo.Reason, + errorId: "RemotePSInvocationStateInfoReason", + category: ErrorCategory.NotSpecified); dataAsPSObject.Properties.Add(exceptionProperty); } @@ -1563,6 +1561,9 @@ internal static ErrorRecord GetErrorRecordFromException(Exception exception) /// /// Gets a Note Property for the exception. /// + /// + /// If is of not type IContainsErrorRecord, a new ErrorRecord is created. + /// /// /// ErrorId to use if exception is not of type IContainsErrorRecord. /// ErrorCategory to use if exception is not of type IContainsErrorRecord. diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index d0439613408..abcb32966f3 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -205,10 +205,10 @@ internal byte[] Blob /// internal byte[] GetBytes() { - int objectIdSize = 8; // number of bytes of long - int fragmentIdSize = 8; // number of bytes of long - int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl - int blobLengthSize = 4; // number of bytes of int + const int objectIdSize = 8; // number of bytes of long + const int fragmentIdSize = 8; // number of bytes of long + const int flagsSize = 1; // 1 byte for IsEndOfFrag and IsControl + const int blobLengthSize = 4; // number of bytes of int int totalLength = objectIdSize + fragmentIdSize + flagsSize + blobLengthSize + BlobLength; diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index d354574c37b..1bf8afd3dd1 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -163,8 +163,8 @@ Verify arrays and dataToBeSent objects before referencing. */ if (_dataSyncObjects != null && _dataToBeSent != null) { - int promptResponseIndex = (int)DataPriorityType.PromptResponse; - int defaultIndex = (int)DataPriorityType.Default; + const int promptResponseIndex = (int)DataPriorityType.PromptResponse; + const int defaultIndex = (int)DataPriorityType.Default; lock (_dataSyncObjects[promptResponseIndex]) { diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index d9b4d734900..d98239c3c33 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -92,7 +92,7 @@ internal void ExecuteVoidMethod(RemoteHostMethodId methodId, object[] parameters Dbg.Assert(parameters != null, "Expected parameters != null"); // Use void call ID so that the call is known to not have a return value. - long callId = ServerDispatchTable.VoidCallId; + const long callId = ServerDispatchTable.VoidCallId; RemoteHostCall remoteHostCall = new RemoteHostCall(callId, methodId, parameters); // Dispatch the call but don't wait for response since the return value is void. diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 0c6691532b8..b70f0cb4b4d 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -2066,7 +2066,7 @@ public override bool IsActive public override void SetDebuggerStepMode(bool enabled) { // Enable both the wrapper and wrapped debuggers for debugging before setting step mode. - DebugModes mode = DebugModes.LocalScript | DebugModes.RemoteScript; + const DebugModes mode = DebugModes.LocalScript | DebugModes.RemoteScript; base.SetDebugMode(mode); _wrappedDebugger.Value.SetDebugMode(mode); @@ -2712,7 +2712,7 @@ internal void StartPowerShellCommand( powershell.InvocationStateChanged += HandlePowerShellInvocationStateChanged; powershell.SetIsNested(false); - string script = @" + const string script = @" param ($Debugger, $Commands, $output) trap { throw $_ } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index c6091aceee6..5fdc13e0efc 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -206,7 +206,7 @@ internal static ServerRemoteSession CreateServerRemoteSession( throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings.NonExistentInitialSessionStateProvider", configurationProviderId); } - string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; + const string shellPrefix = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix; int index = configurationProviderId.IndexOf(shellPrefix, StringComparison.OrdinalIgnoreCase); senderInfo.ConfigurationName = (index == 0) ? configurationProviderId.Substring(shellPrefix.Length) : string.Empty; ServerRemoteSession result = new ServerRemoteSession( diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 4f649e19fc1..f5d2f51f698 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -547,7 +547,6 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) Diagnostics.Assert(commandAst.Redirections.Count == 1, "only 1 kind of redirection is supported"); Diagnostics.Assert(commandAst.Redirections[0] is MergingRedirectionAst, "unexpected redirection type"); - PipelineResultTypes toType = PipelineResultTypes.Output; PipelineResultTypes fromType; switch (commandAst.Redirections[0].FromStream) { @@ -581,7 +580,7 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) break; } - command.MergeMyResults(fromType, toType); + command.MergeMyResults(fromType, toResult: PipelineResultTypes.Output); } _powershell.AddCommand(command); diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index e6eafa8704f..5feb3c00189 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1250,7 +1250,7 @@ private static bool Match(string target, ICollection patterns) /// The result helpInfo objects after processing. internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest) { - HelpCategory categoriesHandled = (HelpCategory.Alias + const HelpCategory categoriesHandled = (HelpCategory.Alias | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand); if ((helpInfo.HelpCategory & categoriesHandled) != 0) diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index e67caa40db8..edf8d9e4355 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -516,7 +516,7 @@ private void ValidateAndThrowIfError(HelpCategory cat) } // categories that support -Parameter, -Role, -Functionality, -Component parameters - HelpCategory supportedCategories = + const HelpCategory supportedCategories = HelpCategory.Alias | HelpCategory.Cmdlet | HelpCategory.ExternalScript | HelpCategory.Filter | HelpCategory.Function | HelpCategory.ScriptCommand; diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index beda31bfd8e..21ac7b9e79d 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -496,7 +496,7 @@ private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, M private static void GetExampleSections(string content, out string prompt_str, out string code_str, out string remarks_str) { - string default_prompt_str = "PS > "; + const string default_prompt_str = "PS > "; var promptMatch = Regex.Match(content, "^.*?>"); prompt_str = promptMatch.Success ? promptMatch.Value : default_prompt_str; diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index ee65529a026..e4c74c6398a 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -80,11 +80,9 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool else patternList.Add(target); - bool useWildCards = true; - foreach (string pattern in patternList) { - PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards, _context); + PSClassSearcher searcher = new PSClassSearcher(pattern, useWildCards: true, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { @@ -108,10 +106,7 @@ internal override IEnumerable ExactMatchHelp(HelpRequest helpRequest) yield return null; } - string target = helpRequest.Target; - bool useWildCards = false; - - PSClassSearcher searcher = new PSClassSearcher(target, useWildCards, _context); + PSClassSearcher searcher = new PSClassSearcher(helpRequest.Target, useWildCards: false, _context); foreach (var helpInfo in GetHelpInfo(searcher)) { diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 9697ffb2f25..d9453b58c2e 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -299,9 +299,9 @@ private Dictionary, UpdatableHelpModuleInfo> GetModuleInf } } - // Match wildcards - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new[] { moduleNamePattern }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); foreach (KeyValuePair name in s_metadataCache) { diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index add71bd55b5..f7a476d5d07 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -513,6 +513,9 @@ private string ResolveUri(string baseUri, bool verbose) private const string HelpInfoXmlNamespace = "http://schemas.microsoft.com/powershell/help/2010/05"; private const string HelpInfoXmlValidationFailure = "HelpInfoXmlValidationFailure"; + private const string MamlXmlNamespace = "http://schemas.microsoft.com/maml/2004/10"; + private const string CommandXmlNamespace = "http://schemas.microsoft.com/maml/dev/command/2004/10"; + private const string DscResourceXmlNamespace = "http://schemas.microsoft.com/maml/dev/dscResource/2004/10"; /// /// Creates a HelpInfo object. @@ -586,8 +589,9 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { currentCulture }, wildcardOptions); + IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( + globPatterns: new[] { currentCulture }, + options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); for (int i = 0; i < updatableHelpItem.Length; i++) { @@ -1305,8 +1309,6 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de Debug.Assert(helpItemsNode != null, "helpItemsNode must not be null"); - string targetNamespace = "http://schemas.microsoft.com/maml/2004/10"; - foreach (XmlNode node in helpItemsNode.ChildNodes) { if (node.NodeType == XmlNodeType.Element) @@ -1315,11 +1317,11 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de { if (node.LocalName.Equals("para", StringComparison.OrdinalIgnoreCase)) { - if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/2004/10", StringComparison.OrdinalIgnoreCase)) + if (!node.NamespaceURI.Equals(MamlXmlNamespace, StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, - StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null); + StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, MamlXmlNamespace)), ErrorCategory.InvalidData, null, null); } else { @@ -1327,16 +1329,16 @@ private void ValidateAndCopyHelpContent(string sourcePath, Collection de } } - if (!node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/command/2004/10", StringComparison.OrdinalIgnoreCase) && - !node.NamespaceURI.Equals("http://schemas.microsoft.com/maml/dev/dscResource/2004/10", StringComparison.OrdinalIgnoreCase)) + if (!node.NamespaceURI.Equals(CommandXmlNamespace, StringComparison.OrdinalIgnoreCase) && + !node.NamespaceURI.Equals(DscResourceXmlNamespace, StringComparison.OrdinalIgnoreCase)) { throw new UpdatableHelpSystemException("HelpContentXmlValidationFailure", StringUtil.Format(HelpDisplayStrings.HelpContentXmlValidationFailure, - StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, targetNamespace)), ErrorCategory.InvalidData, null, null); + StringUtil.Format(HelpDisplayStrings.HelpContentMustBeInTargetNamespace, MamlXmlNamespace)), ErrorCategory.InvalidData, null, null); } } - CreateValidXmlDocument(node.OuterXml, targetNamespace, xsd, + CreateValidXmlDocument(node.OuterXml, MamlXmlNamespace, xsd, new ValidationEventHandler(HelpContentValidationHandler), false); } diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 8d77bc000d1..1b7822d634c 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -4195,7 +4195,7 @@ private void RemoveFunctionsPSCopyFileFromRemoteSession(System.Management.Automa return; } - string remoteScript = @" + const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyFromSessionHelper -ea SilentlyContinue -Force Microsoft.PowerShell.Management\Remove-Item function:PSCopyRemoteUtils -ea SilentlyContinue -Force "; @@ -4373,7 +4373,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf wStream = AlternateDataStreamUtilities.CreateFileStream(destinationFile.FullName, streamName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); } #endif - long fragmentSize = FILETRANSFERSIZE; + const long fragmentSize = FILETRANSFERSIZE; long copiedSoFar = 0; long currentIndex = 0; @@ -4506,7 +4506,7 @@ private void RemoveFunctionPSCopyFileToRemoteSession(System.Management.Automatio { if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } - string remoteScript = @" + const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyToSessionHelper -ea SilentlyContinue -Force Microsoft.PowerShell.Management\Remove-Item function:PSCopyRemoteUtils -ea SilentlyContinue -Force "; @@ -4624,7 +4624,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath WriteProgress(progress); // 4MB gives the best results without spiking the resources on the remote connection. - int fragmentSize = FILETRANSFERSIZE; + const int fragmentSize = FILETRANSFERSIZE; byte[] fragment = null; int iteration = 0; bool success = false; @@ -6771,7 +6771,7 @@ public IContentWriter GetContentWriter(string path) bool usingByteEncoding = false; bool streamTypeSpecified = false; Encoding encoding = ClrFacade.GetDefaultEncoding(); - FileMode filemode = FileMode.OpenOrCreate; + const FileMode filemode = FileMode.OpenOrCreate; string streamName = null; bool suppressNewline = false; @@ -8287,10 +8287,10 @@ internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) #if !UNIX private static bool WinIsSameFileSystemItem(string pathOne, string pathTwo) { - var access = FileAccess.Read; - var share = FileShare.Read; - var creation = FileMode.Open; - var attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const FileAccess access = FileAccess.Read; + const FileShare share = FileShare.Read; + const FileMode creation = FileMode.Open; + const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; using (var sfOne = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathOne, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) using (var sfTwo = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathTwo, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) @@ -8326,10 +8326,10 @@ internal static bool GetInodeData(string path, out System.ValueTuple inodeData) { - var access = FileAccess.Read; - var share = FileShare.Read; - var creation = FileMode.Open; - var attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const FileAccess access = FileAccess.Read; + const FileShare share = FileShare.Read; + const FileMode creation = FileMode.Open; + const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; using (var sf = AlternateDataStreamUtilities.NativeMethods.CreateFile(path, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) { @@ -8629,7 +8629,7 @@ internal static List GetStreams(string path) findStreamData.Name = findStreamData.Name.Substring(1); // And trailing :$DATA (as long as it's not the default data stream) - string dataStream = ":$DATA"; + const string dataStream = ":$DATA"; if (!string.Equals(findStreamData.Name, dataStream, StringComparison.OrdinalIgnoreCase)) { findStreamData.Name = findStreamData.Name.Replace(dataStream, string.Empty); diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 149a3711f7d..29e37a163e4 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -1819,7 +1819,7 @@ public void GetProperty( // as the property name when adding the note, as // PSObject does not allow an empty propertyName - notePropertyName = GetLocalizedDefaultToken(); + notePropertyName = LocalizedDefaultToken; } propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); @@ -2024,7 +2024,7 @@ public void ClearProperty( string propertyNameToAdd = valueName; if (string.IsNullOrEmpty(valueName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, defaultValue)); @@ -3056,7 +3056,7 @@ private void GetFilteredRegistryKeyProperties(string path, if (!string.IsNullOrEmpty(requestedValueName)) { - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } } @@ -3071,7 +3071,7 @@ private void GetFilteredRegistryKeyProperties(string path, // as the property name when adding the note, as // PSObject does not allow an empty propertyName - valueNameToMatch = GetLocalizedDefaultToken(); + valueNameToMatch = LocalizedDefaultToken; } hadAMatch = true; @@ -3783,7 +3783,7 @@ private void WriteWrappedPropertyObject(object value, string propertyName, strin string propertyNameToAdd = propertyName; if (string.IsNullOrEmpty(propertyName)) { - propertyNameToAdd = GetLocalizedDefaultToken(); + propertyNameToAdd = LocalizedDefaultToken; } result.Properties.Add(new PSNoteProperty(propertyNameToAdd, value)); @@ -4033,7 +4033,7 @@ private void WriteRegistryItemObject( if (string.IsNullOrEmpty(valueNames[index])) { // The first unnamed value becomes the default value - valueNames[index] = GetLocalizedDefaultToken(); + valueNames[index] = LocalizedDefaultToken; break; } } @@ -4108,16 +4108,13 @@ private bool ParseKind(string type, out RegistryValueKind kind) /// Gets the default value name token from the resource. /// In English that token is "(default)" without the quotes. /// + /// + /// This should not be localized as it will break scripts. + /// /// /// A string containing the default value name. /// - private string GetLocalizedDefaultToken() - { - // This shouldn't be localized as it will break scripts - - string defaultValueName = "(default)"; - return defaultValueName; - } + private string LocalizedDefaultToken => "(default)"; /// /// Converts an empty or null userEnteredPropertyName to the localized @@ -4140,7 +4137,7 @@ private string GetPropertyName(string userEnteredPropertyName) if (stringComparer.Compare( userEnteredPropertyName, - GetLocalizedDefaultToken(), + LocalizedDefaultToken, CompareOptions.IgnoreCase) == 0) { result = null; diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index f984976b33d..0c1c76b63e4 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -409,8 +409,8 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) _cmdlet.ThrowTerminatingError(errorRecord); } - DWORD GENERIC_READ = 0x80000000; - DWORD OPEN_EXISTING = 3; + const DWORD GENERIC_READ = 0x80000000; + const DWORD OPEN_EXISTING = 3; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // Open the file that is to be hashed for reading and get its handle diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index 226082be67e..49181e34584 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -160,7 +160,7 @@ public override void Flush() public override int Write(object obj) { - int numberOfObjectsWritten = 1; + const int numberOfObjectsWritten = 1; _count += numberOfObjectsWritten; return numberOfObjectsWritten; } diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index edac5b24f04..c885fa7fd2e 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -370,7 +370,7 @@ private static void CreatePwshInvocation( (string path, int quotedLength) invocationInfo) { // "exec " - string prefix = "exec "; + const string prefix = "exec "; prefix.AsSpan().CopyTo(strBuf); // The quoted path to pwsh, like "'/opt/microsoft/powershell/7/pwsh'" @@ -380,7 +380,7 @@ private static void CreatePwshInvocation( i += invocationInfo.quotedLength; // ' "$@"' the argument vector splat to pass pwsh arguments through - string suffix = " \"$@\""; + const string suffix = " \"$@\""; Span bufSuffix = strBuf.Slice(i); suffix.AsSpan().CopyTo(bufSuffix); } diff --git a/test/xUnit/csharp/test_NamedPipe.cs b/test/xUnit/csharp/test_NamedPipe.cs index 1ee50036fc0..1174799fd95 100644 --- a/test/xUnit/csharp/test_NamedPipe.cs +++ b/test/xUnit/csharp/test_NamedPipe.cs @@ -31,7 +31,7 @@ public void TestCustomPipeNameCreation() [Fact] public void TestCustomPipeNameCreationTooLongOnNonWindows() { - var longPipeName = "DoggoipsumwaggywagssmolborkingdoggowithalongsnootforpatsdoingmeafrightenporgoYapperporgolongwatershoobcloudsbigolpupperlengthboy"; + const string longPipeName = "DoggoipsumwaggywagssmolborkingdoggowithalongsnootforpatsdoingmeafrightenporgoYapperporgolongwatershoobcloudsbigolpupperlengthboy"; if (!Platform.IsWindows) { diff --git a/test/xUnit/csharp/test_Utils.cs b/test/xUnit/csharp/test_Utils.cs index b30c3ad18f8..ea45ce533d6 100644 --- a/test/xUnit/csharp/test_Utils.cs +++ b/test/xUnit/csharp/test_Utils.cs @@ -59,7 +59,7 @@ public static void TestHistoryStack() [Fact] public static void TestBoundedStack() { - int capacity = 20; + const int capacity = 20; var boundedStack = new BoundedStack(capacity); Assert.Throws(() => boundedStack.Pop()); @@ -116,7 +116,7 @@ public static void TestConvertToJsonWithEnum() public static void TestConvertToJsonWithoutCompress() { var context = new JsonObject.ConvertToJsonContext(maxDepth: 1, enumsAsStrings: true, compressOutput: false); - string expected = @"{ + const string expected = @"{ ""type"": ""Alias"" }"; Hashtable hash = new Hashtable { From 15e4e8a6af2f120bbd1eef8607131d878677c0ad Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 24 Nov 2020 20:30:42 +0000 Subject: [PATCH 061/138] Remove unnecessary finalizers (#14248) --- .../commands/management/ContentCommandBase.cs | 8 -------- .../FormatAndOutput/OutGridView/OutGridViewCommand.cs | 8 -------- .../commands/utility/ShowCommand/ShowCommand.cs | 8 -------- .../commands/utility/Tee-Object.cs | 8 -------- .../engine/CommandProcessorBase.cs | 8 -------- src/System.Management.Automation/engine/EventManager.cs | 8 -------- .../engine/lang/scriptblock.cs | 8 -------- src/System.Management.Automation/engine/pipeline.cs | 8 -------- 8 files changed, 64 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index b595c0195f9..583f12cc8ea 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -705,14 +705,6 @@ public void Dispose() GC.SuppressFinalize(this); } - /// - /// Finalizer. - /// - ~ContentCommandBase() - { - Dispose(false); - } #endregion IDisposable - } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index 96a06a71070..f7cc2028325 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -492,13 +492,5 @@ public void Dispose() this.Dispose(true); GC.SuppressFinalize(this); } - - /// - /// Finalizer. - /// - ~OutGridViewCommand() - { - Dispose(false); - } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index d9556753fb1..6306b7913f9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -63,14 +63,6 @@ public class ShowCommandCommand : PSCmdlet, IDisposable private object _commandViewModelObj; #endregion - /// - /// Finalizes an instance of the ShowCommandCommand class. - /// - ~ShowCommandCommand() - { - this.Dispose(false); - } - #region Input Cmdlet Parameter /// /// Gets or sets the command name. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs index ec5b859173e..78ca964d408 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -149,14 +149,6 @@ public void Dispose() GC.SuppressFinalize(this); } - /// - /// Finalizer. - /// - ~TeeObjectCommand() - { - Dispose(false); - } - #region private private CommandWrapper _commandWrapper; private bool _alreadyDisposed; diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index e422340991c..6ab07114652 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -957,14 +957,6 @@ private void Dispose(bool disposing) _disposed = true; } - /// - /// Finalizer for class CommandProcessorBase. - /// - ~CommandProcessorBase() - { - Dispose(false); - } - #endregion IDispose } } diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 94fc57ea0d7..8f13eecd023 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -1510,14 +1510,6 @@ protected virtual void OnForwardEvent(PSEventArgs e) ForwardEvent?.Invoke(this, e); } - /// - /// Destructor for the EventManager class. - /// - ~PSLocalEventManager() - { - Dispose(false); - } - /// /// Disposes the EventManager class. /// diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 05aaa6c56b9..765809be306 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1313,14 +1313,6 @@ private void Dispose(bool disposing) _disposed = true; } - /// - /// Finalizer for class SteppablePipeline. - /// - ~SteppablePipeline() - { - Dispose(false); - } - #endregion IDispose } diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 17fe22bcfd0..00ea51f71e4 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -91,14 +91,6 @@ private void Dispose(bool disposing) _disposed = true; } - /// - /// Finalizer for class PipelineProcessor. - /// - ~PipelineProcessor() - { - Dispose(false); - } - #endregion IDispose #region Execution Logging From bb4a0f4660d2b923377a048599792a8d08bde24d Mon Sep 17 00:00:00 2001 From: Dave Goldman <39909564+dgoldman-msft@users.noreply.github.com> Date: Wed, 25 Nov 2020 01:53:55 -0500 Subject: [PATCH 062/138] Fixing formatting in Reset-PWSHSystemPath.ps1 (#13689) --- tools/windows/Reset-PWSHSystemPath.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/windows/Reset-PWSHSystemPath.ps1 b/tools/windows/Reset-PWSHSystemPath.ps1 index a72a9b47b3c..4b98e714525 100644 --- a/tools/windows/Reset-PWSHSystemPath.ps1 +++ b/tools/windows/Reset-PWSHSystemPath.ps1 @@ -32,11 +32,13 @@ Removes ALL PowerShell paths from the Machine level path. Good for running right before upgrading PowerShell. + .EXAMPLE .\Reset-PWSHSystemPath.ps1 -PathScope Machine, User, Process Removes all paths but the very last one when sorted in ascending order. Processes all path scopes including current process. + .EXAMPLE .\Reset-PWSHSystemPath.ps1 -PathScope Machine, User, Process -RemoveAllOccurencs From 0d1ea73e599021c9ead87542646f7975bc04e5b9 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 25 Nov 2020 12:37:01 +0000 Subject: [PATCH 063/138] Enable IDE0074: Use coalesce compound assignment (#13396) * Autofix IDE0074: Use compound assignment --- .globalconfig | 2 +- .../cmdletization/SessionBasedWrapper.cs | 2 +- .../cmdletization/cim/cimWrapper.cs | 9 +++--- .../commands/utility/MatchString.cs | 2 +- .../host/msh/ConsoleHost.cs | 2 +- .../DscSupport/CimDSCParser.cs | 3 +- .../engine/Attributes.cs | 2 +- .../engine/CmdletInfo.cs | 3 +- .../engine/CmdletParameterBinderController.cs | 3 +- .../engine/CommandBase.cs | 4 +-- .../engine/CommandDiscovery.cs | 2 +- .../engine/CommandInfo.cs | 2 +- .../engine/EngineIntrinsics.cs | 2 +- .../engine/ErrorPackage.cs | 2 +- .../engine/ExecutionContext.cs | 4 +-- .../engine/ExternalScriptInfo.cs | 5 ++- .../engine/FunctionInfo.cs | 5 ++- .../engine/InformationRecord.cs | 4 +-- .../engine/InitialSessionState.cs | 2 +- .../engine/InvocationInfo.cs | 5 ++- .../engine/Modules/PSModuleInfo.cs | 12 +++---- .../engine/MshCmdlet.cs | 2 +- .../engine/MshCommandRuntime.cs | 8 ++--- .../engine/ParameterBinderBase.cs | 2 +- .../engine/PathInterfaces.cs | 2 +- .../engine/ReflectionParameterBinder.cs | 2 +- .../engine/ScriptInfo.cs | 5 ++- .../engine/SessionState.cs | 6 ++-- .../engine/SessionStatePublic.cs | 8 ++--- .../engine/SessionStateScope.cs | 5 ++- .../engine/ShellVariable.cs | 4 +-- .../engine/hostifaces/ConnectionBase.cs | 2 +- .../engine/hostifaces/FieldDescription.cs | 2 +- .../engine/interpreter/AddInstruction.cs | 32 +++++++++---------- .../interpreter/ControlFlowInstructions.cs | 6 ++-- .../engine/interpreter/DivInstruction.cs | 16 +++++----- .../engine/interpreter/EqualInstruction.cs | 26 +++++++-------- .../interpreter/GreaterThanInstruction.cs | 22 ++++++------- .../engine/interpreter/InstructionFactory.cs | 12 +++---- .../engine/interpreter/InstructionList.cs | 6 ++-- .../engine/interpreter/InterpretedFrame.cs | 4 +-- .../engine/interpreter/LessThanInstruction.cs | 22 ++++++------- .../engine/interpreter/MulInstruction.cs | 32 +++++++++---------- .../engine/interpreter/NotEqualInstruction.cs | 26 +++++++-------- .../engine/interpreter/SubInstruction.cs | 32 +++++++++---------- .../engine/parser/Parser.cs | 4 +-- .../engine/parser/tokenizer.cs | 18 ++++------- .../remoting/client/JobSourceAdapter.cs | 2 +- .../engine/remoting/client/remoterunspace.cs | 2 +- .../remoting/commands/DisconnectPSSession.cs | 2 +- .../engine/runtime/Operations/MiscOps.cs | 2 +- .../engine/serialization.cs | 8 ++--- .../logging/MshLog.cs | 3 +- .../utils/ExecutionExceptions.cs | 2 +- .../utils/ParameterBinderExceptions.cs | 2 +- .../utils/StructuredTraceSource.cs | 2 +- 56 files changed, 195 insertions(+), 213 deletions(-) diff --git a/.globalconfig b/.globalconfig index 095b150c301..98345b665e6 100644 --- a/.globalconfig +++ b/.globalconfig @@ -949,7 +949,7 @@ dotnet_diagnostic.IDE0072.severity = silent dotnet_diagnostic.IDE0073.severity = suggestion # IDE0074: UseCoalesceCompoundAssignment -dotnet_diagnostic.IDE0074.severity = silent +dotnet_diagnostic.IDE0074.severity = warning # IDE0075: SimplifyConditionalExpression dotnet_diagnostic.IDE0075.severity = silent diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 1091713367c..8db958d5f00 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -75,7 +75,7 @@ protected virtual void Dispose(bool disposing) [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] protected TSession[] Session { - get { return _session ?? (_session = new TSession[] { this.DefaultSession }); } + get { return _session ??= new TSession[] { this.DefaultSession }; } set { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs index bbe9332083f..f718ffe1dee 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -94,11 +94,10 @@ internal CimCmdletInvocationContext CmdletInvocationContext { get { - return _cmdletInvocationContext ?? - (_cmdletInvocationContext = new CimCmdletInvocationContext( - this.CmdletDefinitionContext, - this.Cmdlet, - this.GetDynamicNamespace())); + return _cmdletInvocationContext ??= new CimCmdletInvocationContext( + this.CmdletDefinitionContext, + this.Cmdlet, + this.GetDynamicNamespace()); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 3cd3418341a..83811fffef2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -142,7 +142,7 @@ public string Filename return s_inputStream; } - return _filename ?? (_filename = System.IO.Path.GetFileName(_path)); + return _filename ??= System.IO.Path.GetFileName(_path); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 8b0ee08f5aa..bc41b6ddb7f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -935,7 +935,7 @@ public override PSObject PrivateData get { if (ui == null) return null; - return _consoleColorProxy ?? (_consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui))); + return _consoleColorProxy ??= PSObject.AsPSObject(new ConsoleColorProxy(ui)); } } diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 525717164a9..b3f91da547f 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -3710,8 +3710,7 @@ private static ScriptBlock CimKeywordImplementationFunction get { // The scriptblock cache will handle mutual exclusion - return s_cimKeywordImplementationFunction ?? - (s_cimKeywordImplementationFunction = ScriptBlock.Create(CimKeywordImplementationFunctionText)); + return s_cimKeywordImplementationFunction ??= ScriptBlock.Create(CimKeywordImplementationFunctionText); } } diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 9262c2a17fc..d097cf039b4 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -507,7 +507,7 @@ public OutputTypeAttribute(params string[] type) [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ParameterSetName { - get => _parameterSetName ?? (_parameterSetName = new[] { ParameterAttribute.AllParameterSets }); + get => _parameterSetName ??= new[] { ParameterAttribute.AllParameterSets }; set => _parameterSetName = value; } diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index c10d8b48fad..05b7548f9fc 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -535,8 +535,7 @@ internal override CommandMetadata CommandMetadata { get { - return _cmdletMetadata ?? - (_cmdletMetadata = CommandMetadata.Get(this.Name, this.ImplementingType, Context)); + return _cmdletMetadata ??= CommandMetadata.Get(this.Name, this.ImplementingType, Context); } } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 679adf3eca5..452cd34f5b6 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -3927,8 +3927,7 @@ private HashSet BoundObsoleteParameterNames { get { - return _boundObsoleteParameterNames ?? - (_boundObsoleteParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase)); + return _boundObsoleteParameterNames ??= new HashSet(StringComparer.OrdinalIgnoreCase); } } diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index 995009de639..3f477895bb5 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -76,7 +76,7 @@ internal InternalCommand() /// The invocation object for this command. internal InvocationInfo MyInvocation { - get { return _myInvocation ?? (_myInvocation = new InvocationInfo(this)); } + get { return _myInvocation ??= new InvocationInfo(this); } } /// @@ -470,7 +470,7 @@ public ProviderIntrinsics InvokeProvider { using (PSTransactionManager.GetEngineProtectionScope()) { - return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); + return _invokeProvider ??= new ProviderIntrinsics(this); } } } diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 8749d5468ce..be855147037 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -1348,7 +1348,7 @@ internal LookupPathCollection GetLookupDirectoryPaths() } // Cache the new lookup paths - return _cachedLookupPaths ?? (_cachedLookupPaths = result); + return _cachedLookupPaths ??= result; } /// diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index d1afb8b3b12..a091f7c462d 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -583,7 +583,7 @@ public virtual Dictionary Parameters internal CommandMetadata ExternalCommandMetadata { - get { return _externalCommandMetadata ?? (_externalCommandMetadata = new CommandMetadata(this, true)); } + get { return _externalCommandMetadata ??= new CommandMetadata(this, true); } set { _externalCommandMetadata = value; } } diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index 9700a13f905..a492a5215fc 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -101,7 +101,7 @@ public SessionState SessionState /// public CommandInvocationIntrinsics InvokeCommand { - get { return _invokeCommand ?? (_invokeCommand = new CommandInvocationIntrinsics(_context)); } + get { return _invokeCommand ??= new CommandInvocationIntrinsics(_context); } } #endregion Public methods diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 948e9c5c0f8..6d7a6c8326a 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -1480,7 +1480,7 @@ internal void SetTargetObject(object target) /// for that ErrorCategory. /// /// never null - public ErrorCategoryInfo CategoryInfo { get => _categoryInfo ?? (_categoryInfo = new ErrorCategoryInfo(this)); } + public ErrorCategoryInfo CategoryInfo { get => _categoryInfo ??= new ErrorCategoryInfo(this); } private ErrorCategoryInfo _categoryInfo; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 740ae1ae1dd..3f8156e32a4 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -666,7 +666,7 @@ internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool def /// internal HelpSystem HelpSystem { - get { return _helpSystem ?? (_helpSystem = new HelpSystem(this)); } + get { return _helpSystem ??= new HelpSystem(this); } } private HelpSystem _helpSystem; @@ -745,7 +745,7 @@ internal InternalHost InternalHost /// internal EngineIntrinsics EngineIntrinsics { - get { return _engineIntrinsics ?? (_engineIntrinsics = new EngineIntrinsics(this)); } + get { return _engineIntrinsics ??= new EngineIntrinsics(this); } } private EngineIntrinsics _engineIntrinsics; diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 554b7ef23f4..03e17d74dd5 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -358,9 +358,8 @@ internal override CommandMetadata CommandMetadata { get { - return _commandMetadata ?? - (_commandMetadata = - new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); + return _commandMetadata ??= + new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } diff --git a/src/System.Management.Automation/engine/FunctionInfo.cs b/src/System.Management.Automation/engine/FunctionInfo.cs index 89b3793d9da..70ab80e8ca4 100644 --- a/src/System.Management.Automation/engine/FunctionInfo.cs +++ b/src/System.Management.Automation/engine/FunctionInfo.cs @@ -479,9 +479,8 @@ internal override CommandMetadata CommandMetadata { get { - return _commandMetadata ?? - (_commandMetadata = - new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); + return _commandMetadata ??= + new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 29d317e2c02..ad4aeeff5a9 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -81,7 +81,7 @@ internal InformationRecord(InformationRecord baseRecord) [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public List Tags { - get { return _tags ?? (_tags = new List()); } + get { return _tags ??= new List(); } internal set { _tags = value; } } @@ -120,7 +120,7 @@ public string User [DataMember] public string Computer { - get { return this._computerName ?? (this._computerName = PsUtils.GetHostName()); } + get { return this._computerName ??= PsUtils.GetHostName(); } set { this._computerName = value; } } diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 17ccb75163d..24fec940099 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -949,7 +949,7 @@ public override InitialSessionStateEntry Clone() /// public Collection Attributes { - get { return _attributes ?? (_attributes = new Collection()); } + get { return _attributes ??= new Collection(); } } private Collection _attributes; diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index cae261aec7d..1ae22542c63 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -201,8 +201,7 @@ public Dictionary BoundParameters { get { - return _boundParameters ?? - (_boundParameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _boundParameters ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } internal set { _boundParameters = value; } @@ -213,7 +212,7 @@ public Dictionary BoundParameters /// public List UnboundArguments { - get { return _unboundArguments ?? (_unboundArguments = new List()); } + get { return _unboundArguments ??= new List(); } internal set { _unboundArguments = value; } } diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index caa4a5a666f..9827a06b99a 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -299,8 +299,7 @@ public string ModuleBase { get { - return _moduleBase ?? - (_moduleBase = !string.IsNullOrEmpty(Path) ? IO.Path.GetDirectoryName(Path) : string.Empty); + return _moduleBase ??= !string.IsNullOrEmpty(Path) ? IO.Path.GetDirectoryName(Path) : string.Empty; } } @@ -922,8 +921,7 @@ public ReadOnlyCollection NestedModules { get { - return _readonlyNestedModules ?? - (_readonlyNestedModules = new ReadOnlyCollection(_nestedModules)); + return _readonlyNestedModules ??= new ReadOnlyCollection(_nestedModules); } } @@ -1014,8 +1012,7 @@ public ReadOnlyCollection RequiredModules { get { - return _readonlyRequiredModules ?? - (_readonlyRequiredModules = new ReadOnlyCollection(_requiredModules)); + return _readonlyRequiredModules ??= new ReadOnlyCollection(_requiredModules); } } @@ -1040,8 +1037,7 @@ internal ReadOnlyCollection RequiredModulesSpecification { get { - return _readonlyRequiredModulesSpecification ?? - (_readonlyRequiredModulesSpecification = new ReadOnlyCollection(_requiredModulesSpecification)); + return _readonlyRequiredModulesSpecification ??= new ReadOnlyCollection(_requiredModulesSpecification); } } diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index e6a1d2602b2..8c572f91826 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -999,7 +999,7 @@ public CommandInvocationIntrinsics InvokeCommand { using (PSTransactionManager.GetEngineProtectionScope()) { - return _invokeCommand ?? (_invokeCommand = new CommandInvocationIntrinsics(Context, this)); + return _invokeCommand ??= new CommandInvocationIntrinsics(Context, this); } } } diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 92238db5e31..39bc3b267d0 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -125,7 +125,7 @@ public override string ToString() /// The invocation object for this command. internal InvocationInfo MyInvocation { - get { return _myInvocation ?? (_myInvocation = _thisCommand.MyInvocation); } + get { return _myInvocation ??= _thisCommand.MyInvocation; } } /// @@ -2211,7 +2211,7 @@ internal void SetMergeFromRuntime(MshCommandRuntime fromRuntime) /// internal Pipe InputPipe { - get { return _inputPipe ?? (_inputPipe = new Pipe()); } + get { return _inputPipe ??= new Pipe(); } set { _inputPipe = value; } } @@ -2221,7 +2221,7 @@ internal Pipe InputPipe /// internal Pipe OutputPipe { - get { return _outputPipe ?? (_outputPipe = new Pipe()); } + get { return _outputPipe ??= new Pipe(); } set { _outputPipe = value; } } @@ -2244,7 +2244,7 @@ internal object[] GetResultsAsArray() /// internal Pipe ErrorOutputPipe { - get { return _errorOutputPipe ?? (_errorOutputPipe = new Pipe()); } + get { return _errorOutputPipe ??= new Pipe(); } set { _errorOutputPipe = value; } } diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 15cc6571896..ee7028c3865 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -172,7 +172,7 @@ internal object Target /// internal CommandLineParameters CommandLineParameters { - get { return _commandLineParameters ?? (_commandLineParameters = new CommandLineParameters()); } + get { return _commandLineParameters ??= new CommandLineParameters(); } // Setter is needed to pass into RuntimeParameterBinder instances set { _commandLineParameters = value; } diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 2cf562d5f85..9a604829295 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -1402,7 +1402,7 @@ private LocationGlobber PathResolver _sessionState != null, "The only constructor for this class should always set the sessionState field"); - return _pathResolver ?? (_pathResolver = _sessionState.ExecutionContext.LocationGlobber); + return _pathResolver ??= _sessionState.ExecutionContext.LocationGlobber; } } diff --git a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs index ee0562f5b89..6488dbcee90 100644 --- a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs +++ b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs @@ -124,7 +124,7 @@ internal override void BindParameter(string name, object value, CompiledCommandP try { var setter = parameterMetadata != null - ? (parameterMetadata.Setter ?? (parameterMetadata.Setter = GetSetter(Target.GetType(), name))) + ? (parameterMetadata.Setter ??= GetSetter(Target.GetType(), name)) : GetSetter(Target.GetType(), name); setter(Target, value); } diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index 9c6b097fc05..af91867c452 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -116,9 +116,8 @@ internal override CommandMetadata CommandMetadata { get { - return _commandMetadata ?? - (_commandMetadata = - new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); + return _commandMetadata ??= + new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 218fa6fd1c0..8efe2c94b65 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -143,7 +143,7 @@ internal void InitializeSessionStateInternalSpecialVariables(bool clearVariables /// internal LocationGlobber Globber { - get { return _globberPrivate ?? (_globberPrivate = ExecutionContext.LocationGlobber); } + get { return _globberPrivate ??= ExecutionContext.LocationGlobber; } } private LocationGlobber _globberPrivate; @@ -158,7 +158,7 @@ internal LocationGlobber Globber /// internal SessionState PublicSessionState { - get { return _publicSessionState ?? (_publicSessionState = new SessionState(this)); } + get { return _publicSessionState ??= new SessionState(this); } set { _publicSessionState = value; } } @@ -170,7 +170,7 @@ internal SessionState PublicSessionState /// internal ProviderIntrinsics InvokeProvider { - get { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } + get { return _invokeProvider ??= new ProviderIntrinsics(this); } } private ProviderIntrinsics _invokeProvider; diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index aa8932470ff..8f010cb65d4 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -88,7 +88,7 @@ public SessionState() /// public DriveManagementIntrinsics Drive { - get { return _drive ?? (_drive = new DriveManagementIntrinsics(_sessionState)); } + get { return _drive ??= new DriveManagementIntrinsics(_sessionState); } } /// @@ -96,7 +96,7 @@ public DriveManagementIntrinsics Drive /// public CmdletProviderManagementIntrinsics Provider { - get { return _provider ?? (_provider = new CmdletProviderManagementIntrinsics(_sessionState)); } + get { return _provider ??= new CmdletProviderManagementIntrinsics(_sessionState); } } /// @@ -104,7 +104,7 @@ public CmdletProviderManagementIntrinsics Provider /// public PathIntrinsics Path { - get { return _path ?? (_path = new PathIntrinsics(_sessionState)); } + get { return _path ??= new PathIntrinsics(_sessionState); } } /// @@ -112,7 +112,7 @@ public PathIntrinsics Path /// public PSVariableIntrinsics PSVariable { - get { return _variable ?? (_variable = new PSVariableIntrinsics(_sessionState)); } + get { return _variable ??= new PSVariableIntrinsics(_sessionState); } } /// diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 9cdc8b45cdb..500b70fc3c0 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1692,7 +1692,7 @@ private static FunctionInfo CreateFunction(string name, ScriptBlock function, Fu // performance degradation, so we use lazy initialization for all of them. private Dictionary GetDrives() { - return _drives ?? (_drives = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _drives ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } private Dictionary _drives; @@ -1704,8 +1704,7 @@ private Dictionary GetDrives() // performance degradation, so we use lazy initialization for all of them. private Dictionary GetAutomountedDrives() { - return _automountedDrives ?? - (_automountedDrives = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _automountedDrives ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } private Dictionary _automountedDrives; diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 1a4bdb359a7..f8a32fca917 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -387,7 +387,7 @@ internal void SetOptions(ScopedItemOptions newOptions, bool force) /// public Collection Attributes { - get { return _attributes ?? (_attributes = new PSVariableAttributeCollection(this)); } + get { return _attributes ??= new PSVariableAttributeCollection(this); } } private PSVariableAttributeCollection _attributes; @@ -840,7 +840,7 @@ public override object Value /// public override string Description { - get { return _description ?? (_description = SessionStateStrings.DollarNullDescription); } + get { return _description ??= SessionStateStrings.DollarNullDescription; } set { /* Do nothing */ } } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 48129196ad8..99151b7b0d4 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -1574,7 +1574,7 @@ internal ProviderIntrinsics InvokeProvider /// internal override SessionStateProxy GetSessionStateProxy() { - return _sessionStateProxy ?? (_sessionStateProxy = new SessionStateProxy(this)); + return _sessionStateProxy ??= new SessionStateProxy(this); } #endregion session state proxy diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index c9a2c9fe424..75987cc463a 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -291,7 +291,7 @@ public string Name Collection Attributes { - get { return metadata ?? (metadata = new Collection()); } + get { return metadata ??= new Collection(); } } /// diff --git a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs index 9858167aa74..2f7ada9dcfd 100644 --- a/src/System.Management.Automation/engine/interpreter/AddInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/AddInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new AddSingle()); - case TypeCode.Double: return s_double ?? (s_double = new AddDouble()); + case TypeCode.Int16: return s_int16 ??= new AddInt16(); + case TypeCode.Int32: return s_int32 ??= new AddInt32(); + case TypeCode.Int64: return s_int64 ??= new AddInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new AddUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new AddUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new AddUInt64(); + case TypeCode.Single: return s_single ??= new AddSingle(); + case TypeCode.Double: return s_double ??= new AddDouble(); default: throw Assert.Unreachable; @@ -263,14 +263,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new AddOvfInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new AddOvfInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new AddOvfInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new AddOvfUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new AddOvfUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new AddOvfUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new AddOvfSingle()); - case TypeCode.Double: return s_double ?? (s_double = new AddOvfDouble()); + case TypeCode.Int16: return s_int16 ??= new AddOvfInt16(); + case TypeCode.Int32: return s_int32 ??= new AddOvfInt32(); + case TypeCode.Int64: return s_int64 ??= new AddOvfInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new AddOvfUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new AddOvfUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new AddOvfUInt64(); + case TypeCode.Single: return s_single ??= new AddOvfSingle(); + case TypeCode.Double: return s_double ??= new AddOvfDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index 1b8ee9d93c9..0fddd203346 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -69,7 +69,7 @@ internal sealed class BranchFalseInstruction : OffsetInstruction public override Instruction[] Cache { - get { return s_cache ?? (s_cache = new Instruction[CacheSize]); } + get { return s_cache ??= new Instruction[CacheSize]; } } internal BranchFalseInstruction() @@ -97,7 +97,7 @@ internal sealed class BranchTrueInstruction : OffsetInstruction public override Instruction[] Cache { - get { return s_cache ?? (s_cache = new Instruction[CacheSize]); } + get { return s_cache ??= new Instruction[CacheSize]; } } internal BranchTrueInstruction() @@ -125,7 +125,7 @@ internal sealed class CoalescingBranchInstruction : OffsetInstruction public override Instruction[] Cache { - get { return s_cache ?? (s_cache = new Instruction[CacheSize]); } + get { return s_cache ??= new Instruction[CacheSize]; } } internal CoalescingBranchInstruction() diff --git a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs index f6cfb5b265f..11edd140945 100644 --- a/src/System.Management.Automation/engine/interpreter/DivInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DivInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new DivInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new DivInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new DivInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new DivUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new DivUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new DivUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new DivSingle()); - case TypeCode.Double: return s_double ?? (s_double = new DivDouble()); + case TypeCode.Int16: return s_int16 ??= new DivInt16(); + case TypeCode.Int32: return s_int32 ??= new DivInt32(); + case TypeCode.Int64: return s_int64 ??= new DivInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new DivUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new DivUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new DivUInt64(); + case TypeCode.Single: return s_single ??= new DivSingle(); + case TypeCode.Double: return s_double ??= new DivDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs index 639190e4d46..4db34761ce8 100644 --- a/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/EqualInstruction.cs @@ -154,25 +154,25 @@ public static Instruction Create(Type type) var typeToUse = type.IsEnum ? Enum.GetUnderlyingType(type) : type; switch (typeToUse.GetTypeCode()) { - case TypeCode.Boolean: return s_boolean ?? (s_boolean = new EqualBoolean()); - case TypeCode.SByte: return s_SByte ?? (s_SByte = new EqualSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new EqualByte()); - case TypeCode.Char: return s_char ?? (s_char = new EqualChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new EqualInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new EqualInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new EqualInt64()); + case TypeCode.Boolean: return s_boolean ??= new EqualBoolean(); + case TypeCode.SByte: return s_SByte ??= new EqualSByte(); + case TypeCode.Byte: return s_byte ??= new EqualByte(); + case TypeCode.Char: return s_char ??= new EqualChar(); + case TypeCode.Int16: return s_int16 ??= new EqualInt16(); + case TypeCode.Int32: return s_int32 ??= new EqualInt32(); + case TypeCode.Int64: return s_int64 ??= new EqualInt64(); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new EqualInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new EqualInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new EqualInt64()); + case TypeCode.UInt16: return s_UInt16 ??= new EqualInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new EqualInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new EqualInt64(); - case TypeCode.Single: return s_single ?? (s_single = new EqualSingle()); - case TypeCode.Double: return s_double ?? (s_double = new EqualDouble()); + case TypeCode.Single: return s_single ??= new EqualSingle(); + case TypeCode.Double: return s_double ??= new EqualDouble(); case TypeCode.Object: if (!type.IsValueType) { - return s_reference ?? (s_reference = new EqualReference()); + return s_reference ??= new EqualReference(); } // TODO: Nullable throw new NotImplementedException(); diff --git a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs index 9f46323308f..ccd5c3780f7 100644 --- a/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/GreaterThanInstruction.cs @@ -144,17 +144,17 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.SByte: return s_SByte ?? (s_SByte = new GreaterThanSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new GreaterThanByte()); - case TypeCode.Char: return s_char ?? (s_char = new GreaterThanChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new GreaterThanInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new GreaterThanInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new GreaterThanInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new GreaterThanUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new GreaterThanUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new GreaterThanUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new GreaterThanSingle()); - case TypeCode.Double: return s_double ?? (s_double = new GreaterThanDouble()); + case TypeCode.SByte: return s_SByte ??= new GreaterThanSByte(); + case TypeCode.Byte: return s_byte ??= new GreaterThanByte(); + case TypeCode.Char: return s_char ??= new GreaterThanChar(); + case TypeCode.Int16: return s_int16 ??= new GreaterThanInt16(); + case TypeCode.Int32: return s_int32 ??= new GreaterThanInt32(); + case TypeCode.Int64: return s_int64 ??= new GreaterThanInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new GreaterThanUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new GreaterThanUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new GreaterThanUInt64(); + case TypeCode.Single: return s_single ??= new GreaterThanSingle(); + case TypeCode.Double: return s_double ??= new GreaterThanDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs index e523a2dab5d..4a707201eb6 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs @@ -87,32 +87,32 @@ private InstructionFactory() { } protected internal override Instruction GetArrayItem() { - return _getArrayItem ?? (_getArrayItem = new GetArrayItemInstruction()); + return _getArrayItem ??= new GetArrayItemInstruction(); } protected internal override Instruction SetArrayItem() { - return _setArrayItem ?? (_setArrayItem = new SetArrayItemInstruction()); + return _setArrayItem ??= new SetArrayItemInstruction(); } protected internal override Instruction TypeIs() { - return _typeIs ?? (_typeIs = new TypeIsInstruction()); + return _typeIs ??= new TypeIsInstruction(); } protected internal override Instruction TypeAs() { - return _typeAs ?? (_typeAs = new TypeAsInstruction()); + return _typeAs ??= new TypeAsInstruction(); } protected internal override Instruction DefaultValue() { - return _defaultValue ?? (_defaultValue = new DefaultValueInstruction()); + return _defaultValue ??= new DefaultValueInstruction(); } protected internal override Instruction NewArray() { - return _newArray ?? (_newArray = new NewArrayInstruction()); + return _newArray ??= new NewArrayInstruction(); } protected internal override Instruction NewArrayInit(int elementCount) diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 818dfd4bf62..f4e7a454cfa 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -341,11 +341,11 @@ public void EmitLoad(bool value) { if ((bool)value) { - Emit(s_true ?? (s_true = new LoadObjectInstruction(value))); + Emit(s_true ??= new LoadObjectInstruction(value)); } else { - Emit(s_false ?? (s_false = new LoadObjectInstruction(value))); + Emit(s_false ??= new LoadObjectInstruction(value)); } } @@ -353,7 +353,7 @@ public void EmitLoad(object value, Type type) { if (value == null) { - Emit(s_null ?? (s_null = new LoadObjectInstruction(null))); + Emit(s_null ??= new LoadObjectInstruction(null)); return; } diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 431471d0619..4b084ba72a8 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -295,12 +295,12 @@ internal void PopPendingContinuation() internal static MethodInfo GotoMethod { - get { return s_goto ?? (s_goto = typeof(InterpretedFrame).GetMethod("Goto")); } + get { return s_goto ??= typeof(InterpretedFrame).GetMethod("Goto"); } } internal static MethodInfo VoidGotoMethod { - get { return s_voidGoto ?? (s_voidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); } + get { return s_voidGoto ??= typeof(InterpretedFrame).GetMethod("VoidGoto"); } } public int VoidGoto(int labelIndex) diff --git a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs index aaf632d0c77..2d6754ff2fd 100644 --- a/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/LessThanInstruction.cs @@ -144,17 +144,17 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.SByte: return s_SByte ?? (s_SByte = new LessThanSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new LessThanByte()); - case TypeCode.Char: return s_char ?? (s_char = new LessThanChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new LessThanInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new LessThanInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new LessThanInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new LessThanUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new LessThanUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new LessThanUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new LessThanSingle()); - case TypeCode.Double: return s_double ?? (s_double = new LessThanDouble()); + case TypeCode.SByte: return s_SByte ??= new LessThanSByte(); + case TypeCode.Byte: return s_byte ??= new LessThanByte(); + case TypeCode.Char: return s_char ??= new LessThanChar(); + case TypeCode.Int16: return s_int16 ??= new LessThanInt16(); + case TypeCode.Int32: return s_int32 ??= new LessThanInt32(); + case TypeCode.Int64: return s_int64 ??= new LessThanInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new LessThanUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new LessThanUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new LessThanUInt64(); + case TypeCode.Single: return s_single ??= new LessThanSingle(); + case TypeCode.Double: return s_double ??= new LessThanDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs index 486d2ebc751..3b150a7abbd 100644 --- a/src/System.Management.Automation/engine/interpreter/MulInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/MulInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new MulSingle()); - case TypeCode.Double: return s_double ?? (s_double = new MulDouble()); + case TypeCode.Int16: return s_int16 ??= new MulInt16(); + case TypeCode.Int32: return s_int32 ??= new MulInt32(); + case TypeCode.Int64: return s_int64 ??= new MulInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new MulUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new MulUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new MulUInt64(); + case TypeCode.Single: return s_single ??= new MulSingle(); + case TypeCode.Double: return s_double ??= new MulDouble(); default: throw Assert.Unreachable; @@ -263,14 +263,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new MulOvfInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new MulOvfInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new MulOvfInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new MulOvfUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new MulOvfUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new MulOvfUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new MulOvfSingle()); - case TypeCode.Double: return s_double ?? (s_double = new MulOvfDouble()); + case TypeCode.Int16: return s_int16 ??= new MulOvfInt16(); + case TypeCode.Int32: return s_int32 ??= new MulOvfInt32(); + case TypeCode.Int64: return s_int64 ??= new MulOvfInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new MulOvfUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new MulOvfUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new MulOvfUInt64(); + case TypeCode.Single: return s_single ??= new MulOvfSingle(); + case TypeCode.Double: return s_double ??= new MulOvfDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs index 440b5f8d6fa..79df1b9a84b 100644 --- a/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/NotEqualInstruction.cs @@ -154,25 +154,25 @@ public static Instruction Create(Type type) var typeToUse = type.IsEnum ? Enum.GetUnderlyingType(type) : type; switch (typeToUse.GetTypeCode()) { - case TypeCode.Boolean: return s_boolean ?? (s_boolean = new NotEqualBoolean()); - case TypeCode.SByte: return s_SByte ?? (s_SByte = new NotEqualSByte()); - case TypeCode.Byte: return s_byte ?? (s_byte = new NotEqualByte()); - case TypeCode.Char: return s_char ?? (s_char = new NotEqualChar()); - case TypeCode.Int16: return s_int16 ?? (s_int16 = new NotEqualInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new NotEqualInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new NotEqualInt64()); + case TypeCode.Boolean: return s_boolean ??= new NotEqualBoolean(); + case TypeCode.SByte: return s_SByte ??= new NotEqualSByte(); + case TypeCode.Byte: return s_byte ??= new NotEqualByte(); + case TypeCode.Char: return s_char ??= new NotEqualChar(); + case TypeCode.Int16: return s_int16 ??= new NotEqualInt16(); + case TypeCode.Int32: return s_int32 ??= new NotEqualInt32(); + case TypeCode.Int64: return s_int64 ??= new NotEqualInt64(); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new NotEqualInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new NotEqualInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new NotEqualInt64()); + case TypeCode.UInt16: return s_UInt16 ??= new NotEqualInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new NotEqualInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new NotEqualInt64(); - case TypeCode.Single: return s_single ?? (s_single = new NotEqualSingle()); - case TypeCode.Double: return s_double ?? (s_double = new NotEqualDouble()); + case TypeCode.Single: return s_single ??= new NotEqualSingle(); + case TypeCode.Double: return s_double ??= new NotEqualDouble(); case TypeCode.Object: if (!type.IsValueType) { - return s_reference ?? (s_reference = new NotEqualReference()); + return s_reference ??= new NotEqualReference(); } // TODO: Nullable throw new NotImplementedException(); diff --git a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs index c0874d47d89..486cd7f8933 100644 --- a/src/System.Management.Automation/engine/interpreter/SubInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/SubInstruction.cs @@ -130,14 +130,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new SubSingle()); - case TypeCode.Double: return s_double ?? (s_double = new SubDouble()); + case TypeCode.Int16: return s_int16 ??= new SubInt16(); + case TypeCode.Int32: return s_int32 ??= new SubInt32(); + case TypeCode.Int64: return s_int64 ??= new SubInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new SubUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new SubUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new SubUInt64(); + case TypeCode.Single: return s_single ??= new SubSingle(); + case TypeCode.Double: return s_double ??= new SubDouble(); default: throw Assert.Unreachable; @@ -263,14 +263,14 @@ public static Instruction Create(Type type) Debug.Assert(!type.IsEnum); switch (type.GetTypeCode()) { - case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubOvfInt16()); - case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubOvfInt32()); - case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubOvfInt64()); - case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubOvfUInt16()); - case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubOvfUInt32()); - case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubOvfUInt64()); - case TypeCode.Single: return s_single ?? (s_single = new SubOvfSingle()); - case TypeCode.Double: return s_double ?? (s_double = new SubOvfDouble()); + case TypeCode.Int16: return s_int16 ??= new SubOvfInt16(); + case TypeCode.Int32: return s_int32 ??= new SubOvfInt32(); + case TypeCode.Int64: return s_int64 ??= new SubOvfInt64(); + case TypeCode.UInt16: return s_UInt16 ??= new SubOvfUInt16(); + case TypeCode.UInt32: return s_UInt32 ??= new SubOvfUInt32(); + case TypeCode.UInt64: return s_UInt64 ??= new SubOvfUInt64(); + case TypeCode.Single: return s_single ??= new SubOvfSingle(); + case TypeCode.Double: return s_double ??= new SubOvfDouble(); default: throw Assert.Unreachable; diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index e781be44c30..eea0c4958c7 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -7939,7 +7939,7 @@ private static void AssertErrorIdCorrespondsToMsgString(string errorId, string e private static object[] arrayOfOneArg { - get { return t_arrayOfOneArg ?? (t_arrayOfOneArg = new object[1]); } + get { return t_arrayOfOneArg ??= new object[1]; } } [ThreadStatic] @@ -7947,7 +7947,7 @@ private static object[] arrayOfOneArg private static object[] arrayOfTwoArgs { - get { return t_arrayOfTwoArgs ?? (t_arrayOfTwoArgs = new object[2]); } + get { return t_arrayOfTwoArgs ??= new object[2]; } } [ThreadStatic] diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 159f697725a..5ab09c0a40f 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -77,8 +77,7 @@ private static Dictionary DynamicKeywords { get { - return t_dynamicKeywords ?? - (t_dynamicKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return t_dynamicKeywords ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -92,8 +91,7 @@ private static Stack> DynamicKeywordsStack { get { - return t_dynamicKeywordsStack ?? - (t_dynamicKeywordsStack = new Stack>()); + return t_dynamicKeywordsStack ??= new Stack>(); } } @@ -320,8 +318,7 @@ public Dictionary Properties { get { - return _properties ?? - (_properties = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _properties ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -334,8 +331,7 @@ public Dictionary Parameters { get { - return _parameters ?? - (_parameters = new Dictionary(StringComparer.OrdinalIgnoreCase)); + return _parameters ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -426,7 +422,7 @@ public class DynamicKeywordProperty /// public List Attributes { - get { return _attributes ?? (_attributes = new List()); } + get { return _attributes ??= new List(); } } private List _attributes; @@ -436,7 +432,7 @@ public List Attributes /// public List Values { - get { return _values ?? (_values = new List()); } + get { return _values ??= new List(); } } private List _values; @@ -446,7 +442,7 @@ public List Values /// public Dictionary ValueMap { - get { return _valueMap ?? (_valueMap = new Dictionary(StringComparer.OrdinalIgnoreCase)); } + get { return _valueMap ??= new Dictionary(StringComparer.OrdinalIgnoreCase); } } private Dictionary _valueMap; diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index de3d41d1956..f5a5022d705 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -238,7 +238,7 @@ public JobDefinition Definition /// public List Parameters { - get { return _parameters ?? (_parameters = new List()); } + get { return _parameters ??= new List(); } } /// diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 8d20e669871..7ddd657872e 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -1201,7 +1201,7 @@ internal void DoConcurrentCheckAndAddToRunningPipelines(RemotePipeline pipeline, /// internal override SessionStateProxy GetSessionStateProxy() { - return _sessionStateProxy ?? (_sessionStateProxy = new RemoteSessionStateProxy(this)); + return _sessionStateProxy ??= new RemoteSessionStateProxy(this); } private RemoteSessionStateProxy _sessionStateProxy = null; diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index b309fe142a7..0e2458daba0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -109,7 +109,7 @@ private PSSessionOption PSSessionOption { // no need to lock as the cmdlet parameters will not be assigned // from multiple threads. - return _sessionOption ?? (_sessionOption = new PSSessionOption()); + return _sessionOption ??= new PSSessionOption(); } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 62703cb36ec..0e84f3dab58 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1308,7 +1308,7 @@ internal ScriptBlock GetScriptBlock(ExecutionContext context, bool isFilter) Diagnostics.Assert(_scriptBlock == null || _scriptBlock.SessionStateInternal == null, "Cached script block should not hold on to session state"); - var result = (_scriptBlock ?? (_scriptBlock = new ScriptBlock(_ast, isFilter))).Clone(); + var result = (_scriptBlock ??= new ScriptBlock(_ast, isFilter)).Clone(); result.SessionStateInternal = context.EngineSessionState; return result; } diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 467da39dc4a..d5c81758b35 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -1893,9 +1893,8 @@ private Collection> ExtendedMembersCollection { get { - return _extendedMembersCollection ?? - (_extendedMembersCollection = - PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable)); + return _extendedMembersCollection ??= + PSObject.GetMemberCollection(PSMemberViewTypes.Extended, _typeTable); } } @@ -1905,8 +1904,7 @@ private Collection> AllPropertiesCollection { get { - return _allPropertiesCollection ?? - (_allPropertiesCollection = PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable)); + return _allPropertiesCollection ??= PSObject.GetPropertyCollection(PSMemberViewTypes.All, _typeTable); } } diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 32de4db2af8..02a8990bc69 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -469,7 +469,8 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, if (NeedToLogCommandLifecycleEvent(provider, executionContext)) { provider.LogCommandLifecycleEvent( - () => logContext ?? (logContext = GetLogContext(executionContext, invocationInfo)), commandState); + () => logContext ??= GetLogContext(executionContext, invocationInfo), + commandState); } } } diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 450797a7534..226a9cb8cdd 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -707,7 +707,7 @@ public override string Message { get { - return _message ?? (_message = (_wrapperException != null) ? _wrapperException.Message : string.Empty); + return _message ??= (_wrapperException != null) ? _wrapperException.Message : string.Empty; } } diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index baee153558d..841523f6bdb 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -384,7 +384,7 @@ public ParameterBindingException( /// public override string Message { - get { return _message ?? (_message = BuildMessage()); } + get { return _message ??= BuildMessage(); } } private string _message; diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index 84eb6fa40ef..47b6e1b4e1d 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -1443,7 +1443,7 @@ internal static int ThreadIndentLevel /// internal TraceSource TraceSource { - get { return _traceSource ?? (_traceSource = new MonadTraceSource(_name)); } + get { return _traceSource ??= new MonadTraceSource(_name); } } private TraceSource _traceSource; From d5b026437471635450f72d0e9d981a2757941d2d Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 25 Nov 2020 17:58:52 +0000 Subject: [PATCH 064/138] Use consistent spacing in xml documentation tags (#14231) --- .../CoreCLR/Stubs.cs | 4 +- .../cmdletization/SessionBasedWrapper.cs | 12 +++--- .../commands/utility/Join-String.cs | 6 +-- .../commands/utility/MatchString.cs | 6 +-- .../Common/WebRequestPSCmdlet.Common.cs | 24 +++++------ .../security/CertificateProvider.cs | 2 +- .../common/DisplayDatabase/typeDataManager.cs | 2 +- .../other/ciminstancetypeadapter.cs | 2 +- .../engine/SessionStateContainer.cs | 4 +- .../engine/SessionStateScope.cs | 6 +-- .../engine/SessionStateVariableAPIs.cs | 8 ++-- .../engine/parser/TypeInferenceVisitor.cs | 20 +++++----- .../engine/regex.cs | 2 +- .../engine/remoting/client/ThrottlingJob.cs | 10 ++--- .../remoting/server/serverremotesession.cs | 4 +- .../engine/serialization.cs | 2 +- .../namespaces/ContainerProviderBase.cs | 2 +- .../namespaces/CoreCommandContext.cs | 4 +- .../namespaces/FileSystemProvider.cs | 6 +-- .../namespaces/LocationGlobber.cs | 40 +++++++++---------- .../namespaces/RegistrySecurity.cs | 4 +- .../utils/tracing/EtwActivityReverter.cs | 2 +- .../utils/tracing/EtwEventCorrelator.cs | 20 +++++----- 23 files changed, 96 insertions(+), 96 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs index 9e320e610d0..5d57816c0e7 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs @@ -28,8 +28,8 @@ public enum PerformanceCounterCategoryType } /// - /// Specifies the formula used to calculate the - /// method for a instance. + /// Specifies the formula used to calculate the + /// method for a instance. /// /// 2 public enum PerformanceCounterType diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 8db958d5f00..79fc1dd0461 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -126,9 +126,9 @@ public SwitchParameter AsJob /// Doing so will interfere with ThrottleLimit functionality. /// /// - /// (and other methods returning job results) will block to support throttling and flow-control. + /// (and other methods returning job results) will block to support throttling and flow-control. /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing, - /// until calls from (and other methods returning job results) return. + /// until calls from (and other methods returning job results) return. /// /// internal abstract StartableJob CreateQueryJob(TSession session, QueryBuilder query); @@ -178,9 +178,9 @@ private StartableJob DoCreateQueryJob(TSession sessionForJob, QueryBuilder query /// Doing so will interfere with ThrottleLimit functionality. /// /// - /// (and other methods returning job results) will block to support throttling and flow-control. + /// (and other methods returning job results) will block to support throttling and flow-control. /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing, - /// until calls from (and other methods returning job results) return. + /// until calls from (and other methods returning job results) return. /// /// internal abstract StartableJob CreateInstanceMethodInvocationJob(TSession session, TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru); @@ -213,9 +213,9 @@ private StartableJob DoCreateInstanceMethodInvocationJob(TSession sessionForJob, /// Doing so will interfere with ThrottleLimit functionality. /// /// - /// (and other methods returning job results) will block to support throttling and flow-control. + /// (and other methods returning job results) will block to support throttling and flow-control. /// Implementations of Job instance returned from this method should make sure that implementation-specific flow-control mechanism pauses further processing, - /// until calls from (and other methods returning job results) return. + /// until calls from (and other methods returning job results) return. /// /// internal abstract StartableJob CreateStaticMethodInvocationJob(TSession session, MethodInvocationInfo methodInvocationInfo); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs index c1bcabef814..cab826691c9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -93,7 +93,7 @@ public string Separator [Parameter(ValueFromPipeline = true)] public PSObject[] InputObject { get; set; } - /// + /// protected override void BeginProcessing() { _quoteChar = SingleQuote ? '\'' : DoubleQuote ? '"' : char.MinValue; @@ -104,7 +104,7 @@ protected override void BeginProcessing() } } - /// + /// protected override void ProcessRecord() { if (InputObject != null) @@ -151,7 +151,7 @@ protected override void ProcessRecord() } } - /// + /// protected override void EndProcessing() { _outputBuilder.Append(OutputSuffix); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 83811fffef2..cb449a309e3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -425,7 +425,7 @@ private class CircularBuffer : ICollection /// Initializes a new instance of the class. /// /// The maximum capacity of the buffer. - /// If is negative. + /// If is negative. public CircularBuffer(int capacity) { if (capacity < 0) @@ -455,9 +455,9 @@ public CircularBuffer(int capacity) /// has been properly offset and wrapped. /// /// The index to wrap. - /// If is out of range. + /// If is out of range. /// - /// The actual index that + /// The actual index that /// maps to. /// private int WrapIndex(int zeroBasedIndex) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index f540fa67636..5cf9eff79c7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -1856,12 +1856,12 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr } /// - /// Adds content to a . Object type detection is used to determine if the value is string, File, or Collection. + /// Adds content to a . Object type detection is used to determine if the value is string, File, or Collection. /// /// The Field Name to use. /// The Field Value to use. - /// The > to update. - /// If true, collection types in will be enumerated. If false, collections will be treated as single value. + /// The > to update. + /// If true, collection types in will be enumerated. If false, collections will be treated as single value. private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { if (formData == null) @@ -1912,10 +1912,10 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF } /// - /// Gets a from the supplied field name and field value. Uses to convert the objects to strings. + /// Gets a from the supplied field name and field value. Uses to convert the objects to strings. /// - /// The Field Name to use for the - /// The Field Value to use for the + /// The Field Name to use for the + /// The Field Value to use for the private static StringContent GetMultipartStringContent(object fieldName, object fieldValue) { var contentDisposition = new ContentDispositionHeaderValue("form-data"); @@ -1929,10 +1929,10 @@ private static StringContent GetMultipartStringContent(object fieldName, object } /// - /// Gets a from the supplied field name and . Uses to convert the fieldname to a string. + /// Gets a from the supplied field name and . Uses to convert the fieldname to a string. /// - /// The Field Name to use for the - /// The to use for the + /// The Field Name to use for the + /// The to use for the private static StreamContent GetMultipartStreamContent(object fieldName, Stream stream) { var contentDisposition = new ContentDispositionHeaderValue("form-data"); @@ -1947,10 +1947,10 @@ private static StreamContent GetMultipartStreamContent(object fieldName, Stream } /// - /// Gets a from the supplied field name and file. Calls to create the and then sets the file name. + /// Gets a from the supplied field name and file. Calls to create the and then sets the file name. /// - /// The Field Name to use for the - /// The file to use for the + /// The Field Name to use for the + /// The file to use for the private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file) { var result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index fdbac1ca8d2..26b1668c6fb 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -3010,7 +3010,7 @@ public string LocationName /// /// Gets the location as a - /// + /// /// public StoreLocation Location { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index 51be05505e6..c42bd21adc7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -57,7 +57,7 @@ internal TypeInfoDataBaseManager() /// /// Host passed to . Can be null if no interactive questions should be asked. /// - /// + /// /// /// 1. FormatFile is not rooted. /// diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 7adda9937c9..c05ced76d20 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -135,7 +135,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property return null; } - /// + /// public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, MemberNamePredicate predicate) { if (predicate == null) diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index 76bb2d54a6f..feb80bbc73f 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -4038,7 +4038,7 @@ private bool HasChildItems( #region CopyItem /// - /// Copies an item at the specified path to an item at the . + /// Copies an item at the specified path to an item at the . /// /// /// The path(s) of the item(s) to copy. @@ -4106,7 +4106,7 @@ internal Collection CopyItem(string[] paths, } /// - /// Copies an item at the specified path to an item at the . + /// Copies an item at the specified path to an item at the . /// /// /// The path(s) of the item(s) to copy. diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 500b70fc3c0..6f0c4fbbec3 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -111,7 +111,7 @@ internal SessionStateScope ScriptScope /// the provider has already been notified. /// /// - /// If is null. + /// If is null. /// /// /// If a drive of the same name already exists in this scope. @@ -165,7 +165,7 @@ internal void NewDrive(PSDriveInfo newDrive) /// by the provider. /// /// - /// If is null. + /// If is null. /// internal void RemoveDrive(PSDriveInfo drive) { @@ -216,7 +216,7 @@ internal void RemoveAllDrives() /// exists in this scope or null if one does not exist. /// /// - /// If is null. + /// If is null. /// internal PSDriveInfo GetDrive(string name) { diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index f63a0a87c0f..bf3321b5b71 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -181,7 +181,7 @@ internal object GetVariableValue(string name, object defaultValue) /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. If any other drive specifier /// is found the lookup goes in the following order. @@ -252,7 +252,7 @@ internal object GetVariableValue( /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. If any other drive specifier /// is found the lookup goes in the following order. @@ -523,7 +523,7 @@ internal object GetVariableValueFromProvider( /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. /// - current scope @@ -575,7 +575,7 @@ internal PSVariable GetVariableItem( /// The variable if it was found or null if it was not. /// /// - /// The is first parsed to see if it contains a drive + /// The is first parsed to see if it contains a drive /// specifier or special scope. If a special scope is found ("LOCAL" or "GLOBAL") /// then only that scope is searched for the variable. /// - current scope diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index ce61c645233..ca4acbb0269 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -132,7 +132,7 @@ public TypeInferenceContext() : this(PowerShell.Create(RunspaceMode.CurrentRunsp } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// The powerShell instance passed need to have a non null Runspace. /// /// The instance of powershell to use for expression evaluation needed for type inference. @@ -2141,17 +2141,17 @@ private Type GetMostSpecificEnumeratedItemType(Type enumerableType) /// The interface to test. /// /// A reference to a value indicating whether a non-generic enumerable type has been - /// seen. If is a non-generic enumerable type this - /// value will be set to . + /// seen. If is a non-generic enumerable type this + /// value will be set to . /// /// - /// A reference to a value indicating whether has been - /// seen. If is a this - /// value will be set to . + /// A reference to a value indicating whether has been + /// seen. If is a this + /// value will be set to . /// /// - /// The value of if it can be used to infer a specific - /// enumerated type, otherwise . + /// The value of if it can be used to infer a specific + /// enumerated type, otherwise . /// private Type GetGenericCollectionLikeInterface( Type interfaceType, @@ -2250,8 +2250,8 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression } /// - /// Infers the types as if they were enumerated. For example, a - /// of type would be returned as . + /// Infers the types as if they were enumerated. For example, a + /// of type would be returned as . /// /// /// The potentially enumerable types to infer enumerated type from. diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 1ee6a3525ed..d8ef7a3a240 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -325,7 +325,7 @@ public static bool ContainsWildcardCharacters(string pattern) /// converted to their unescaped form. /// /// - /// If is null. + /// If is null. /// public static string Unescape(string pattern) { diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index 32952a4f89d..a00fdee17c2 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -191,8 +191,8 @@ internal enum ChildJobFlags /// /// Child job can call method - /// or - /// or + /// or + /// or /// method /// of the instance it belongs to. /// @@ -269,12 +269,12 @@ private int CountOfRunningOrReadyToRunChildJobs /// Passing 0 requests to turn off throttling (i.e. allow unlimited number of child jobs to run) /// /// - /// if this is used from a cmdlet invoked without -AsJob switch. - /// if this is used from a cmdlet invoked with -AsJob switch. + /// if this is used from a cmdlet invoked without -AsJob switch. + /// if this is used from a cmdlet invoked with -AsJob switch. /// /// If is , then /// memory can be managed more aggressively (for example ChildJobs can be discarded as soon as they complete) - /// because the is not exposed to the end user. + /// because the is not exposed to the end user. /// internal ThrottlingJob(string command, string jobName, string jobTypeName, int maximumConcurrentChildJobs, bool cmdletMode) : base(command, jobName) diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 5fdc13e0efc..7b08c674301 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -285,10 +285,10 @@ internal override RemotingDestination MySelf /// This parameter contains the remote data received from client. /// /// - /// If the parameter is null. + /// If the parameter is null. /// /// - /// If the parameter does not contain remote data. + /// If the parameter does not contain remote data. /// /// /// If the destination of the data is not for server. diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index d5c81758b35..30537cbc619 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -2826,7 +2826,7 @@ internal static string EncodeString(string s) /// /// This is the real workhorse that encodes strings. - /// See for more information. + /// See for more information. /// /// String to encode. /// IndexOfFirstEncodableCharacter. diff --git a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs index bd3e9957311..cc3e0ac83e2 100644 --- a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs @@ -999,7 +999,7 @@ protected virtual bool HasChildItems(string path) } /// - /// Copies an item at the specified path to an item at the . + /// Copies an item at the specified path to an item at the . /// /// /// The path of the item to copy. diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 1422e256a47..5446b6b71cb 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -331,13 +331,13 @@ internal CmdletProviderContext( /// /// A collection in which objects that are written using the WriteObject(s) - /// methods are accumulated if is false. + /// methods are accumulated if is false. /// private Collection _accumulatedObjects = new Collection(); /// /// A collection in which objects that are written using the WriteError - /// method are accumulated if is false. + /// method are accumulated if is false. /// private Collection _accumulatedErrorObjects = new Collection(); diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 1b7822d634c..a3acc0abb82 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2241,7 +2241,7 @@ protected override void RenameItem( /// Specify "directory" or "container" to create a directory. /// /// - /// If is "file" then this parameter becomes the content + /// If is "file" then this parameter becomes the content /// of the file to be created. /// /// @@ -6159,8 +6159,8 @@ private bool IsSameWindowsVolume(string source, string destination) /// /// The list of properties to get. Examples include "Attributes", "LastAccessTime," /// and other properties defined by - /// and - /// + /// and + /// /// public void GetProperty(string path, Collection providerSpecificPickList) { diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 4aaa3549d65..1282b999031 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -52,7 +52,7 @@ internal sealed class LocationGlobber /// The instance of session state on which this location globber acts. /// /// - /// If is null. + /// If is null. /// internal LocationGlobber(SessionState sessionState) { @@ -1666,7 +1666,7 @@ internal bool IsAbsolutePath(string path, out string driveName) /// The path with the glob characters unescaped. /// /// - /// If is null. + /// If is null. /// private static string RemoveGlobEscaping(string path) { @@ -1699,7 +1699,7 @@ private static string RemoveGlobEscaping(string path) /// false otherwise. /// /// - /// If is null. + /// If is null. /// /// /// The comparison is done using a case-insensitive comparison using the @@ -1763,7 +1763,7 @@ internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope) /// /// /// This out parameter returns the drive that was specified - /// by the . If is + /// by the . If is /// an absolute path this value may be something other than /// the current working drive. /// @@ -1789,7 +1789,7 @@ internal bool IsShellVirtualDrive(string driveName, out SessionStateScope scope) /// This is internal so that it can be called from SessionState /// /// - /// If is null. + /// If is null. /// /// /// If the refers to a drive that could not be found. @@ -2417,7 +2417,7 @@ private static string ParseProviderPath(string path, out string providerId) /// paths. Instead an appropriate path will be returned as if it did exist. /// /// - /// The provider that will be used to glob the . + /// The provider that will be used to glob the . /// /// /// The context under which the command is occurring. @@ -3273,27 +3273,27 @@ internal static string RemoveProviderQualifier(string path) /// /// Generates a collection of containers and/or leaves that are children of the containers /// in the currentDirs parameter and match the glob expression in the - /// parameter. + /// parameter. /// /// /// A collection of paths that should be searched for leaves that match the - /// expression. + /// expression. /// /// /// The drive the Msh path is relative to. /// /// /// A single element of a path that may or may not contain a glob expression. This parameter - /// is used to search the containers in for children that + /// is used to search the containers in for children that /// match the glob expression. /// /// - /// True if the is the last element to glob over. If false, we + /// True if the is the last element to glob over. If false, we /// need to get all container names from the provider even if they don't match the filter. /// /// /// The provider associated with the paths that are being passed in the - /// and parameters. + /// and parameters. /// The provider must derive from ContainerCmdletProvider or NavigationCmdletProvider /// in order to get globbing. /// @@ -3302,10 +3302,10 @@ internal static string RemoveProviderQualifier(string path) /// /// /// A collection of fully qualified namespace paths whose leaf element matches the - /// expression. + /// expression. /// /// - /// If or + /// If or /// is null. /// /// @@ -3892,24 +3892,24 @@ internal Collection ExpandGlobPath( /// /// Generates a collection of containers and/or leaves that are children of the containers /// in the currentDirs parameter and match the glob expression in the - /// parameter. + /// parameter. /// /// /// A collection of paths that should be searched for leaves that match the - /// expression. + /// expression. /// /// /// A single element of a path that may or may not contain a glob expression. This parameter - /// is used to search the containers in for children that + /// is used to search the containers in for children that /// match the glob expression. /// /// - /// True if the is the last element to glob over. If false, we + /// True if the is the last element to glob over. If false, we /// need to get all container names from the provider even if they don't match the filter. /// /// /// The provider associated with the paths that are being passed in the - /// and parameters. + /// and parameters. /// The provider must derive from ContainerCmdletProvider or NavigationCmdletProvider /// in order to get globbing. /// @@ -3918,10 +3918,10 @@ internal Collection ExpandGlobPath( /// /// /// A collection of fully qualified namespace paths whose leaf element matches the - /// expression. + /// expression. /// /// - /// If or + /// If or /// is null. /// /// diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index ad355ac6638..9308c50dddc 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -164,7 +164,7 @@ public void SetSecurityDescriptor( /// Specifies the parts of a security descriptor to create. /// /// - /// An instance of object. + /// An instance of object. /// /// and are not used by this method. public ObjectSecurity NewSecurityDescriptorFromPath( @@ -191,7 +191,7 @@ public ObjectSecurity NewSecurityDescriptorFromPath( /// Specifies the parts of a security descriptor to create. /// /// - /// An instance of object. + /// An instance of object. /// public ObjectSecurity NewSecurityDescriptorOfType( string type, diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs index a7a257ceb21..5154f637283 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs @@ -20,7 +20,7 @@ public interface IEtwActivityReverter : /// Reverts the ETW activity ID of the current thread to its original value. /// /// - /// Calling has the same effect as + /// Calling has the same effect as /// calling this method and is useful in the C# "using" syntax. /// void RevertCurrentActivityId(); diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index 4895a582223..ce2d05395cf 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -19,8 +19,8 @@ public interface IEtwEventCorrelator /// /// /// This method should only be used for advanced scenarios - /// or diagnostics. Prefer using - /// or instead. + /// or diagnostics. Prefer using + /// or instead. /// Guid CurrentActivityId { get; set; } @@ -29,7 +29,7 @@ public interface IEtwEventCorrelator /// the new activity with another activity. /// /// The ID of an existing activity to be correlated with the - /// new activity or if correlation is not desired. + /// new activity or if correlation is not desired. /// An object which can be used to revert the activity ID of the current thread once /// the new activity yields control of the current thread. IEtwActivityReverter StartActivity(Guid relatedActivityId); @@ -44,7 +44,7 @@ public interface IEtwEventCorrelator } /// - /// A simple implementation of . + /// A simple implementation of . /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Etw")] public class EtwEventCorrelator : @@ -54,11 +54,11 @@ public class EtwEventCorrelator : private readonly EventDescriptor _transferEvent; /// - /// Creates an . + /// Creates an . /// - /// The to use when logging transfer events + /// The to use when logging transfer events /// during activity correlation. - /// The to use when logging transfer events + /// The to use when logging transfer events /// during activity correlation. public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transferEvent) { @@ -72,7 +72,7 @@ public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transf } /// - /// Implements . + /// Implements . /// public Guid CurrentActivityId { @@ -88,7 +88,7 @@ public Guid CurrentActivityId } /// - /// Implements . + /// Implements . /// public IEtwActivityReverter StartActivity(Guid relatedActivityId) { @@ -105,7 +105,7 @@ public IEtwActivityReverter StartActivity(Guid relatedActivityId) } /// - /// Implements . + /// Implements . /// public IEtwActivityReverter StartActivity() { From 17b3375eea91d4647094778940969fdbfd21a8f3 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 26 Nov 2020 05:35:16 +0000 Subject: [PATCH 065/138] Fix IDE0090: Simplify new expression part 4.1 (#14255) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../FormatAndOutput/OutGridView/HeaderInfo.cs | 6 +++--- .../OutGridView/OutGridViewCommand.cs | 8 ++++---- .../FormatAndOutput/OutGridView/TableView.cs | 12 ++++++------ .../common/WriteFormatDataCommand.cs | 2 +- .../FormatAndOutput/format-hex/Format-Hex.cs | 14 +++++++------- .../FormatAndOutput/format-object/Format-Object.cs | 8 ++++---- .../FormatAndOutput/format-wide/Format-Wide.cs | 10 +++++----- .../utility/FormatAndOutput/out-file/Out-File.cs | 2 +- .../FormatAndOutput/out-printer/Out-Printer.cs | 2 +- .../out-printer/PrinterLineOutput.cs | 8 ++++---- .../FormatAndOutput/out-string/Out-String.cs | 6 +++--- 11 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs index c88cdd0bcb0..d811ce32303 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands { internal class HeaderInfo { - private readonly List _columns = new List(); + private readonly List _columns = new(); internal void AddColumn(ColumnInfo col) { @@ -18,7 +18,7 @@ internal void AddColumn(ColumnInfo col) internal PSObject AddColumnsToWindow(OutWindowProxy windowProxy, PSObject liveObject) { - PSObject staleObject = new PSObject(); + PSObject staleObject = new(); // Initiate arrays to be of the same size. int count = _columns.Count; @@ -47,7 +47,7 @@ internal PSObject AddColumnsToWindow(OutWindowProxy windowProxy, PSObject liveOb internal PSObject CreateStalePSObject(PSObject liveObject) { - PSObject staleObject = new PSObject(); + PSObject staleObject = new(); foreach (ColumnInfo column in _columns) { // Add a property to the stale PSObject. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index f7cc2028325..e606e58e9e4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -212,7 +212,7 @@ protected override void StopProcessing() /// PSObject to be converted to a string. internal string ConvertToString(PSObject liveObject) { - StringFormatError formatErrorObject = new StringFormatError(); + StringFormatError formatErrorObject = new(); string smartToString = PSObjectHelper.SmartToString(liveObject, _expressionFactory, InnerFormatShapeCommand.FormatEnumerationLimit(), @@ -265,7 +265,7 @@ baseObject is PSReference || baseObject is FormatInfoData || baseObject is PSObject) { - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( new FormatException(StringUtil.Format(FormatAndOut_out_gridview.DataNotQualifiedForGridView)), DataNotQualifiedForGridView, ErrorCategory.InvalidType, @@ -289,7 +289,7 @@ baseObject is FormatInfoData || Exception exception = _windowProxy.GetLastException(); if (exception != null) { - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( exception, "ManagementListInvocationException", ErrorCategory.OperationStopped, @@ -357,7 +357,7 @@ internal class NonscalarTypeHeader : GridHeader internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { // Prepare a table view. - TableView tableView = new TableView(); + TableView tableView = new(); tableView.Initialize(parentCmd._expressionFactory, parentCmd._typeInfoDataBase); // Request a view definition from the type database. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 0523e2e0c35..216d9121d54 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -25,7 +25,7 @@ internal void Initialize(PSPropertyExpressionFactory expressionFactory, _typeInfoDatabase = db; // Initialize Format Error Manager. - FormatErrorPolicy formatErrorPolicy = new FormatErrorPolicy(); + FormatErrorPolicy formatErrorPolicy = new(); formatErrorPolicy.ShowErrorsAsMessages = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsAsMessages; formatErrorPolicy.ShowErrorsInFormattedOutput = _typeInfoDatabase.defaultSettingsSection.formatErrorPolicy.ShowErrorsInFormattedOutput; @@ -35,7 +35,7 @@ internal void Initialize(PSPropertyExpressionFactory expressionFactory, internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBody, OutGridViewCommand parentCmdlet) { - HeaderInfo headerInfo = new HeaderInfo(); + HeaderInfo headerInfo = new(); // This verification is needed because the database returns "LastWriteTime" value for file system objects // as strings and it is used to detect this situation and use the actual field value. @@ -124,7 +124,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parentCmdlet) { - HeaderInfo headerInfo = new HeaderInfo(); + HeaderInfo headerInfo = new(); List activeAssociationList; // Get properties from the default property set of the object @@ -201,7 +201,7 @@ private static void FilterActiveAssociationList(List nMax) { - List tmp = new List(activeAssociationList); + List tmp = new(activeAssociationList); activeAssociationList.Clear(); for (int k = 0; k < nMax; k++) activeAssociationList.Add(tmp[k]); @@ -222,7 +222,7 @@ private List GetActiveTableRowDefinition(TableControlBod TableRowDefinition matchingRowDefinition = null; var typeNames = so.InternalTypeNames; - TypeMatch match = new TypeMatch(_expressionFactory, _typeInfoDatabase, typeNames); + TypeMatch match = new(_expressionFactory, _typeInfoDatabase, typeNames); foreach (TableRowDefinition x in tableBody.optionalDefinitionList) { @@ -268,7 +268,7 @@ private List GetActiveTableRowDefinition(TableControlBod } // we have an override, we need to compute the merge of the active cells - List activeRowItemDefinitionList = new List(); + List activeRowItemDefinitionList = new(); int col = 0; foreach (TableRowItemDefinition rowItem in matchingRowDefinition.rowItemDefinitionList) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs index 5f0db5dfe8a..3ccbe942829 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -74,7 +74,7 @@ public string LiteralPath private bool _isLiteralPath = false; - private readonly List _typeDefinitions = new List(); + private readonly List _typeDefinitions = new(); private bool _force; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index 4c7fd83ce73..091903f011a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -27,7 +27,7 @@ public sealed class FormatHex : PSCmdlet /// For cases where a homogenous collection of bytes or other items are directly piped in, we collect all the /// bytes in a List<byte> and then output the formatted result all at once in EndProcessing(). /// - private readonly List _inputBuffer = new List(); + private readonly List _inputBuffer = new(); /// /// Expect to group s by default. When receiving input that should not be grouped, @@ -153,12 +153,12 @@ protected override void EndProcessing() /// private List ResolvePaths(string[] path, bool literalPath) { - List pathsToProcess = new List(); + List pathsToProcess = new(); ProviderInfo provider = null; foreach (string currentPath in path) { - List newPaths = new List(); + List newPaths = new(); if (literalPath) { @@ -174,7 +174,7 @@ private List ResolvePaths(string[] path, bool literalPath) { if (!WildcardPattern.ContainsWildcardCharacters(currentPath)) { - ErrorRecord errorRecord = new ErrorRecord(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); + ErrorRecord errorRecord = new(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); WriteError(errorRecord); continue; } @@ -185,7 +185,7 @@ private List ResolvePaths(string[] path, bool literalPath) { // Write a non-terminating error message indicating that path specified is not supported. string errorMessage = StringUtil.Format(UtilityCommonStrings.FormatHexOnlySupportsFileSystemPaths, currentPath); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(errorMessage), "FormatHexOnlySupportsFileSystemPaths", ErrorCategory.InvalidArgument, @@ -293,7 +293,7 @@ private void ProcessString(string originalString) } } - private static readonly Random _idGenerator = new Random(); + private static readonly Random _idGenerator = new(); private static string GetGroupLabel(Type inputType) => string.Format("{0} ({1}) <{2:X8}>", inputType.Name, inputType.FullName, _idGenerator.Next()); @@ -370,7 +370,7 @@ private void ProcessInputObjects(PSObject inputObject) else { string errorMessage = StringUtil.Format(UtilityCommonStrings.FormatHexTypeNotSupported, obj.GetType()); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(errorMessage), "FormatHexTypeNotSupported", ErrorCategory.InvalidArgument, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs index b2052555622..9e064ba37db 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs @@ -58,12 +58,12 @@ public int Depth internal override FormattingCommandLineParameters GetCommandLineParameters() { - FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); + FormattingCommandLineParameters parameters = new(); if (_props != null) { - ParameterProcessor processor = new ParameterProcessor(new FormatObjectParameterDefinition()); - TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); + ParameterProcessor processor = new(new FormatObjectParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); parameters.mshParameterList = processor.ProcessParameters(_props, invocationContext); } @@ -87,7 +87,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() parameters.expansion = ProcessExpandParameter(); - ComplexSpecificParameters csp = new ComplexSpecificParameters(); + ComplexSpecificParameters csp = new(); csp.maxDepth = _depth; parameters.shapeParameters = csp; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index 923dc1bdb5c..7a8613ac032 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -83,12 +83,12 @@ public int Column internal override FormattingCommandLineParameters GetCommandLineParameters() { - FormattingCommandLineParameters parameters = new FormattingCommandLineParameters(); + FormattingCommandLineParameters parameters = new(); if (_prop != null) { - ParameterProcessor processor = new ParameterProcessor(new FormatWideParameterDefinition()); - TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); + ParameterProcessor processor = new(new FormatWideParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); parameters.mshParameterList = processor.ProcessParameters(new object[] { _prop }, invocationContext); } @@ -111,7 +111,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() // the user specified -autosize:true AND a column number string msg = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyAutosizeAndColumnsError); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidDataException(), "FormatCannotSpecifyAutosizeAndColumns", ErrorCategory.InvalidArgument, @@ -134,7 +134,7 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() if (_autosize.HasValue) parameters.autosize = _autosize.Value; - WideSpecificParameters wideSpecific = new WideSpecificParameters(); + WideSpecificParameters wideSpecific = new(); parameters.shapeParameters = wideSpecific; if (_column.HasValue) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index 751b2b32c72..2fbdb73dc9c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -228,7 +228,7 @@ private LineOutput InstantiateLineOutputInterface() } // use the stream writer to create and initialize the Line Output writer - TextWriterLineOutput twlo = new TextWriterLineOutput(_sw, computedWidth, _suppressNewline); + TextWriterLineOutput twlo = new(_sw, computedWidth, _suppressNewline); // finally have the ILineOutput interface extracted return (LineOutput)twlo; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs index 166613365b0..58342172906 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/Out-Printer.cs @@ -56,7 +56,7 @@ protected override void BeginProcessing() /// private LineOutput InstantiateLineOutputInterface() { - PrinterLineOutput printOutput = new PrinterLineOutput(_printerName); + PrinterLineOutput printOutput = new(_printerName); return (LineOutput)printOutput; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index 2b1aab06ae9..cbd19a17f4f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -90,8 +90,8 @@ internal PrinterLineOutput(string printerName) _printerName = printerName; // instantiate the helper to do the line processing when LineOutput.WriteXXX() is called - WriteLineHelper.WriteCallback wl = new WriteLineHelper.WriteCallback(this.OnWriteLine); - WriteLineHelper.WriteCallback w = new WriteLineHelper.WriteCallback(this.OnWrite); + WriteLineHelper.WriteCallback wl = new(this.OnWriteLine); + WriteLineHelper.WriteCallback w = new(this.OnWrite); _writeLineHelper = new WriteLineHelper(true, wl, w, this.DisplayCells); } @@ -124,7 +124,7 @@ private void DoPrint() try { // create a new print document object and set the printer name, if available - PrintDocument pd = new PrintDocument(); + PrintDocument pd = new(); if (!string.IsNullOrEmpty(_printerName)) { @@ -316,7 +316,7 @@ private void pd_PrintPage(object sender, PrintPageEventArgs ev) /// /// Text lines ready to print (after output cache playback). /// - private readonly Queue _lines = new Queue(); + private readonly Queue _lines = new(); /// /// Cached font object. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs index 48727c201dc..512bf1048e0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs @@ -90,7 +90,7 @@ protected override void BeginProcessing() private LineOutput InstantiateLineOutputInterface() { // set up the streaming text writer - StreamingTextWriter.WriteLineCallback callback = new StreamingTextWriter.WriteLineCallback(this.OnWriteLine); + StreamingTextWriter.WriteLineCallback callback = new(this.OnWriteLine); _writer = new StreamingTextWriter(callback, Host.CurrentCulture); @@ -104,7 +104,7 @@ private LineOutput InstantiateLineOutputInterface() } // use it to create and initialize the Line Output writer - TextWriterLineOutput twlo = new TextWriterLineOutput(_writer, computedWidth); + TextWriterLineOutput twlo = new(_writer, computedWidth); // finally have the LineOutput interface extracted return (LineOutput)twlo; @@ -165,6 +165,6 @@ protected override void EndProcessing() /// /// Buffer used when buffering until the end. /// - private readonly StringBuilder _buffer = new StringBuilder(); + private readonly StringBuilder _buffer = new(); } } From b5fc2f34e4935d6f404db9467b078b5a0785c0c5 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 26 Nov 2020 05:36:23 +0000 Subject: [PATCH 066/138] Use xml documentation child blocks correctly (#14249) --- .../CimSessionProxy.cs | 4 ++-- .../NewCimSessionCommand.cs | 4 +++- .../SetCimInstanceCommand.cs | 2 ++ .../commands/utility/WebCmdlet/ConvertToJsonCommand.cs | 2 +- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index 4badfd387c5..cf869c5c89f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -91,20 +91,20 @@ internal InvocationContext(string computerName, CimInstance targetCimInstance) /// /// ComputerName of the session /// + /// /// /// return value could be null /// - /// internal virtual string ComputerName { get; } /// /// /// CimInstance on which the current operation against. /// + /// /// /// return value could be null /// - /// internal virtual CimInstance TargetCimInstance { get; } } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index d0431ccb860..a4a93419e70 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -97,7 +97,7 @@ public PasswordAuthenticationMechanism Authentication /// /// /// The unit is Second. - /// + /// /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] @@ -153,9 +153,11 @@ public UInt32 Port /// If the argument is not given, a default SessionOption will be created for /// the session in .NET API layer. /// + /// /// If a object is passed, then /// connection is made using DCOM. If a /// object is passed, then connection is made using WsMan. + /// /// [Parameter(ValueFromPipelineByPropertyName = true)] public Microsoft.Management.Infrastructure.Options.CimSessionOptions SessionOption { get; set; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index 3e22eb9c6a5..c208f43b6ea 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -256,8 +256,10 @@ public IDictionary Property private IDictionary property; /// + /// /// The following is the definition of the input parameter "PassThru", /// indicate whether Set-CimInstance should output modified result instance or not. + /// /// /// True indicates output the result instance, otherwise output nothing as by default /// behavior. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index 3d35cc3c7ce..b741825e7e0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -72,7 +72,7 @@ public int Depth /// /// Specifies how strings are escaped when writing JSON text. /// If the EscapeHandling property is set to EscapeHtml, the result JSON string will - /// be returned with HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped. + /// be returned with HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped. /// [Parameter] public StringEscapeHandling EscapeHandling { get; set; } = StringEscapeHandling.Default; From 2f6d0ac61033a656a26258dbabc77c2fb6a69909 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 26 Nov 2020 05:38:27 +0000 Subject: [PATCH 067/138] Fix IDE0090: Simplify new expression part 4.4 (#14258) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../commands/utility/AddMember.cs | 8 ++-- .../commands/utility/AddType.cs | 46 +++++++++---------- .../commands/utility/Compare-Object.cs | 16 +++---- .../commands/utility/ConsoleColorCmdlet.cs | 2 +- .../utility/ConvertFrom-SddlString.cs | 10 ++-- .../utility/ConvertFrom-StringData.cs | 2 +- .../utility/ConvertFromMarkdownCommand.cs | 8 ++-- .../commands/utility/ConvertTo-Html.cs | 22 ++++----- .../commands/utility/Csv.cs | 2 +- .../commands/utility/CsvCommands.cs | 44 +++++++++--------- .../commands/utility/CustomSerialization.cs | 2 +- .../commands/utility/DebugRunspaceCommand.cs | 2 +- .../EnableDisableRunspaceDebugCommand.cs | 2 +- .../commands/utility/ExportAliasCommand.cs | 6 +-- .../commands/utility/Get-PSBreakpoint.cs | 2 +- .../commands/utility/GetAliasCommand.cs | 6 +-- .../commands/utility/GetDateCommand.cs | 8 ++-- .../commands/utility/GetEventCommand.cs | 2 +- .../utility/GetEventSubscriberCommand.cs | 4 +- .../commands/utility/GetHash.cs | 6 +-- .../commands/utility/GetMember.cs | 4 +- .../commands/utility/GetRandomCommand.cs | 6 +-- 22 files changed, 105 insertions(+), 105 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index 4fda5a09dd8..efb035b7785 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Commands HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097109", RemotingCapability = RemotingCapability.None)] public class AddMemberCommand : PSCmdlet { - private static readonly object s_notSpecified = new object(); + private static readonly object s_notSpecified = new(); private static bool HasBeenSpecified(object obj) { @@ -221,7 +221,7 @@ private void EnsureValue1HasBeenSpecified() { if (!HasBeenSpecified(_value1)) { - Collection fdc = new Collection(); + Collection fdc = new(); fdc.Add(new FieldDescription("Value")); string prompt = StringUtil.Format(AddMember.Value1Prompt, _memberType); Dictionary result = this.Host.UI.Prompt(prompt, null, fdc); @@ -531,9 +531,9 @@ private void UpdateTypeNames() private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) { - ErrorDetails details = new ErrorDetails(this.GetType().GetTypeInfo().Assembly, + ErrorDetails details = new(this.GetType().GetTypeInfo().Assembly, "Microsoft.PowerShell.Commands.Utility.resources.AddMember", resourceId, args); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidOperation, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index a2ffec58392..a54094ea464 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -153,7 +153,7 @@ public string[] Path string[] pathValue = value; - List resolvedPaths = new List(); + List resolvedPaths = new(); // Verify that the paths are resolved and valid foreach (string path in pathValue) @@ -198,7 +198,7 @@ public string[] LiteralPath return; } - List resolvedPaths = new List(); + List resolvedPaths = new(); foreach (string path in value) { string literalPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); @@ -230,7 +230,7 @@ private void ProcessPaths(List resolvedPaths) // Throw an error if it is an unrecognized extension default: - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.FileExtensionNotSupported, currentExtension)), "EXTENSION_NOT_SUPPORTED", @@ -248,7 +248,7 @@ private void ProcessPaths(List resolvedPaths) else if (!string.Equals(activeExtension, currentExtension, StringComparison.OrdinalIgnoreCase)) { // All files must have the same extension otherwise throw. - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.MultipleExtensionsNotSupported)), "MULTIPLE_EXTENSION_NOT_SUPPORTED", @@ -327,7 +327,7 @@ public string OutputAssembly // Try to resolve the path ProviderInfo provider = null; - Collection newPaths = new Collection(); + Collection newPaths = new(); try { @@ -336,7 +336,7 @@ public string OutputAssembly // Ignore the ItemNotFound -- we handle it. catch (ItemNotFoundException) { } - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new Exception( StringUtil.Format(AddTypeStrings.OutputAssemblyDidNotResolve, _outputAssembly)), "INVALID_OUTPUT_ASSEMBLY", @@ -520,7 +520,7 @@ private static string GetUsingTemplate(Language language) // Generate the code for the using statements private string GetUsingSet(Language language) { - StringBuilder usingNamespaceSet = new StringBuilder(); + StringBuilder usingNamespaceSet = new(); switch (language) { @@ -578,7 +578,7 @@ protected override void EndProcessing() // assembly type without an output assembly if (string.IsNullOrEmpty(_outputAssembly) && this.MyInvocation.BoundParameters.ContainsKey(nameof(OutputType))) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new Exception( string.Format( CultureInfo.CurrentCulture, @@ -630,21 +630,21 @@ protected override void EndProcessing() private static readonly string s_frameworkFolder = PathType.GetDirectoryName(typeof(object).Assembly.Location); // These assemblies are always automatically added to ReferencedAssemblies. - private static readonly Lazy s_autoReferencedAssemblies = new Lazy(InitAutoIncludedRefAssemblies); + private static readonly Lazy s_autoReferencedAssemblies = new(InitAutoIncludedRefAssemblies); // A HashSet of assembly names to be ignored if they are specified in '-ReferencedAssemblies' - private static readonly Lazy> s_refAssemblyNamesToIgnore = new Lazy>(InitRefAssemblyNamesToIgnore); + private static readonly Lazy> s_refAssemblyNamesToIgnore = new(InitRefAssemblyNamesToIgnore); // These assemblies are used, when ReferencedAssemblies parameter is not specified. - private static readonly Lazy> s_defaultAssemblies = new Lazy>(InitDefaultRefAssemblies); + private static readonly Lazy> s_defaultAssemblies = new(InitDefaultRefAssemblies); private bool InMemory { get { return string.IsNullOrEmpty(_outputAssembly); } } // These dictionaries prevent reloading already loaded and unchanged code. // We don't worry about unbounded growing of the cache because in .Net Core 2.0 we can not unload assemblies. // TODO: review if we will be able to unload assemblies after migrating to .Net Core 2.1. - private static readonly HashSet s_sourceTypesCache = new HashSet(); - private static readonly Dictionary s_sourceAssemblyCache = new Dictionary(); + private static readonly HashSet s_sourceTypesCache = new(); + private static readonly Dictionary s_sourceAssemblyCache = new(); private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; @@ -995,7 +995,7 @@ private void SourceCodeProcessing() } SourceText sourceText; - List syntaxTrees = new List(); + List syntaxTrees = new(); switch (ParameterSetName) { @@ -1074,12 +1074,12 @@ private void CompileToAssembly(List syntaxTrees, CompilationOptions private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag newTypes) { - AllNamedTypeSymbolsVisitor visitor = new AllNamedTypeSymbolsVisitor(); + AllNamedTypeSymbolsVisitor visitor = new(); visitor.Visit(compilation.Assembly.GlobalNamespace); foreach (var symbolName in visitor.DuplicateSymbols) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new Exception( string.Format(AddTypeStrings.TypeAlreadyExists, symbolName)), "TYPE_ALREADY_EXISTS", @@ -1090,7 +1090,7 @@ private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag DuplicateSymbols = new ConcurrentBag(); - public readonly ConcurrentBag UniqueSymbols = new ConcurrentBag(); + public readonly ConcurrentBag DuplicateSymbols = new(); + public readonly ConcurrentBag UniqueSymbols = new(); public override void VisitNamespace(INamespaceSymbol symbol) { @@ -1243,7 +1243,7 @@ private void HandleCompilerErrors(ImmutableArray compilerDiagnostics } else { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new Exception(errorText), "SOURCE_CODE_ERROR", ErrorCategory.InvalidData, @@ -1255,7 +1255,7 @@ private void HandleCompilerErrors(ImmutableArray compilerDiagnostics if (IsError) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(AddTypeStrings.CompilerErrors), "COMPILER_ERRORS", ErrorCategory.InvalidData, @@ -1288,7 +1288,7 @@ private static string BuildErrorMessage(Diagnostic diagnisticRecord) var errorLineString = textLines[errorLineNumber].ToString(); var errorPosition = lineSpan.StartLinePosition.Character; - StringBuilder sb = new StringBuilder(diagnisticMessage.Length + errorLineString.Length * 2 + 4); + StringBuilder sb = new(diagnisticMessage.Length + errorLineString.Length * 2 + 4); sb.AppendLine(diagnisticMessage); sb.AppendLine(errorLineString); @@ -1314,7 +1314,7 @@ private static string BuildErrorMessage(Diagnostic diagnisticRecord) private static int SyntaxTreeArrayGetHashCode(IEnumerable sts) { // We use our extension method EnumerableExtensions.SequenceGetHashCode(). - List stHashes = new List(); + List stHashes = new(); foreach (var st in sts) { stHashes.Add(SyntaxTreeGetHashCode(st)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs index 48cc3b3ca86..714054275d0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -101,10 +101,10 @@ public SwitchParameter PassThru private List _referenceEntries; private readonly List _referenceEntryBacklog - = new List(); + = new(); private readonly List _differenceEntryBacklog - = new List(); + = new(); private OrderByProperty _orderByProperty = null; private OrderByPropertyComparer _comparer = null; @@ -256,7 +256,7 @@ private void InitComparer() if (_comparer != null) return; - List referenceObjectList = new List(ReferenceObject); + List referenceObjectList = new(ReferenceObject); _orderByProperty = new OrderByProperty( this, referenceObjectList, Property, true, _cultureInfo, CaseSensitive); Diagnostics.Assert(_orderByProperty.Comparer != null, "no comparer"); @@ -327,7 +327,7 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) mshobj = new PSObject(); if (Property == null || Property.Length == 0) { - PSNoteProperty inputNote = new PSNoteProperty( + PSNoteProperty inputNote = new( InputObjectPropertyName, entry.inputObject); mshobj.Properties.Add(inputNote); } @@ -348,7 +348,7 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) object prop = hash[FormatParameterDefinitionKeys.ExpressionEntryKey]; Diagnostics.Assert(prop != null, "null prop"); string propName = prop.ToString(); - PSNoteProperty propertyNote = new PSNoteProperty( + PSNoteProperty propertyNote = new( propName, entry.orderValues[i].PropertyValue); try @@ -364,7 +364,7 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) } mshobj.Properties.Remove(SideIndicatorPropertyName); - PSNoteProperty sideNote = new PSNoteProperty( + PSNoteProperty sideNote = new( SideIndicatorPropertyName, sideIndicator); mshobj.Properties.Add(sideNote); WriteObject(mshobj); @@ -411,7 +411,7 @@ protected override void ProcessRecord() InitComparer(); } - List differenceList = new List(DifferenceObject); + List differenceList = new(DifferenceObject); List differenceEntries = OrderByProperty.CreateOrderMatrix( this, differenceList, _orderByProperty.MshParameterList); @@ -459,7 +459,7 @@ private void HandleDifferenceObjectOnly() return; } - List differenceList = new List(DifferenceObject); + List differenceList = new(DifferenceObject); _orderByProperty = new OrderByProperty( this, differenceList, Property, true, _cultureInfo, CaseSensitive); List differenceEntries = diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs index 3c3fde6cc61..e4d36c66106 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs @@ -92,7 +92,7 @@ public ConsoleColorCmdlet() private static ErrorRecord BuildOutOfRangeErrorRecord(object val, string errorId) { string msg = StringUtil.Format(HostStrings.InvalidColorErrorTemplate, val.ToString()); - ArgumentOutOfRangeException e = new ArgumentOutOfRangeException("value", val, msg); + ArgumentOutOfRangeException e = new("value", val, msg); return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null); } #endregion helper diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index 03a83bd4477..013f9079d63 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -57,9 +57,9 @@ private static string ConvertToNTAccount(SecurityIdentifier securityIdentifier) private static List GetApplicableAccessRights(int accessMask, AccessRightTypeNames? typeName) { - List typesToExamine = new List(); - List foundAccessRightNames = new List(); - HashSet foundAccessRightValues = new HashSet(); + List typesToExamine = new(); + List foundAccessRightNames = new(); + HashSet foundAccessRightValues = new(); if (typeName != null) { @@ -121,10 +121,10 @@ private static string[] ConvertAccessControlListToStrings(CommonAcl acl, AccessR return Array.Empty(); } - List aceStringList = new List(acl.Count); + List aceStringList = new(acl.Count); foreach (CommonAce ace in acl) { - StringBuilder aceString = new StringBuilder(); + StringBuilder aceString = new(); string ntAccount = ConvertToNTAccount(ace.SecurityIdentifier); aceString.Append($"{ntAccount}: {ace.AceQualifier}"); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs index adf91785673..16bb4be012d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -47,7 +47,7 @@ public string StringData /// protected override void ProcessRecord() { - Hashtable result = new Hashtable(StringComparer.OrdinalIgnoreCase); + Hashtable result = new(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrEmpty(_stringData)) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs index 1a87067b9b4..28d117f639f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs @@ -106,7 +106,7 @@ protected override void ProcessRecord() else { string errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidDataException(errorMessage), "InvalidInputObject", ErrorCategory.InvalidData, @@ -150,7 +150,7 @@ private async Task ReadContentFromFile(string filePath) try { - using (StreamReader reader = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))) + using (StreamReader reader = new(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))) { string mdContent = await reader.ReadToEndAsync(); return mdContent; @@ -189,7 +189,7 @@ private List ResolvePath(string path, bool isLiteral) { ProviderInfo provider = null; PSDriveInfo drive = null; - List resolvedPaths = new List(); + List resolvedPaths = new(); try { @@ -216,7 +216,7 @@ private List ResolvePath(string path, bool isLiteral) if (!provider.Name.Equals("FileSystem", StringComparison.OrdinalIgnoreCase)) { string errorMessage = StringUtil.Format(ConvertMarkdownStrings.FileSystemPathsOnly, path); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(), "OnlyFileSystemPathsSupported", ErrorCategory.InvalidArgument, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index e9ca7df9e30..e72fc825e7c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -340,9 +340,9 @@ protected override void SetEntries() /// private List ProcessParameter(object[] properties) { - TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); + TerminatingErrorContext invocationContext = new(this); ParameterProcessor processor = - new ParameterProcessor(new ConvertHTMLExpressionParameterDefinition()); + new(new ConvertHTMLExpressionParameterDefinition()); if (properties == null) { properties = new object[] { "*" }; @@ -394,7 +394,7 @@ private static Hashtable CreateAuxPropertyHT( string alignment, string width) { - Hashtable ht = new Hashtable(); + Hashtable ht = new(); if (label != null) { ht.Add(ConvertHTMLParameterDefinitionKeys.LabelEntryKey, label); @@ -444,8 +444,8 @@ protected override void BeginProcessing() // ValidateNotNullOrEmpty attribute is not working for System.Uri datatype, so handling it here if ((_cssuriSpecified) && (string.IsNullOrEmpty(_cssuri.OriginalString.Trim()))) { - ArgumentException ex = new ArgumentException(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri")); - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri"); + ArgumentException ex = new(StringUtil.Format(UtilityCommonStrings.EmptyCSSUri, "CSSUri")); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, "CSSUri"); ThrowTerminatingError(er); } @@ -480,7 +480,7 @@ protected override void BeginProcessing() if (_metaSpecified) { - List useditems = new List(); + List useditems = new(); foreach (string s in _meta.Keys) { if (!useditems.Contains(s)) @@ -503,7 +503,7 @@ protected override void BeginProcessing() default: MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); - WarningRecord record = new WarningRecord(Message); + WarningRecord record = new(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; if (invocationInfo != null) @@ -549,7 +549,7 @@ protected override void BeginProcessing() /// private void WriteColumns(List mshParams) { - StringBuilder COLTag = new StringBuilder(); + StringBuilder COLTag = new(); COLTag.Append(""); foreach (MshParameter p in mshParams) @@ -587,7 +587,7 @@ private void WriteListEntry() { foreach (MshParameter p in _resolvedNameMshParameters) { - StringBuilder Listtag = new StringBuilder(); + StringBuilder Listtag = new(); Listtag.Append(""); // for writing the property name @@ -713,7 +713,7 @@ protected override void ProcessRecord() { WriteColumns(_resolvedNameMshParameters); - StringBuilder THtag = new StringBuilder(""); + StringBuilder THtag = new(""); // write the table header WriteTableHeader(THtag, _resolvedNameMshParameters); @@ -726,7 +726,7 @@ protected override void ProcessRecord() // if the As parameter is Table, write the property values if (_as.Equals("Table", StringComparison.OrdinalIgnoreCase)) { - StringBuilder TRtag = new StringBuilder(""); + StringBuilder TRtag = new(""); // write the table row WriteTableRow(TRtag, _resolvedNameMshParameters); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs index 3bb626ca06e..9590cd7c771 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs @@ -28,7 +28,7 @@ internal CSVHelper(char delimiter) /// internal Collection ParseCsv(string csv) { - Collection result = new Collection(); + Collection result = new(); string tempString = string.Empty; csv = csv.Trim(); if (csv.Length == 0 || csv[0] == '#') diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index bd1e2fea05f..4b86f9d1a29 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -108,15 +108,15 @@ protected override void BeginProcessing() { if (this.MyInvocation.BoundParameters.ContainsKey(nameof(QuoteFields)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(UseQuotes))) { - InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyQuoteFieldsAndUseQuotes); - ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyQuoteFieldsAndUseQuotes", ErrorCategory.InvalidData, null); + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyQuoteFieldsAndUseQuotes); + ErrorRecord errorRecord = new(exception, "CannotSpecifyQuoteFieldsAndUseQuotes", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(NoTypeInformation))) { - InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyIncludeTypeInformationAndNoTypeInformation); - ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null); + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyIncludeTypeInformationAndNoTypeInformation); + ErrorRecord errorRecord = new(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } @@ -258,8 +258,8 @@ protected override void BeginProcessing() // Validate that they don't provide both Path and LiteralPath, but have provided at least one. if (!(_specifiedPath ^ _isLiteralPath)) { - InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); - ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); + ErrorRecord errorRecord = new(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } @@ -371,7 +371,7 @@ private void CreateFileStream() using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath)) { - ImportCsvHelper readingHelper = new ImportCsvHelper( + ImportCsvHelper readingHelper = new( this, this.Delimiter, null /* header */, null /* typeName */, streamReader); readingHelper.ReadHeader(); _preexistingPropertyNames = readingHelper.Header; @@ -446,7 +446,7 @@ private void ReconcilePreexistingPropertyNames() throw new InvalidOperationException(CsvCommandStrings.ReconcilePreexistingPropertyNamesMethodShouldOnlyGetCalledWhenPreexistingPropertyNamesHaveBeenReadSuccessfully); } - HashSet appendedPropertyNames = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet appendedPropertyNames = new(StringComparer.OrdinalIgnoreCase); foreach (string appendedPropertyName in _propertyNames) { appendedPropertyNames.Add(appendedPropertyName); @@ -463,8 +463,8 @@ private void ReconcilePreexistingPropertyNames() CsvCommandStrings.CannotAppendCsvWithMismatchedPropertyNames, preexistingPropertyName, this.Path); - InvalidOperationException exception = new InvalidOperationException(errorMessage); - ErrorRecord errorRecord = new ErrorRecord(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName); + InvalidOperationException exception = new(errorMessage); + ErrorRecord errorRecord = new(exception, "CannotAppendCsvWithMismatchedPropertyNames", ErrorCategory.InvalidData, preexistingPropertyName); this.ThrowTerminatingError(errorRecord); } } @@ -644,8 +644,8 @@ protected override void ProcessRecord() // Validate that they don't provide both Path and LiteralPath, but have provided at least one. if (!(_specifiedPath ^ _isLiteralPath)) { - InvalidOperationException exception = new InvalidOperationException(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); - ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); + InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyPathAndLiteralPath); + ErrorRecord errorRecord = new(exception, "CannotSpecifyPathAndLiteralPath", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } @@ -655,7 +655,7 @@ protected override void ProcessRecord() { using (StreamReader streamReader = PathUtils.OpenStreamReader(this, path, this.Encoding, _isLiteralPath)) { - ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, null /* typeName */, streamReader); + ImportCsvHelper helper = new(this, Delimiter, Header, null /* typeName */, streamReader); try { @@ -663,7 +663,7 @@ protected override void ProcessRecord() } catch (ExtendedTypeSystemException exception) { - ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null); + ErrorRecord errorRecord = new(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null); this.ThrowTerminatingError(errorRecord); } } @@ -833,10 +833,10 @@ protected override void ProcessRecord() { foreach (PSObject inputObject in InputObject) { - using (MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(inputObject.ToString()))) - using (StreamReader streamReader = new StreamReader(memoryStream, System.Text.Encoding.Unicode)) + using (MemoryStream memoryStream = new(Encoding.Unicode.GetBytes(inputObject.ToString()))) + using (StreamReader streamReader = new(memoryStream, System.Text.Encoding.Unicode)) { - ImportCsvHelper helper = new ImportCsvHelper(this, Delimiter, Header, _typeName, streamReader); + ImportCsvHelper helper = new(this, Delimiter, Header, _typeName, streamReader); try { @@ -844,7 +844,7 @@ protected override void ProcessRecord() } catch (ExtendedTypeSystemException exception) { - ErrorRecord errorRecord = new ErrorRecord(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null); + ErrorRecord errorRecord = new(exception, "AlreadyPresentPSMemberInfoInternalCollectionAdd", ErrorCategory.NotSpecified, null); this.ThrowTerminatingError(errorRecord); } @@ -1384,7 +1384,7 @@ private static void ValidatePropertyNames(IList names) } else { - HashSet headers = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet headers = new(StringComparer.OrdinalIgnoreCase); foreach (string currentHeader in names) { if (!string.IsNullOrEmpty(currentHeader)) @@ -1402,7 +1402,7 @@ private static void ValidatePropertyNames(IList names) ExtendedTypeSystem.MemberAlreadyPresent, currentHeader); - ExtendedTypeSystemException exception = new ExtendedTypeSystemException(memberAlreadyPresentMsg); + ExtendedTypeSystemException exception = new(memberAlreadyPresentMsg); throw exception; } } @@ -1636,7 +1636,7 @@ private bool IsNewLine(char ch, out string newLine) /// private void ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, bool eatTrailingBlanks) { - StringBuilder temp = new StringBuilder(); + StringBuilder temp = new(); // Did we see any non-whitespace character bool nonWhiteSpace = false; @@ -1684,7 +1684,7 @@ private void ReadTillNextDelimiter(StringBuilder current, ref bool endOfRecord, private PSObject BuildMshobject(string type, IList names, List values, char delimiter, bool preValidated = false) { - PSObject result = new PSObject(names.Count); + PSObject result = new(names.Count); char delimiterlocal = delimiter; int unspecifiedNameIndex = 1; for (int i = 0; i <= names.Count - 1; i++) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 2f5f8f6b7ba..6ad8b02a558 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -741,7 +741,7 @@ private void WritePSObjectProperties(PSObject source, int depth) Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties) { - PSMemberInfoInternalCollection specificProperties = new PSMemberInfoInternalCollection(); + PSMemberInfoInternalCollection specificProperties = new(); foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null)) { PSPropertyInfo property = source.Properties[propertyName]; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index 8111a721b97..aa370c12ba1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -43,7 +43,7 @@ public sealed class DebugRunspaceCommand : PSCmdlet // Debugging to persist until Ctrl+C or Debugger 'Exit' stops cmdlet. private bool _debugging; - private readonly ManualResetEventSlim _newRunningScriptEvent = new ManualResetEventSlim(true); + private readonly ManualResetEventSlim _newRunningScriptEvent = new(true); private RunspaceAvailability _previousRunspaceAvailability = RunspaceAvailability.None; #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index 177980aec94..c37d83ecf84 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -291,7 +291,7 @@ protected void SetDebugPreferenceHelper(string processName, string[] appDomainNa } catch (Exception ex) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, Debugger.PersistDebugPreferenceFailure, processName), ex), fullyQualifiedErrorId, ErrorCategory.InvalidOperation, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 431f30a3dcc..7260bc51d95 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -244,7 +244,7 @@ protected override void ProcessRecord() // that doesn't exist and they are not globbing. ItemNotFoundException itemNotFound = - new ItemNotFoundException( + new( aliasName, "AliasNotFound", SessionStateStrings.AliasNotFound); @@ -310,7 +310,7 @@ protected override void EndProcessing() /// /// Holds all the matching aliases for writing to the file. /// - private readonly Collection _matchingAliases = new Collection(); + private readonly Collection _matchingAliases = new(); private static string GetAliasLine(AliasInfo alias, string formatString) { @@ -406,7 +406,7 @@ private void ThrowFileOpenError(Exception e, string pathWithError) { string message = StringUtil.Format(AliasCommandStrings.ExportAliasFileOpenFailed, pathWithError, e.Message); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( e, "FileOpenFailure", ErrorCategory.OpenError, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index 26109ca710d..469e18926d8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -224,7 +224,7 @@ protected override void ProcessRecord() /// private static List Filter(List input, T[] filter, FilterSelector selector) { - List output = new List(); + List output = new(); for (int i = 0; i < input.Count; i++) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs index e44179440c1..fee8b3ab27c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -118,7 +118,7 @@ private void WriteMatches(string value, string parametersetname) _excludes, WildcardOptions.IgnoreCase); - List results = new List(); + List results = new(); foreach (KeyValuePair tableEntry in aliasTable) { if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase)) @@ -192,8 +192,8 @@ private void WriteMatches(string value, string parametersetname) // Need to write an error if the user tries to get an alias // tat doesn't exist and they are not globbing. - ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value)); - ErrorRecord er = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value); + ItemNotFoundException itemNotFound = new(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value)); + ErrorRecord er = new(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value); WriteError(er); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index 0e78e182f57..241c49a989f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -368,15 +368,15 @@ protected override void ProcessRecord() else { // output DateTime object wrapped in an PSObject with DisplayHint attached - PSObject outputObj = new PSObject(dateToUse); - PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint); + PSObject outputObj = new(dateToUse); + PSNoteProperty note = new("DisplayHint", DisplayHint); outputObj.Properties.Add(note); WriteObject(outputObj); } } - private static readonly DateTime s_epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly DateTime s_epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// /// This is more an implementation of the UNIX strftime. @@ -384,7 +384,7 @@ protected override void ProcessRecord() private string UFormatDateString(DateTime dateTime) { int offset = 0; - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); // folks may include the "+" as part of the format string if (UFormat[0] == '+') diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs index faf16d384f7..42360983c4e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -124,7 +124,7 @@ protected override void EndProcessing() error = EventingStrings.EventIdentifierNotFound; } - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)), "INVALID_SOURCE_IDENTIFIER", ErrorCategory.InvalidArgument, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs index cde73b2914d..b3bd99b7bdf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -67,7 +67,7 @@ protected override void ProcessRecord() // Go through all the received events and write them to the output // pipeline - List subscribers = new List(Events.Subscribers); + List subscribers = new(Events.Subscribers); foreach (PSEventSubscriber subscriber in subscribers) { // If they specified a event identifier and we don't match, continue @@ -118,7 +118,7 @@ protected override void ProcessRecord() error = EventingStrings.EventSubscriptionNotFound; } - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(string.Format(System.Globalization.CultureInfo.CurrentCulture, error, identifier)), "INVALID_SOURCE_IDENTIFIER", ErrorCategory.InvalidArgument, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs index 65e55a86ab1..40ea1d187d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -83,7 +83,7 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { - List pathsToProcess = new List(); + List pathsToProcess = new(); ProviderInfo provider = null; switch (ParameterSetName) @@ -104,7 +104,7 @@ protected override void ProcessRecord() { if (!WildcardPattern.ContainsWildcardCharacters(path)) { - ErrorRecord errorRecord = new ErrorRecord(e, + ErrorRecord errorRecord = new(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); @@ -211,7 +211,7 @@ private bool ComputeFileHash(string path, out string hash) /// private void WriteHashResult(string Algorithm, string hash, string path) { - FileHashInfo result = new FileHashInfo(); + FileHashInfo result = new(); result.Algorithm = Algorithm; result.Hash = hash; result.Path = path; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index 2f47c0d4c25..2fd9a499012 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -131,7 +131,7 @@ public SwitchParameter Force private MshMemberMatchOptions _matchOptions = MshMemberMatchOptions.None; - private readonly HybridDictionary _typesAlreadyDisplayed = new HybridDictionary(); + private readonly HybridDictionary _typesAlreadyDisplayed = new(); /// /// This method implements the ProcessRecord method for get-member command. @@ -271,7 +271,7 @@ protected override void EndProcessing() { if (_typesAlreadyDisplayed.Count == 0) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(GetMember.NoObjectSpecified), "NoObjectInGetMember", ErrorCategory.CloseError, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index 3569b2e4dc2..7d02713d801 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -95,7 +95,7 @@ private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) throw PSTraceSource.NewArgumentNullException("max"); } - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(string.Format( CultureInfo.InvariantCulture, GetRandomCommandStrings.MinGreaterThanOrEqualMax, minValue, maxValue)), "MinGreaterThanOrEqualMax", @@ -109,10 +109,10 @@ private void ThrowMinGreaterThanOrEqualMax(object minValue, object maxValue) #region Random generator state - private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new ReaderWriterLockSlim(); + private static readonly ReaderWriterLockSlim s_runspaceGeneratorMapLock = new(); // 1-to-1 mapping of runspaces and random number generators - private static readonly Dictionary s_runspaceGeneratorMap = new Dictionary(); + private static readonly Dictionary s_runspaceGeneratorMap = new(); private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { From 3c1261f90db028b7ab2210fbb75ac40e8ff449cf Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 26 Nov 2020 05:39:27 +0000 Subject: [PATCH 068/138] Enable SA1643: Destructor summary documentation should begin with standard text (#14236) https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1643.md --- .globalconfig | 2 +- .../WindowsTaskbarJumpList/PropVariant.cs | 2 +- .../host/msh/ConsoleHost.cs | 16 +++++++-------- .../engine/EventManager.cs | 8 ++++++++ .../engine/hostifaces/LocalPipeline.cs | 2 +- .../remoting/fanin/BaseTransportManager.cs | 2 +- .../engine/remoting/fanin/WSManNativeAPI.cs | 20 ++++++++----------- .../remoting/fanin/WSManPluginFacade.cs | 12 ++--------- .../remoting/fanin/WSManPluginShellSession.cs | 6 +----- .../help/CabinetNativeApi.cs | 2 +- 10 files changed, 32 insertions(+), 40 deletions(-) diff --git a/.globalconfig b/.globalconfig index 98345b665e6..6e4858fb0e4 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1531,7 +1531,7 @@ dotnet_diagnostic.SA1641.severity = none dotnet_diagnostic.SA1642.severity = none # SA1643: Destructor summary documentation should begin with standard text -dotnet_diagnostic.SA1643.severity = none +dotnet_diagnostic.SA1643.severity = warning # SA1648: inheritdoc should be used with inheriting class dotnet_diagnostic.SA1648.severity = none diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index ac1e6dfd139..90148ca7e25 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -51,7 +51,7 @@ public void Dispose() } /// - /// Finalizer. + /// Finalizes an instance of the class. /// ~PropVariant() { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index bc41b6ddb7f..73707dd0efe 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1194,14 +1194,6 @@ private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArg ui.WriteLine(); } - /// - /// Finalizes the instance. - /// - ~ConsoleHost() - { - Dispose(false); - } - /// /// Disposes of this instance, per the IDisposable pattern. /// @@ -1260,6 +1252,14 @@ private void Dispose(bool isDisposingNotFinalizing) _isDisposed = true; } + /// + /// Finalizes an instance of the class. + /// + ~ConsoleHost() + { + Dispose(false); + } + /// /// Indicates if the session should be terminated or not. Typically set by the break handler for Close, Logoff, and /// Shutdown events. Note that the only valid transition for this property is from false to true: it is not legal to diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 8f13eecd023..4afde8a9913 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -1544,6 +1544,14 @@ public void Dispose(bool disposing) } } } + + /// + /// Finalizes an instance of the class. + /// + ~PSLocalEventManager() + { + Dispose(false); + } } /// diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index b79eb4d6fd5..ab430decb50 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -1251,7 +1251,7 @@ public void Dispose() } /// - /// Ensure we release the worker thread. + /// Finalizes an instance of the class. /// ~PipelineThread() { diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 0af0c6e75ae..5d12914074c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -972,7 +972,7 @@ internal virtual void PrepareForConnect() #region Clean up /// - /// Finalizer. + /// Finalizes an instance of the class. /// ~BaseClientTransportManager() { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index efbb3ba7eed..8bcf2c09f2c 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -687,18 +687,6 @@ internal WSManData_ManToUn(string data) Marshal.StructureToPtr(_internalData, _marshalledObject, false); } - /// - /// Finalizer - /// - /// Note: Do not depend on the finalizer! This object should be - /// properly disposed of when no longer needed via a direct call - /// to Dispose(). - /// - ~WSManData_ManToUn() - { - Dispose(false); - } - /// /// Gets the type of data. /// @@ -747,6 +735,14 @@ private void Dispose(bool isDisposing) } } + /// + /// Finalizes an instance of the class. + /// + ~WSManData_ManToUn() + { + Dispose(false); + } + /// /// Implicit IntPtr conversion. /// diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 1c204773d70..e2679fcdf44 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -234,11 +234,7 @@ private void Dispose(bool disposing) } /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. + /// Finalizes an instance of the class. /// ~WSManPluginEntryDelegates() { @@ -766,11 +762,7 @@ private void Dispose(bool disposing) } /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. + /// Finalizes an instance of the class. /// ~WSManPluginManagedEntryInstanceWrapper() { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 6df3d25bb86..51635922e0b 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -111,11 +111,7 @@ protected virtual void Dispose(bool disposing) } /// - /// Use C# destructor syntax for finalization code. - /// This destructor will run only if the Dispose method - /// does not get called. - /// It gives your base class the opportunity to finalize. - /// Do not provide destructors in types derived from this class. + /// Finalizes an instance of the class. /// ~WSManPluginServerSession() { diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 20ae932d5d0..76e8fe853a4 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -84,7 +84,7 @@ protected override void Dispose(bool disposing) } /// - /// Finalizer to ensure destruction of unmanaged resources. + /// Finalizes an instance of the class. /// ~CabinetExtractor() { From 9f1f6762073e450d0940cfcbe8ee6dbb8710ea08 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 26 Nov 2020 05:43:29 +0000 Subject: [PATCH 069/138] Fix IDE0090: Simplify new expression part 2 (#14200) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../cmdletization/cim/CimJobException.cs | 14 ++-- .../cim/TerminatingErrorTracker.cs | 10 +-- .../cmdletization/cim/cimChildJobBase.cs | 10 +-- .../cim/cimCmdletInvocationContext.cs | 4 +- .../cmdletization/cim/cimConverter.cs | 2 +- .../cim/cimOperationOptionsHelper.cs | 4 +- .../cimSupport/cmdletization/cim/cimQuery.cs | 2 +- .../cmdletization/cim/cimWrapper.cs | 8 +-- .../cmdletization/cim/clientSideQuery.cs | 6 +- .../commands/management/AddContentCommand.cs | 2 +- .../commands/management/CIMHelper.cs | 4 +- .../management/ClearPropertyCommand.cs | 4 +- .../management/ClearRecycleBinCommand.cs | 2 +- .../commands/management/Clipboard.cs | 4 +- .../commands/management/Computer.cs | 58 +++++++-------- .../commands/management/ContentCommandBase.cs | 18 ++--- .../management/GetComputerInfoCommand.cs | 4 +- .../commands/management/GetContentCommand.cs | 10 +-- .../commands/management/Hotfix.cs | 8 +-- .../commands/management/Navigation.cs | 34 ++++----- .../commands/management/ParsePathCommand.cs | 4 +- .../commands/management/Process.cs | 72 +++++++++---------- .../commands/management/Service.cs | 72 +++++++++---------- .../management/SetClipboardCommand.cs | 4 +- .../commands/management/SetContentCommand.cs | 2 +- .../management/TestConnectionCommand.cs | 26 +++---- .../commands/management/TimeZoneCommands.cs | 12 ++-- .../management/WriteContentCommandBase.cs | 6 +- 28 files changed, 203 insertions(+), 203 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 624f47297a3..808ca1a4de9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -90,7 +90,7 @@ internal static CimJobException CreateFromCimException( Dbg.Assert(cimException != null, "Caller should verify cimException != null"); string message = BuildErrorMessage(jobDescription, jobContext, cimException.Message); - CimJobException cimJobException = new CimJobException(message, cimException); + CimJobException cimJobException = new(message, cimException); cimJobException.InitializeErrorRecord(jobContext, cimException); return cimJobException; } @@ -111,7 +111,7 @@ internal static CimJobException CreateFromAnyException( } string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); - CimJobException cimJobException = new CimJobException(message, inner); + CimJobException cimJobException = new(message, inner); var containsErrorRecord = inner as IContainsErrorRecord; if (containsErrorRecord != null) { @@ -142,7 +142,7 @@ internal static CimJobException CreateWithFullControl( Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null"); Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null"); - CimJobException cimJobException = new CimJobException(jobContext.PrependComputerNameToMessage(message), inner); + CimJobException cimJobException = new(jobContext.PrependComputerNameToMessage(message), inner); cimJobException.InitializeErrorRecord(jobContext, errorId, errorCategory); return cimJobException; } @@ -156,7 +156,7 @@ internal static CimJobException CreateWithoutJobContext( Dbg.Assert(!string.IsNullOrEmpty(message), "Caller should verify message != null"); Dbg.Assert(!string.IsNullOrEmpty(errorId), "Caller should verify errorId != null"); - CimJobException cimJobException = new CimJobException(message, inner); + CimJobException cimJobException = new(message, inner); cimJobException.InitializeErrorRecord(null, errorId, errorCategory); return cimJobException; } @@ -170,7 +170,7 @@ internal static CimJobException CreateFromMethodErrorCode(string jobDescription, string errorMessage = BuildErrorMessage(jobDescription, jobContext, rawErrorMessage); - CimJobException cje = new CimJobException(errorMessage); + CimJobException cje = new(errorMessage); cje.InitializeErrorRecord(jobContext, "CimJob_" + methodName + "_" + errorCodeFromMethod, ErrorCategory.InvalidResult); return cje; @@ -197,7 +197,7 @@ private static string BuildErrorMessage(string jobDescription, CimJobContext job private void InitializeErrorRecordCore(CimJobContext jobContext, Exception exception, string errorId, ErrorCategory errorCategory) { - ErrorRecord coreErrorRecord = new ErrorRecord( + ErrorRecord coreErrorRecord = new( exception: exception, errorId: errorId, errorCategory: errorCategory, @@ -205,7 +205,7 @@ private void InitializeErrorRecordCore(CimJobContext jobContext, Exception excep if (jobContext != null) { - System.Management.Automation.Remoting.OriginInfo originInfo = new System.Management.Automation.Remoting.OriginInfo( + System.Management.Automation.Remoting.OriginInfo originInfo = new( jobContext.Session.ComputerName, Guid.Empty); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index 73b8d0f3015..515e19f895c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -24,7 +24,7 @@ internal class TerminatingErrorTracker #region Getting tracker for a given cmdlet invocation private static readonly ConditionalWeakTable s_invocationToTracker = - new ConditionalWeakTable(); + new(); private static int GetNumberOfSessions(InvocationInfo invocationInfo) { @@ -100,7 +100,7 @@ private TerminatingErrorTracker(int numberOfSessions) #region Tracking session's "connectivity" status - private readonly ConcurrentDictionary _sessionToIsConnected = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _sessionToIsConnected = new(); internal void MarkSessionAsConnected(CimSession connectedSession) { @@ -166,7 +166,7 @@ internal Exception GetExceptionIfBrokenSession( #region Tracking session's "terminated" status - private readonly ConcurrentDictionary _sessionToIsTerminated = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _sessionToIsTerminated = new(); internal void MarkSessionAsTerminated(CimSession terminatedSession, out bool sessionWasAlreadyTerminated) { @@ -196,8 +196,8 @@ internal bool IsSessionTerminated(CimSession session) internal CmdletMethodInvoker GetErrorReportingDelegate(ErrorRecord errorRecord) { - ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim(); - object lockObject = new object(); + ManualResetEventSlim manualResetEventSlim = new(); + object lockObject = new(); Func action = (Cmdlet cmdlet) => { _numberOfReportedSessionTerminatingErrors++; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 3e885cf60ce..6dc65424f50 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -57,7 +57,7 @@ internal CimChildJobBase(CimJobContext jobContext) _jobSpecificCustomOptions = new Lazy(this.CalculateJobSpecificCustomOptions); } - private readonly CimSensitiveValueConverter _cimSensitiveValueConverter = new CimSensitiveValueConverter(); + private readonly CimSensitiveValueConverter _cimSensitiveValueConverter = new(); internal CimSensitiveValueConverter CimSensitiveValueConverter { get { return _cimSensitiveValueConverter; } } @@ -158,7 +158,7 @@ public virtual void OnCompleted() }); } - private static readonly Random s_globalRandom = new Random(); + private static readonly Random s_globalRandom = new(); private readonly Random _random; private int _sleepAndRetryDelayRangeMs = 1000; private int _sleepAndRetryExtraDelayMs = 0; @@ -543,7 +543,7 @@ private CimCustomOptionsDictionary GetJobSpecificCustomOptions() #region Controlling job state - private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private readonly CancellationTokenSource _cancellationTokenSource = new(); /// /// Stops this job. @@ -578,7 +578,7 @@ public override void StopJob() _cancellationTokenSource.Cancel(); } - private readonly object _jobStateLock = new object(); + private readonly object _jobStateLock = new(); private bool _jobHadErrors; private bool _jobWasStarted; private bool _jobWasStopped; @@ -730,7 +730,7 @@ internal void SetCompletedJobState(JobState state, Exception reason) #region Support for progress reporting - private readonly ConcurrentDictionary _activityIdToLastProgressRecord = new ConcurrentDictionary(); + private readonly ConcurrentDictionary _activityIdToLastProgressRecord = new(); internal override void WriteProgress(ProgressRecord progressRecord) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs index dd7b6ad8d7d..c876184c141 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -76,7 +76,7 @@ private static void WarnAboutUnsupportedActionPreferences( if (actionPreferenceComesFromCommandLineParameter) { Exception exception = new ArgumentException(message); - ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null); + ErrorRecord errorRecord = new(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null); cmdlet.ThrowTerminatingError(errorRecord); } } @@ -113,7 +113,7 @@ public bool ShowComputerName } } - private readonly Lazy _defaultCimSession = new Lazy(CreateDefaultCimSession); + private readonly Lazy _defaultCimSession = new(CreateDefaultCimSession); private static CimSession CreateDefaultCimSession() { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 915fb02e495..91500758a06 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -129,7 +129,7 @@ private void Dispose(bool disposing) } } - private readonly List _trackedDisposables = new List(); + private readonly List _trackedDisposables = new(); /// /// Releases resources associated with this object. diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs index 17801923bf0..1445ed17a14 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim internal class CimCustomOptionsDictionary { private readonly IDictionary _dict; - private readonly object _dictModificationLock = new object(); + private readonly object _dictModificationLock = new(); private CimCustomOptionsDictionary(IEnumerable> wrappedDictionary) { @@ -42,7 +42,7 @@ internal static CimCustomOptionsDictionary Create(IEnumerable s_cimInstanceToCustomOptions = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable s_cimInstanceToCustomOptions = new(); internal static void AssociateCimInstanceWithCustomOptions(CimInstance cimInstance, CimCustomOptionsDictionary newCustomOptions) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index 0da27d24d1d..a6f5b9616b9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -27,7 +27,7 @@ internal class CimQuery : QueryBuilder, ISessionBoundQueryBuilder private string _resultRole; private string _sourceRole; - internal readonly Dictionary queryOptions = new Dictionary(StringComparer.OrdinalIgnoreCase); + internal readonly Dictionary queryOptions = new(StringComparer.OrdinalIgnoreCase); internal ClientSideQuery ClientSideQuery { get; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs index f718ffe1dee..7052b16c768 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -281,7 +281,7 @@ private bool IsSupportedSession(CimSession cimSession, TerminatingErrorTracker t cimSession.ComputerName, nameOfUnsupportedSwitch); Exception exception = new NotSupportedException(errorMessage); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( exception, "NoExtendedSemanticsSupportInRemoteDcomProtocol", ErrorCategory.NotImplemented, @@ -338,7 +338,7 @@ internal override StartableJob CreateStaticMethodInvocationJob(CimSession sessio #region Session affinity management - private static readonly ConditionalWeakTable s_cimInstanceToSessionOfOrigin = new ConditionalWeakTable(); + private static readonly ConditionalWeakTable s_cimInstanceToSessionOfOrigin = new(); internal static void AssociateSessionOfOriginWithInstance(CimInstance cimInstance, CimSession sessionOfOrigin) { @@ -394,10 +394,10 @@ object IDynamicParameters.GetDynamicParameters() if (this.CmdletDefinitionContext.ExposeCimNamespaceParameter) { - Collection namespaceAttributes = new Collection(); + Collection namespaceAttributes = new(); namespaceAttributes.Add(new ValidateNotNullOrEmptyAttribute()); namespaceAttributes.Add(new ParameterAttribute()); - RuntimeDefinedParameter namespaceRuntimeParameter = new RuntimeDefinedParameter( + RuntimeDefinedParameter namespaceRuntimeParameter = new( CimNamespaceParameter, typeof(string), namespaceAttributes); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 4159cc07685..39d1a5bc441 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -153,7 +153,7 @@ public virtual IEnumerable GetNotFoundErrors_IfThisIsTheOnlyFilte private abstract class CimInstancePropertyBasedFilter : CimInstanceFilterBase { - private readonly List _propertyValueFilters = new List(); + private readonly List _propertyValueFilters = new(); protected IEnumerable PropertyValueFilters { get { return _propertyValueFilters; } } @@ -624,8 +624,8 @@ private static bool ActualValueLessThanOrEqualToExpectedValue(string propertyNam private int _numberOfResultsFromMi; private int _numberOfMatchingResults; - private readonly List _filters = new List(); - private readonly object _myLock = new object(); + private readonly List _filters = new(); + private readonly object _myLock = new(); #region "Public" interface for client-side filtering diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs index e56af5aa9cd..0f9762084d5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs @@ -40,7 +40,7 @@ internal override void SeekContentPosition(List contentHolders) catch (Exception e) // Catch-all OK, 3rd party callout { ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderSeekError", SessionStateStrings.ProviderSeekError, holder.PathInfo.Provider, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index b954e502ff8..1b10bbfe7ab 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -86,7 +86,7 @@ internal static string WqlQueryAll(string from) { var type = typeof(T); const BindingFlags binding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; - T rv = new T(); + T rv = new(); using (var instance = session.QueryFirstInstance(nameSpace, CIMHelper.WqlQueryAll(wmiClassName))) { @@ -148,7 +148,7 @@ internal static string WqlQueryAll(string from) foreach (var instance in instances) { - T objT = new T(); + T objT = new(); using (instance) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs index b5febde067b..f63eb8eed91 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs @@ -84,7 +84,7 @@ public string Name /// internal override object GetDynamicParameters(CmdletProviderContext context) { - Collection propertyCollection = new Collection(); + Collection propertyCollection = new(); propertyCollection.Add(_property); if (Path != null && Path.Length > 0) @@ -124,7 +124,7 @@ protected override void ProcessRecord() CmdletProviderContext currentContext = CmdletProviderContext; currentContext.PassThru = PassThru; - Collection propertyCollection = new Collection(); + Collection propertyCollection = new(); propertyCollection.Add(_property); foreach (string path in Path) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 85778dc28ba..78be89b90da 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -220,7 +220,7 @@ private void EmptyRecycleBin(string drivePath) statusDescription = string.Format(CultureInfo.InvariantCulture, ClearRecycleBinResources.ClearRecycleBinStatusDescriptionByDrive, drivePath); } - ProgressRecord progress = new ProgressRecord(0, activity, statusDescription); + ProgressRecord progress = new(0, activity, statusDescription); progress.PercentComplete = 30; progress.RecordType = ProgressRecordType.Processing; WriteProgress(progress); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs index 38a1b5c48a6..5ce64350fbd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs @@ -21,7 +21,7 @@ private static string StartProcess( string args, string stdin = "") { - ProcessStartInfo startInfo = new ProcessStartInfo(); + ProcessStartInfo startInfo = new(); startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; @@ -30,7 +30,7 @@ private static string StartProcess( startInfo.Arguments = args; string stdout; - using (Process process = new Process()) + using (Process process = new()) { process.StartInfo = startInfo; try diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index da250bb375e..d4763bb84f0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -194,9 +194,9 @@ public class RestartComputerCommand : PSCmdlet, IDisposable [Alias("CN", "__SERVER", "Server", "IPAddress")] public string[] ComputerName { get; set; } = new string[] { "." }; - private List _validatedComputerNames = new List(); - private readonly List _waitOnComputers = new List(); - private readonly HashSet _uniqueComputerNames = new HashSet(StringComparer.OrdinalIgnoreCase); + private List _validatedComputerNames = new(); + private readonly List _waitOnComputers = new(); + private readonly HashSet _uniqueComputerNames = new(StringComparer.OrdinalIgnoreCase); /// /// The following is the definition of the input parameter "Credential". @@ -336,13 +336,13 @@ public Int16 Delay /// Indicate to exit. /// private bool _exit, _timeUp; - private readonly CancellationTokenSource _cancel = new CancellationTokenSource(); + private readonly CancellationTokenSource _cancel = new(); /// /// A waithandler to wait on. Current thread will wait on it during the delay interval. /// - private readonly ManualResetEventSlim _waitHandler = new ManualResetEventSlim(false); - private readonly Dictionary _computerInfos = new Dictionary(StringComparer.OrdinalIgnoreCase); + private readonly ManualResetEventSlim _waitHandler = new(false); + private readonly Dictionary _computerInfos = new(StringComparer.OrdinalIgnoreCase); // CLR 4.0 Port note - use https://msdn.microsoft.com/library/system.net.networkinformation.ipglobalproperties.hostname(v=vs.110).aspx private readonly string _shortLocalMachineName = Dns.GetHostName(); @@ -441,7 +441,7 @@ private void ValidateComputerNames() if (!InternalTestHooks.TestWaitStopComputer && Wait && containLocalhost) { // The local machine will be ignored, and an error will be emitted. - InvalidOperationException ex = new InvalidOperationException(ComputerResources.CannotWaitLocalComputer); + InvalidOperationException ex = new(ComputerResources.CannotWaitLocalComputer); WriteError(new ErrorRecord(ex, "CannotWaitLocalComputer", ErrorCategory.InvalidOperation, null)); containLocalhost = false; } @@ -463,7 +463,7 @@ private void ValidateComputerNames() /// private void WriteProgress(string activity, string status, int percent, ProgressRecordType progressRecordType) { - ProgressRecord progress = new ProgressRecord(_activityId, activity, status); + ProgressRecord progress = new(_activityId, activity, status); progress.PercentComplete = percent; progress.RecordType = progressRecordType; WriteProgress(progress); @@ -725,7 +725,7 @@ internal static List TestWmiConnectionUsingWsman(List computerNa /// internal static List TestPowerShell(List computerNames, List nextTestList, System.Management.Automation.PowerShell powershell, PSCredential credential) { - List psList = new List(); + List psList = new(); try { @@ -783,7 +783,7 @@ protected override void BeginProcessing() // Timeout, For, Delay, Progress cannot be present if Wait is not present if ((_timeoutSpecified || _waitForSpecified || _delaySpecified) && !Wait) { - InvalidOperationException ex = new InvalidOperationException(ComputerResources.RestartComputerInvalidParameter); + InvalidOperationException ex = new(ComputerResources.RestartComputerInvalidParameter); ThrowTerminatingError(new ErrorRecord(ex, "RestartComputerInvalidParameter", ErrorCategory.InvalidOperation, null)); } @@ -810,8 +810,8 @@ protected override void BeginProcessing() _powershell.AddScript(TestPowershellScript); break; default: - InvalidOperationException ex = new InvalidOperationException(ComputerResources.NoSupportForCombinedServiceType); - ErrorRecord error = new ErrorRecord(ex, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (int)_waitFor); + InvalidOperationException ex = new(ComputerResources.NoSupportForCombinedServiceType); + ErrorRecord error = new(ex, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (int)_waitFor); ThrowTerminatingError(error); break; } @@ -1117,7 +1117,7 @@ public sealed class StopComputerCommand : PSCmdlet, IDisposable { #region Private Members - private readonly CancellationTokenSource _cancel = new CancellationTokenSource(); + private readonly CancellationTokenSource _cancel = new(); private const int forcedShutdown = 5; // See https://msdn.microsoft.com/library/aa394058(v=vs.85).aspx @@ -1388,7 +1388,7 @@ private string ValidateComputerName() { bool isLocalhost = targetComputer.Equals(ComputerWMIHelper.localhostStr, StringComparison.OrdinalIgnoreCase); string errMsg = StringUtil.Format(ComputerResources.InvalidNewName, isLocalhost ? _shortLocalMachineName : targetComputer, NewName); - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( new InvalidOperationException(errMsg), "InvalidNewName", ErrorCategory.InvalidArgument, NewName); WriteError(error); @@ -1430,7 +1430,7 @@ private void DoRenameComputerWsman(string computer, string computerName, string try { - using (CancellationTokenSource cancelTokenSource = new CancellationTokenSource()) + using (CancellationTokenSource cancelTokenSource = new()) using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credToUse, WsmanAuthentication, isLocalhost, this, cancelTokenSource.Token)) { var operationOptions = new CimOperationOptions @@ -1453,7 +1453,7 @@ private void DoRenameComputerWsman(string computer, string computerName, string if (oldName.Equals(newName, StringComparison.OrdinalIgnoreCase)) { string errMsg = StringUtil.Format(ComputerResources.NewNameIsOldName, computerName, newName); - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( new InvalidOperationException(errMsg), "NewNameIsOldName", ErrorCategory.InvalidArgument, newName); WriteError(error); @@ -1512,7 +1512,7 @@ private void DoRenameComputerWsman(string computer, string computerName, string { var ex = new Win32Exception(retVal); string errMsg = StringUtil.Format(ComputerResources.FailToRename, computerName, newName, ex.Message); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailToRenameComputer", ErrorCategory.OperationStopped, computerName); + ErrorRecord error = new(new InvalidOperationException(errMsg), "FailToRenameComputer", ErrorCategory.OperationStopped, computerName); WriteError(error); } else @@ -1553,14 +1553,14 @@ private void DoRenameComputerWsman(string computer, string computerName, string catch (CimException ex) { string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "RenameComputerException", + ErrorRecord error = new(new InvalidOperationException(errMsg), "RenameComputerException", ErrorCategory.OperationStopped, computerName); WriteError(error); } catch (Exception ex) { string errMsg = StringUtil.Format(ComputerResources.FailToConnectToComputer, computerName, ex.Message); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "RenameComputerException", + ErrorRecord error = new(new InvalidOperationException(errMsg), "RenameComputerException", ErrorCategory.OperationStopped, computerName); WriteError(error); } @@ -1844,7 +1844,7 @@ internal static string GetRandomPassword(int passwordLength) /// internal static string GetScopeString(string computer, string namespaceParameter) { - StringBuilder returnValue = new StringBuilder("\\\\"); + StringBuilder returnValue = new("\\\\"); if (computer.Equals("::1", StringComparison.OrdinalIgnoreCase) || computer.Equals("[::1]", StringComparison.OrdinalIgnoreCase)) { returnValue.Append("localhost"); @@ -1920,7 +1920,7 @@ internal static string GetMachineNames(string[] computerNames) } string compname = string.Empty; - StringBuilder strComputers = new StringBuilder(); + StringBuilder strComputers = new(); int i = 0; foreach (string computer in computerNames) { @@ -1950,7 +1950,7 @@ internal static string GetMachineNames(string[] computerNames) internal static ComputerChangeInfo GetComputerStatusObject(int errorcode, string computername) { - ComputerChangeInfo computerchangeinfo = new ComputerChangeInfo(); + ComputerChangeInfo computerchangeinfo = new(); computerchangeinfo.ComputerName = computername; if (errorcode != 0) { @@ -1966,7 +1966,7 @@ internal static ComputerChangeInfo GetComputerStatusObject(int errorcode, string internal static RenameComputerChangeInfo GetRenameComputerStatusObject(int errorcode, string newcomputername, string oldcomputername) { - RenameComputerChangeInfo renamecomputerchangeinfo = new RenameComputerChangeInfo(); + RenameComputerChangeInfo renamecomputerchangeinfo = new(); renamecomputerchangeinfo.OldComputerName = oldcomputername; renamecomputerchangeinfo.NewComputerName = newcomputername; if (errorcode != 0) @@ -1983,7 +1983,7 @@ internal static RenameComputerChangeInfo GetRenameComputerStatusObject(int error internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, string computername) { - Win32Exception ex = new Win32Exception(errorcode); + Win32Exception ex = new(errorcode); string additionalmessage = string.Empty; if (ex.NativeErrorCode.Equals(0x00000035)) { @@ -1991,7 +1991,7 @@ internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, st } string message = StringUtil.Format(ComputerResources.OperationFailed, ex.Message, computername, additionalmessage); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, computername); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, computername); cmdlet.WriteError(er); } @@ -2101,7 +2101,7 @@ internal static bool InvokeWin32ShutdownUsingWsman( string message = StringUtil.Format(ComputerResources.PrivilegeNotEnabled, computerName, isLocalhost ? ComputerWMIHelper.SE_SHUTDOWN_NAME : ComputerWMIHelper.SE_REMOTE_SHUTDOWN_NAME); - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(message), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null); + ErrorRecord errorRecord = new(new InvalidOperationException(message), "PrivilegeNotEnabled", ErrorCategory.InvalidOperation, null); cmdlet.WriteError(errorRecord); return false; } @@ -2159,7 +2159,7 @@ internal static bool InvokeWin32ShutdownUsingWsman( { var ex = new Win32Exception(retVal); string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } @@ -2172,14 +2172,14 @@ internal static bool InvokeWin32ShutdownUsingWsman( catch (CimException ex) { string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID, + ErrorRecord error = new(new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } catch (Exception ex) { string errMsg = StringUtil.Format(formatErrorMessage, computerName, ex.Message); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), ErrorFQEID, + ErrorRecord error = new(new InvalidOperationException(errMsg), ErrorFQEID, ErrorCategory.OperationStopped, computerName); cmdlet.WriteError(error); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index 583f12cc8ea..e7cc4097066 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -108,7 +108,7 @@ public override SwitchParameter Force /// An array of content holder objects that contain the path information /// and content readers/writers for the item represented by the path information. /// - internal List contentStreams = new List(); + internal List contentStreams = new(); /// /// Wraps the content into a PSObject and adds context information as notes. @@ -297,7 +297,7 @@ public PSObject AttachNotes(PSObject content) { // Construct a provider qualified path as the Path note - PSNoteProperty note = new PSNoteProperty("PSPath", PSPath); + PSNoteProperty note = new("PSPath", PSPath); content.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", PSPath); @@ -385,7 +385,7 @@ internal void CloseContent(List contentHolders, bool disposing) // and write out an error. ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, @@ -422,7 +422,7 @@ internal void CloseContent(List contentHolders, bool disposing) // and write out an error. ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, @@ -480,7 +480,7 @@ internal List GetContentReaders( // Create the results array - List results = new List(); + List results = new(); foreach (PathInfo pathInfo in pathInfos) { @@ -538,7 +538,7 @@ internal List GetContentReaders( if (readers.Count == 1 && readers[0] != null) { ContentHolder holder = - new ContentHolder(pathInfo, readers[0], null); + new(pathInfo, readers[0], null); results.Add(holder); } @@ -573,7 +573,7 @@ internal Collection ResolvePaths( bool allowEmptyResult, CmdletProviderContext currentCommandContext) { - Collection results = new Collection(); + Collection results = new(); foreach (string path in pathsToResolve) { @@ -653,7 +653,7 @@ internal Collection ResolvePaths( out drive); PathInfo pathInfo = - new PathInfo( + new( drive, provider, unresolvedPath, @@ -666,7 +666,7 @@ internal Collection ResolvePaths( { // Detect if the path resolution failed to resolve to a file. string error = StringUtil.Format(NavigationResources.ItemNotFound, Path); - Exception e = new Exception(error); + Exception e = new(error); pathNotFoundErrorRecord = new ErrorRecord( e, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index baef129a15c..4c8a95dddeb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -225,7 +225,7 @@ protected override void ProcessRecord() /// private void UpdateProgress(string status) { - ProgressRecord progress = new ProgressRecord(0, activity, status ?? ComputerResources.ProgressStatusCompleted); + ProgressRecord progress = new(0, activity, status ?? ComputerResources.ProgressStatusCompleted); progress.RecordType = status == null ? ProgressRecordType.Completed : ProgressRecordType.Processing; WriteProgress(progress); @@ -486,7 +486,7 @@ private static DeviceGuardInfo GetDeviceGuard(CimSession session) /// private static HyperVInfo GetHyperVisorInfo(CimSession session) { - HyperVInfo info = new HyperVInfo(); + HyperVInfo info = new(); bool ok = false; CimInstance instance = null; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index 964ebd947d1..c64f1e6b954 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -116,7 +116,7 @@ protected override void ProcessRecord() if (_totalCountSpecified && _tailSpecified) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); + ErrorRecord error = new(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); WriteError(error); return; } @@ -145,7 +145,7 @@ protected override void ProcessRecord() if (_tailSpecified && holder.Reader is not FileSystemContentReaderWriter) { string errMsg = SessionStateStrings.GetContent_TailNotSupported; - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); + ErrorRecord error = new(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); WriteError(error); continue; } @@ -165,7 +165,7 @@ protected override void ProcessRecord() catch (Exception e) { ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, @@ -218,7 +218,7 @@ protected override void ProcessRecord() catch (Exception e) // Catch-all OK. 3rd party callout { ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, @@ -294,7 +294,7 @@ private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext cur catch (Exception e) { ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderContentReadError", SessionStateStrings.ProviderContentReadError, holder.PathInfo.Provider, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index 3c65ecb35c6..d6768a1315e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -66,7 +66,7 @@ public sealed class GetHotFixCommand : PSCmdlet, IDisposable private ManagementObjectSearcher _searchProcess; private bool _inputContainsWildcard = false; - private readonly ConnectionOptions _connectionOptions = new ConnectionOptions(); + private readonly ConnectionOptions _connectionOptions = new(); /// /// Sets connection options. @@ -87,8 +87,8 @@ protected override void ProcessRecord() foreach (string computer in ComputerName) { bool foundRecord = false; - StringBuilder queryString = new StringBuilder(); - ManagementScope scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), _connectionOptions); + StringBuilder queryString = new(); + ManagementScope scope = new(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), _connectionOptions); scope.Connect(); if (Id != null) { @@ -134,7 +134,7 @@ protected override void ProcessRecord() { try { - SecurityIdentifier secObj = new SecurityIdentifier(installed); + SecurityIdentifier secObj = new(installed); obj["InstalledBy"] = secObj.Translate(typeof(NTAccount)); } catch (IdentityNotMappedException) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 859a6dd03f3..6528e8394c2 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -39,7 +39,7 @@ internal virtual CmdletProviderContext CmdletProviderContext { get { - CmdletProviderContext coreCommandContext = new CmdletProviderContext(this); + CmdletProviderContext coreCommandContext = new(this); coreCommandContext.Force = Force; @@ -165,7 +165,7 @@ protected override void StopProcessing() } internal Collection stopContextCollection = - new Collection(); + new(); /// /// Gets or sets the filter property. @@ -301,7 +301,7 @@ internal override CmdletProviderContext CmdletProviderContext { get { - CmdletProviderContext coreCommandContext = new CmdletProviderContext(this, Credential); + CmdletProviderContext coreCommandContext = new(this, Credential); coreCommandContext.Force = Force; Collection includeFilter = @@ -447,7 +447,7 @@ protected override void ProcessRecord() catch (DriveNotFoundException e) { ErrorRecord errorRecord = - new ErrorRecord( + new( e, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, @@ -458,7 +458,7 @@ protected override void ProcessRecord() catch (ProviderNotFoundException e) { ErrorRecord errorRecord = - new ErrorRecord( + new( e, "GetLocationNoMatchingProvider", ErrorCategory.ObjectNotFound, @@ -469,7 +469,7 @@ protected override void ProcessRecord() catch (ArgumentException argException) { ErrorRecord errorRecord = - new ErrorRecord( + new( argException, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, @@ -523,7 +523,7 @@ protected override void ProcessRecord() catch (ProviderNotFoundException e) { ErrorRecord errorRecord = - new ErrorRecord( + new( e, "GetLocationNoMatchingProvider", ErrorCategory.ObjectNotFound, @@ -1237,7 +1237,7 @@ protected override void ProcessRecord() // -Persist switch parameter is supported only for FileSystem provider. if (Persist && !provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - ErrorRecord er = new ErrorRecord(new NotSupportedException(FileSystemProviderStrings.PersistNotSupported), "DriveRootNotNetworkPath", ErrorCategory.InvalidArgument, this); + ErrorRecord er = new(new NotSupportedException(FileSystemProviderStrings.PersistNotSupported), "DriveRootNotNetworkPath", ErrorCategory.InvalidArgument, this); ThrowTerminatingError(er); } @@ -1249,7 +1249,7 @@ protected override void ProcessRecord() // Create the new drive PSDriveInfo newDrive = - new PSDriveInfo( + new( Name, provider, Root, @@ -1368,7 +1368,7 @@ internal List GetMatchingDrives( string[] providerNames, string scope) { - List results = new List(); + List results = new(); if (providerNames == null || providerNames.Length == 0) { @@ -1637,7 +1637,7 @@ protected override void ProcessRecord() if (verifyMatch && !foundMatch) { - DriveNotFoundException e = new DriveNotFoundException( + DriveNotFoundException e = new( driveName, "DriveNotFound", SessionStateStrings.DriveNotFound); @@ -1776,7 +1776,7 @@ protected override void ProcessRecord() if (!WildcardPattern.ContainsWildcardCharacters(driveName)) { DriveNotFoundException driveNotFound = - new DriveNotFoundException( + new( driveName, "DriveNotFound", SessionStateStrings.DriveNotFound); @@ -1793,7 +1793,7 @@ protected override void ProcessRecord() catch (DriveNotFoundException driveNotFound) { ErrorRecord errorRecord = - new ErrorRecord( + new( driveNotFound, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, @@ -1803,7 +1803,7 @@ protected override void ProcessRecord() catch (ProviderNotFoundException providerNotFound) { ErrorRecord errorRecord = - new ErrorRecord( + new( providerNotFound, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, @@ -2539,7 +2539,7 @@ protected override void ProcessRecord() if (SuppressWildcardExpansion == true && resolvedPSPaths.Count == 0) { ItemNotFoundException pathNotFound = - new ItemNotFoundException( + new( path, "PathNotFound", SessionStateStrings.PathNotFound); @@ -2700,7 +2700,7 @@ protected override void ProcessRecord() { try { - System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(providerPath); + System.IO.DirectoryInfo di = new(providerPath); if (di != null && (di.Attributes & System.IO.FileAttributes.ReparsePoint) != 0) { shouldRecurse = false; @@ -2941,7 +2941,7 @@ internal override object GetDynamicParameters(CmdletProviderContext context) private Collection GetResolvedPaths(string path) { - Collection results = new Collection(); + Collection results = new(); try { results = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index a1dd7895fc1..d56a20faba0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -184,7 +184,7 @@ public string[] LiteralPath /// protected override void ProcessRecord() { - StringCollection pathsToParse = new StringCollection(); + StringCollection pathsToParse = new(); if (Resolve) { @@ -305,7 +305,7 @@ protected override void ProcessRecord() if (separatorIndex < 0) { FormatException e = - new FormatException( + new( StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index])); WriteError( new ErrorRecord( diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 2ac312b62a0..c6eb4327471 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -103,8 +103,8 @@ public virtual Process[] InputObject // We use a Dictionary to optimize the check whether the object // is already in the list. - private List _matchingProcesses = new List(); - private readonly Dictionary _keys = new Dictionary(); + private List _matchingProcesses = new(); + private readonly Dictionary _keys = new(); /// /// Retrieve the list of all processes matching the Name, Id @@ -280,7 +280,7 @@ internal Process[] AllProcesses { if (_allProcesses == null) { - List processes = new List(); + List processes = new(); processes.AddRange(Process.GetProcesses()); _allProcesses = processes.ToArray(); } @@ -358,7 +358,7 @@ internal void WriteNonTerminatingError( processId, (innerException == null) ? string.Empty : innerException.Message); ProcessCommandException exception = - new ProcessCommandException(message, innerException); + new(message, innerException); exception.ProcessName = processName; WriteError(new ErrorRecord( @@ -723,7 +723,7 @@ private static PSObject AddUserNameToProcess(Process process) string userName = RetrieveProcessUserName(process); PSObject processAsPsobj = PSObject.AsPSObject(process); - PSNoteProperty noteProperty = new PSNoteProperty("UserName", userName); + PSNoteProperty noteProperty = new("UserName", userName); processAsPsobj.Properties.Add(noteProperty, true); processAsPsobj.TypeNames.Insert(0, TypeNameForProcessWithUserName); @@ -952,7 +952,7 @@ private void myProcess_Exited(object sender, System.EventArgs e) #region Overrides - private readonly List _processList = new List(); + private readonly List _processList = new(); // Wait handle which is used by thread to sleep. private ManualResetEvent _waitHandle; @@ -1029,7 +1029,7 @@ protected override void EndProcessing() if (!process.HasExited) { string message = StringUtil.Format(ProcessResources.ProcessNotTerminated, new object[] { process.ProcessName, process.Id }); - ErrorRecord errorRecord = new ErrorRecord(new TimeoutException(message), "ProcessNotTerminated", ErrorCategory.CloseError, process); + ErrorRecord errorRecord = new(new TimeoutException(message), "ProcessNotTerminated", ErrorCategory.CloseError, process); WriteError(errorRecord); } } @@ -1822,7 +1822,7 @@ protected override void BeginProcessing() if (_nonewwindow && _windowstyleSpecified) { message = StringUtil.Format(ProcessResources.ContradictParametersSpecified, "-NoNewWindow", "-WindowStyle"); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -1840,12 +1840,12 @@ protected override void BeginProcessing() if (!string.IsNullOrEmpty(message)) { - ErrorRecord er = new ErrorRecord(new NotSupportedException(message), "NotSupportedException", ErrorCategory.NotImplemented, null); + ErrorRecord er = new(new NotSupportedException(message), "NotSupportedException", ErrorCategory.NotImplemented, null); ThrowTerminatingError(er); } } - ProcessStartInfo startInfo = new ProcessStartInfo(); + ProcessStartInfo startInfo = new(); // Use ShellExecute by default if we are running on full windows SKUs startInfo.UseShellExecute = Platform.IsWindowsDesktop; @@ -1883,7 +1883,7 @@ protected override void BeginProcessing() if (!Directory.Exists(WorkingDirectory)) { message = StringUtil.Format(ProcessResources.InvalidInput, "WorkingDirectory"); - ErrorRecord er = new ErrorRecord(new DirectoryNotFoundException(message), "DirectoryNotFoundException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new DirectoryNotFoundException(message), "DirectoryNotFoundException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -1942,7 +1942,7 @@ protected override void BeginProcessing() if (!File.Exists(_redirectstandardinput)) { message = StringUtil.Format(ProcessResources.InvalidInput, "RedirectStandardInput '" + this.RedirectStandardInput + "'"); - ErrorRecord er = new ErrorRecord(new FileNotFoundException(message), "FileNotFoundException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new FileNotFoundException(message), "FileNotFoundException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -1956,7 +1956,7 @@ protected override void BeginProcessing() if (_redirectstandardinput.Equals(_redirectstandardoutput, StringComparison.OrdinalIgnoreCase)) { message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardOutput"); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -1970,7 +1970,7 @@ protected override void BeginProcessing() if (_redirectstandardinput.Equals(_redirectstandarderror, StringComparison.OrdinalIgnoreCase)) { message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardInput", "RedirectStandardError"); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -1984,7 +1984,7 @@ protected override void BeginProcessing() if (_redirectstandardoutput.Equals(_redirectstandarderror, StringComparison.OrdinalIgnoreCase)) { message = StringUtil.Format(ProcessResources.DuplicateEntry, "RedirectStandardOutput", "RedirectStandardError"); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); WriteError(er); return; } @@ -2011,7 +2011,7 @@ protected override void BeginProcessing() else { message = StringUtil.Format(ProcessResources.CannotStarttheProcess); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } } @@ -2028,7 +2028,7 @@ protected override void BeginProcessing() _waithandle = new ManualResetEvent(false); // Create and start the job object - ProcessCollection jobObject = new ProcessCollection(); + ProcessCollection jobObject = new(); if (jobObject.AssignProcessToJobObject(process)) { // Wait for the job object to finish @@ -2047,7 +2047,7 @@ protected override void BeginProcessing() else { message = StringUtil.Format(ProcessResources.CannotStarttheProcess); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } } @@ -2269,7 +2269,7 @@ private void WriteToStandardInput(Process p) private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, uint dwCreationDisposition) { System.IntPtr hFileHandle = System.IntPtr.Zero; - ProcessNativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes = new ProcessNativeMethods.SECURITY_ATTRIBUTES(); + ProcessNativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes = new(); hFileHandle = ProcessNativeMethods.CreateFileW(RedirectionPath, ProcessNativeMethods.GENERIC_READ | ProcessNativeMethods.GENERIC_WRITE, @@ -2281,19 +2281,19 @@ private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, u if (hFileHandle == System.IntPtr.Zero) { int error = Marshal.GetLastWin32Error(); - Win32Exception win32ex = new Win32Exception(error); + Win32Exception win32ex = new(error); string message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } - SafeFileHandle sf = new SafeFileHandle(hFileHandle, true); + SafeFileHandle sf = new(hFileHandle, true); return sf; } private static StringBuilder BuildCommandLine(string executableFileName, string arguments) { - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new(); string str = executableFileName.Trim(); bool flag = str.StartsWith('"') && str.EndsWith('"'); if (!flag) @@ -2324,7 +2324,7 @@ private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) string[] strArray2 = new string[sd.Count]; sd.Values.CopyTo(strArray2, 0); Array.Sort(array, strArray2, StringComparer.OrdinalIgnoreCase); - StringBuilder builder = new StringBuilder(); + StringBuilder builder = new(); for (int i = 0; i < sd.Count; i++) { builder.Append(array[i]); @@ -2430,10 +2430,10 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods /// private Process StartWithCreateProcess(ProcessStartInfo startinfo) { - ProcessNativeMethods.STARTUPINFO lpStartupInfo = new ProcessNativeMethods.STARTUPINFO(); - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new SafeNativeMethods.PROCESS_INFORMATION(); + ProcessNativeMethods.STARTUPINFO lpStartupInfo = new(); + SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); int error = 0; - GCHandle pinnedEnvironmentBlock = new GCHandle(); + GCHandle pinnedEnvironmentBlock = new(); IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; string message = string.Empty; @@ -2497,7 +2497,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) } else { - Win32Exception win32ex = new Win32Exception(error); + Win32Exception win32ex = new(error); message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); } @@ -2525,23 +2525,23 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) IntPtr token = WindowsIdentity.GetCurrent().Token; if (!ProcessNativeMethods.CreateEnvironmentBlock(out AddressOfEnvironmentBlock, token, false)) { - Win32Exception win32ex = new Win32Exception(error); + Win32Exception win32ex = new(error); message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); var errorRecord = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(errorRecord); } } - ProcessNativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes = new ProcessNativeMethods.SECURITY_ATTRIBUTES(); - ProcessNativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes = new ProcessNativeMethods.SECURITY_ATTRIBUTES(); + ProcessNativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes = new(); + ProcessNativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes = new(); flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation); if (!flag) { error = Marshal.GetLastWin32Error(); - Win32Exception win32ex = new Win32Exception(error); + Win32Exception win32ex = new(error); message = StringUtil.Format(ProcessResources.InvalidStartProcess, win32ex.Message); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } @@ -2583,7 +2583,7 @@ private Process StartWithShellExecute(ProcessStartInfo startInfo) catch (Win32Exception ex) { string message = StringUtil.Format(ProcessResources.InvalidStartProcess, ex.Message); - ErrorRecord er = new ErrorRecord(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); + ErrorRecord er = new(new InvalidOperationException(message), "InvalidOperationException", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(er); } @@ -2634,7 +2634,7 @@ internal void CheckJobStatus(object stateInfo) ManualResetEvent emptyJobAutoEvent = (ManualResetEvent)stateInfo; int dwSize = 0; const int JOB_OBJECT_BASIC_PROCESS_ID_LIST = 3; - JOBOBJECT_BASIC_PROCESS_ID_LIST JobList = new JOBOBJECT_BASIC_PROCESS_ID_LIST(); + JOBOBJECT_BASIC_PROCESS_ID_LIST JobList = new(); dwSize = Marshal.SizeOf(JobList); if (NativeMethods.QueryInformationJobObject(_jobObjectHandle, @@ -2659,7 +2659,7 @@ internal void CheckJobStatus(object stateInfo) internal void WaitOne(ManualResetEvent waitHandleToUse) { TimerCallback jobObjectStatusCb = this.CheckJobStatus; - using (Timer stateTimer = new Timer(jobObjectStatusCb, waitHandleToUse, 0, 1000)) + using (Timer stateTimer = new(jobObjectStatusCb, waitHandleToUse, 0, 1000)) { waitHandleToUse.WaitOne(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index d0d9c943578..a4471699922 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -134,7 +134,7 @@ internal void SetServiceSecurityDescriptor( if (!status) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); bool accessDenied = exception.NativeErrorCode == NativeMethods.ERROR_ACCESS_DENIED; WriteNonTerminatingError( service, @@ -380,7 +380,7 @@ private static int ServiceComparison(ServiceController x, ServiceController y) /// private List MatchingServicesByServiceName() { - List matchingServices = new List(); + List matchingServices = new(); if (serviceNames == null) { @@ -443,7 +443,7 @@ private List MatchingServicesByServiceName() /// private List MatchingServicesByDisplayName() { - List matchingServices = new List(); + List matchingServices = new(); if (DisplayName == null) { Diagnostics.Assert(false, "null DisplayName"); @@ -486,7 +486,7 @@ private List MatchingServicesByDisplayName() /// private List MatchingServicesByInput() { - List matchingServices = new List(); + List matchingServices = new(); if (InputObject == null) { Diagnostics.Assert(false, "null InputObject"); @@ -669,7 +669,7 @@ private PSObject AddProperties(ServiceController service) if (hScManager == IntPtr.Zero) { lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -686,7 +686,7 @@ private PSObject AddProperties(ServiceController service) if (hService == IntPtr.Zero) { lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -695,13 +695,13 @@ private PSObject AddProperties(ServiceController service) ErrorCategory.PermissionDenied); } - NativeMethods.SERVICE_DESCRIPTIONW description = new NativeMethods.SERVICE_DESCRIPTIONW(); + NativeMethods.SERVICE_DESCRIPTIONW description = new(); bool querySuccessful = NativeMethods.QueryServiceConfig2(hService, NativeMethods.SERVICE_CONFIG_DESCRIPTION, out description); - NativeMethods.SERVICE_DELAYED_AUTO_START_INFO autostartInfo = new NativeMethods.SERVICE_DELAYED_AUTO_START_INFO(); + NativeMethods.SERVICE_DELAYED_AUTO_START_INFO autostartInfo = new(); querySuccessful = querySuccessful && NativeMethods.QueryServiceConfig2(hService, NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, out autostartInfo); - NativeMethods.QUERY_SERVICE_CONFIG serviceInfo = new NativeMethods.QUERY_SERVICE_CONFIG(); + NativeMethods.QUERY_SERVICE_CONFIG serviceInfo = new(); querySuccessful = querySuccessful && NativeMethods.QueryServiceConfig(hService, out serviceInfo); if (!querySuccessful) @@ -715,7 +715,7 @@ private PSObject AddProperties(ServiceController service) ); } - PSProperty noteProperty = new PSProperty("UserName", serviceInfo.lpServiceStartName); + PSProperty noteProperty = new("UserName", serviceInfo.lpServiceStartName); serviceAsPSObj.Properties.Add(noteProperty, true); serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#UserName"); @@ -960,7 +960,7 @@ internal List DoStopService(ServiceController serviceControll // Ignore ServiceController.CanStop. CanStop will be set false // if the service is not running, but this is not an error. - List stoppedServices = new List(); + List stoppedServices = new(); ServiceController[] dependentServices = null; try @@ -1705,14 +1705,14 @@ protected override void ProcessRecord() catch (ArgumentException ex) { // cannot use WriteNonterminatingError as service is null - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.ObjectNotFound, Name); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.ObjectNotFound, Name); WriteError(er); return; } catch (InvalidOperationException ex) { // cannot use WriteNonterminatingError as service is null - ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, Name); + ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, Name); WriteError(er); return; } @@ -1740,7 +1740,7 @@ protected override void ProcessRecord() if (hScManager == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -1759,7 +1759,7 @@ protected override void ProcessRecord() if (hService == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -1805,7 +1805,7 @@ protected override void ProcessRecord() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -1816,7 +1816,7 @@ protected override void ProcessRecord() } } - NativeMethods.SERVICE_DESCRIPTIONW sd = new NativeMethods.SERVICE_DESCRIPTIONW(); + NativeMethods.SERVICE_DESCRIPTIONW sd = new(); sd.lpDescription = Description; int size = Marshal.SizeOf(sd); IntPtr buffer = Marshal.AllocCoTaskMem(size); @@ -1830,7 +1830,7 @@ protected override void ProcessRecord() if (!status) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -1840,7 +1840,7 @@ protected override void ProcessRecord() } // Set the delayed auto start - NativeMethods.SERVICE_DELAYED_AUTO_START_INFO ds = new NativeMethods.SERVICE_DELAYED_AUTO_START_INFO(); + NativeMethods.SERVICE_DELAYED_AUTO_START_INFO ds = new(); ds.fDelayedAutostart = StartupType == ServiceStartupType.AutomaticDelayedStart; size = Marshal.SizeOf(ds); delayedAutoStartInfoBuffer = Marshal.AllocCoTaskMem(size); @@ -1854,7 +1854,7 @@ protected override void ProcessRecord() if (!status) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -1914,7 +1914,7 @@ protected override void ProcessRecord() if (PassThru.IsPresent) { // To display the service, refreshing the service would not show the display name after updating - ServiceController displayservice = new ServiceController(Name); + ServiceController displayservice = new(Name); WriteObject(displayservice); } } @@ -1931,7 +1931,7 @@ protected override void ProcessRecord() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -1947,7 +1947,7 @@ protected override void ProcessRecord() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -2136,7 +2136,7 @@ protected override void BeginProcessing() if (hScManager == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -2213,7 +2213,7 @@ protected override void BeginProcessing() if (hService == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -2226,7 +2226,7 @@ protected override void BeginProcessing() } // Set the service description - NativeMethods.SERVICE_DESCRIPTIONW sd = new NativeMethods.SERVICE_DESCRIPTIONW(); + NativeMethods.SERVICE_DESCRIPTIONW sd = new(); sd.lpDescription = Description; int size = Marshal.SizeOf(sd); IntPtr buffer = Marshal.AllocCoTaskMem(size); @@ -2240,7 +2240,7 @@ protected override void BeginProcessing() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -2254,7 +2254,7 @@ protected override void BeginProcessing() // Set the delayed auto start if (StartupType == ServiceStartupType.AutomaticDelayedStart) { - NativeMethods.SERVICE_DELAYED_AUTO_START_INFO ds = new NativeMethods.SERVICE_DELAYED_AUTO_START_INFO(); + NativeMethods.SERVICE_DELAYED_AUTO_START_INFO ds = new(); ds.fDelayedAutostart = true; size = Marshal.SizeOf(ds); delayedAutoStartInfoBuffer = Marshal.AllocCoTaskMem(size); @@ -2268,7 +2268,7 @@ protected override void BeginProcessing() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -2308,7 +2308,7 @@ protected override void BeginProcessing() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -2326,7 +2326,7 @@ protected override void BeginProcessing() if (!succeeded) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( Name, DisplayName, @@ -2402,14 +2402,14 @@ protected override void ProcessRecord() catch (ArgumentException ex) { // Cannot use WriteNonterminatingError as service is null - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.ObjectNotFound, Name); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.ObjectNotFound, Name); WriteError(er); return; } catch (InvalidOperationException ex) { // Cannot use WriteNonterminatingError as service is null - ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, Name); + ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.ObjectNotFound, Name); WriteError(er); return; } @@ -2435,7 +2435,7 @@ protected override void ProcessRecord() if (hScManager == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteObject(exception); WriteNonTerminatingError( service, @@ -2454,7 +2454,7 @@ protected override void ProcessRecord() if (hService == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, @@ -2469,7 +2469,7 @@ protected override void ProcessRecord() if (!status) { int lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new Win32Exception(lastError); + Win32Exception exception = new(lastError); WriteNonTerminatingError( service, exception, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index 42a4624d5dd..b53ffeb01b3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Commands [Alias("scb")] public class SetClipboardCommand : PSCmdlet { - private readonly List _contentList = new List(); + private readonly List _contentList = new(); /// /// Property that sets clipboard content. @@ -84,7 +84,7 @@ private void SetClipboardContent(List contentList, bool append) return; } - StringBuilder content = new StringBuilder(); + StringBuilder content = new(); if (append) { content.AppendLine(Clipboard.GetText()); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs index c92db09507d..44f4d904d33 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs @@ -29,7 +29,7 @@ internal override void BeforeOpenStreams(string[] paths) throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - CmdletProviderContext context = new CmdletProviderContext(GetCurrentContext()); + CmdletProviderContext context = new(GetCurrentContext()); foreach (string path in paths) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index 136818f0200..e6b33142457 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -57,7 +57,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable private static byte[]? s_DefaultSendBuffer; - private readonly CancellationTokenSource _dnsLookupCancel = new CancellationTokenSource(); + private readonly CancellationTokenSource _dnsLookupCancel = new(); private bool _disposed; @@ -293,7 +293,7 @@ private void ProcessConnectionByTCPPort(string targetNameOrAddress) return; } - TcpClient client = new TcpClient(); + TcpClient client = new(); try { @@ -350,11 +350,11 @@ private void ProcessTraceroute(string targetNameOrAddress) } int currentHop = 1; - PingOptions pingOptions = new PingOptions(currentHop, DontFragment.IsPresent); + PingOptions pingOptions = new(currentHop, DontFragment.IsPresent); PingReply reply; PingReply discoveryReply; int timeout = TimeoutSeconds * 1000; - Stopwatch timer = new Stopwatch(); + Stopwatch timer = new(); IPAddress hopAddress; do @@ -436,7 +436,7 @@ private void ProcessTraceroute(string targetNameOrAddress) resolvedTargetName, ex.Message); Exception pingException = new PingException(message, ex.InnerException); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, @@ -499,7 +499,7 @@ private void ProcessMTUSize(string targetNameOrAddress) try { - PingOptions pingOptions = new PingOptions(MaxHops, true); + PingOptions pingOptions = new(MaxHops, true); int retry = 1; while (LowMTUSize < (HighMTUSize - 1)) @@ -535,7 +535,7 @@ private void ProcessMTUSize(string targetNameOrAddress) targetAddress, reply.Status.ToString()); Exception pingException = new PingException(message); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, @@ -560,7 +560,7 @@ private void ProcessMTUSize(string targetNameOrAddress) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, targetAddress, ex.Message); Exception pingException = new PingException(message, ex.InnerException); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, @@ -603,7 +603,7 @@ private void ProcessPing(string targetNameOrAddress) byte[] buffer = GetSendBuffer(BufferSize); PingReply reply; - PingOptions pingOptions = new PingOptions(MaxHops, DontFragment.IsPresent); + PingOptions pingOptions = new(MaxHops, DontFragment.IsPresent); int timeout = TimeoutSeconds * 1000; int delay = Delay * 1000; @@ -617,7 +617,7 @@ private void ProcessPing(string targetNameOrAddress) { string message = StringUtil.Format(TestConnectionResources.NoPingResult, resolvedTargetName, ex.Message); Exception pingException = new PingException(message, ex.InnerException); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, @@ -678,7 +678,7 @@ private bool TryResolveNameOrAddress( resolvedTargetName, TestConnectionResources.TargetAddressAbsent); Exception pingException = new PingException(message, null); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, @@ -722,7 +722,7 @@ private bool TryResolveNameOrAddress( resolvedTargetName, TestConnectionResources.CannotResolveTargetName); Exception pingException = new PingException(message, ex); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, @@ -744,7 +744,7 @@ private bool TryResolveNameOrAddress( resolvedTargetName, TestConnectionResources.TargetAddressAbsent); Exception pingException = new PingException(message, null); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( pingException, TestConnectionExceptionId, ErrorCategory.ResourceUnavailable, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs index 34d9b415619..0289e885e65 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs @@ -254,14 +254,14 @@ protected override void ProcessRecord() try { // construct and populate a new DYNAMIC_TIME_ZONE_INFORMATION structure - NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION(); + NativeMethods.DYNAMIC_TIME_ZONE_INFORMATION dtzi = new(); dtzi.Bias -= (int)InputObject.BaseUtcOffset.TotalMinutes; dtzi.StandardName = InputObject.StandardName; dtzi.DaylightName = InputObject.DaylightName; dtzi.TimeZoneKeyName = InputObject.Id; // Request time zone transition information for the current year - NativeMethods.TIME_ZONE_INFORMATION tzi = new NativeMethods.TIME_ZONE_INFORMATION(); + NativeMethods.TIME_ZONE_INFORMATION tzi = new(); if (!NativeMethods.GetTimeZoneInformationForYear((ushort)DateTime.Now.Year, ref dtzi, ref tzi)) { ThrowWin32Error(); @@ -343,7 +343,7 @@ protected bool HasAccess try { // setup the privileges being checked - NativeMethods.PRIVILEGE_SET ps = new NativeMethods.PRIVILEGE_SET() + NativeMethods.PRIVILEGE_SET ps = new() { PrivilegeCount = 1, Control = 1, @@ -390,7 +390,7 @@ protected void SetAccessToken(bool enable) try { // setup the privileges being requested - NativeMethods.TOKEN_PRIVILEGES tp = new NativeMethods.TOKEN_PRIVILEGES() + NativeMethods.TOKEN_PRIVILEGES tp = new() { PrivilegeCount = 1, Luid = 0, @@ -779,8 +779,8 @@ internal static class TimeZoneHelper /// A TimeZoneInfo object array containing information about the specified system time zones. internal static TimeZoneInfo[] LookupSystemTimeZoneInfoByName(string name) { - WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); - List tzi = new List(); + WildcardPattern namePattern = new(name, WildcardOptions.IgnoreCase); + List tzi = new(); // get the available system time zones ReadOnlyCollection zones = TimeZoneInfo.GetSystemTimeZones(); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index 90b55c0474e..25ecd672c4c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -143,7 +143,7 @@ protected override void ProcessRecord() catch (Exception e) // Catch-all OK. 3rd party callout { ProviderInvocationException providerException = - new ProviderInvocationException( + new( "ProviderContentWriteError", SessionStateStrings.ProviderContentWriteError, holder.PathInfo.Provider, @@ -258,7 +258,7 @@ internal List GetContentWriters( // Create the results array - List results = new List(); + List results = new(); foreach (PathInfo pathInfo in pathInfos) { @@ -311,7 +311,7 @@ internal List GetContentWriters( if (writers.Count == 1 && writers[0] != null) { ContentHolder holder = - new ContentHolder(pathInfo, null, writers[0]); + new(pathInfo, null, writers[0]); results.Add(holder); } From 9272c5b51c97307b8551796cfa54e62759041041 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 03:13:30 +0000 Subject: [PATCH 070/138] Fix IDE0090: Simplify new expression part 4.2 (#14256) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../BasicHtmlWebResponseObject.Common.cs | 8 ++--- .../WebCmdlet/Common/ContentHelper.Common.cs | 2 +- .../Common/InvokeRestMethodCommand.Common.cs | 4 +-- .../Common/WebRequestPSCmdlet.Common.cs | 34 +++++++++---------- .../WebCmdlet/ConvertFromJsonCommand.cs | 2 +- .../utility/WebCmdlet/ConvertToJsonCommand.cs | 4 +-- .../commands/utility/WebCmdlet/JsonObject.cs | 8 ++--- .../commands/utility/WebCmdlet/PSUserAgent.cs | 4 +-- .../utility/WebCmdlet/StreamHelper.cs | 10 +++--- 9 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 76d5283f797..969dd8231c8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -87,7 +87,7 @@ public WebCmdletElementCollection InputFields { EnsureHtmlParser(); - List parsedFields = new List(); + List parsedFields = new(); MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content); foreach (Match field in fieldMatch) { @@ -114,7 +114,7 @@ public WebCmdletElementCollection Links { EnsureHtmlParser(); - List parsedLinks = new List(); + List parsedLinks = new(); MatchCollection linkMatch = s_linkRegex.Matches(Content); foreach (Match link in linkMatch) { @@ -141,7 +141,7 @@ public WebCmdletElementCollection Images { EnsureHtmlParser(); - List parsedImages = new List(); + List parsedImages = new(); MatchCollection imageMatch = s_imageRegex.Matches(Content); foreach (Match image in imageMatch) { @@ -187,7 +187,7 @@ protected void InitializeContent() private static PSObject CreateHtmlObject(string html, string tagName) { - PSObject elementObject = new PSObject(); + PSObject elementObject = new(); elementObject.Properties.Add(new PSNoteProperty("outerHTML", html)); elementObject.Properties.Add(new PSNoteProperty("tagName", tagName)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index 5d1b7c66048..f16ad99d2a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -68,7 +68,7 @@ internal static Encoding GetEncodingOrDefault(string characterSet) internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { - StringBuilder raw = new StringBuilder(); + StringBuilder raw = new(); string protocol = WebResponseHelper.GetProtocol(response); if (!string.IsNullOrEmpty(protocol)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 85073a911cd..235aaf82773 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -110,7 +110,7 @@ private bool TryProcessFeedStream(Stream responseStream) if (isRssOrFeed) { - XmlDocument workingDocument = new XmlDocument(); + XmlDocument workingDocument = new(); // performing a Read() here to avoid rrechecking // "rss" or "feed" items reader.Read(); @@ -145,7 +145,7 @@ private bool TryProcessFeedStream(Stream responseStream) // Mostly cribbed from Serialization.cs#GetXmlReaderSettingsForCliXml() private static XmlReaderSettings GetSecureXmlReaderSettings() { - XmlReaderSettings xrs = new XmlReaderSettings(); + XmlReaderSettings xrs = new(); xrs.CheckCharacters = false; xrs.CloseInput = false; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 5cf9eff79c7..144c4cc9f3c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -606,13 +606,13 @@ internal virtual void PrepareSession() if (CertificateThumbprint != null) { - X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); + X509Store store = new(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); if (tbCollection.Count == 0) { - CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound); + CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound); throw ex; } @@ -639,7 +639,7 @@ internal virtual void PrepareSession() if (Proxy != null) { - WebProxy webProxy = new WebProxy(Proxy); + WebProxy webProxy = new(Proxy); webProxy.BypassProxyOnLocal = false; if (ProxyCredential != null) { @@ -733,7 +733,7 @@ private Uri PrepareUri(Uri uri) && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) { - UriBuilder uriBuilder = new UriBuilder(uri); + UriBuilder uriBuilder = new(uri); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) { uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan().Slice(1), "&", FormatDictionary(bodyAsDictionary)); @@ -774,7 +774,7 @@ private static string FormatDictionary(IDictionary content) if (content == null) throw new ArgumentNullException(nameof(content)); - StringBuilder bodyBuilder = new StringBuilder(); + StringBuilder bodyBuilder = new(); foreach (string key in content.Keys) { if (bodyBuilder.Length > 0) @@ -984,7 +984,7 @@ private HttpMethod GetHttpMethod(WebRequestMethod method) internal virtual HttpClient GetHttpClient(bool handleRedirect) { // By default the HttpClientHandler will automatically decompress GZip and Deflate content - HttpClientHandler handler = new HttpClientHandler(); + HttpClientHandler handler = new(); handler.CookieContainer = WebSession.Cookies; // set the credentials used by this request @@ -1037,7 +1037,7 @@ internal virtual HttpClient GetHttpClient(bool handleRedirect) handler.SslProtocols = (SslProtocols)SslProtocol; - HttpClient httpClient = new HttpClient(handler); + HttpClient httpClient = new(handler); // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) if (TimeoutSec == 0) @@ -1284,7 +1284,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) catch (FormatException ex) { var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new ErrorRecord(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } @@ -1540,8 +1540,8 @@ protected override void ProcessRecord() { string message = string.Format(CultureInfo.CurrentCulture, WebCmdletStrings.ResponseStatusCodeFailure, (int)response.StatusCode, response.ReasonPhrase); - HttpResponseException httpEx = new HttpResponseException(message, response); - ErrorRecord er = new ErrorRecord(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + HttpResponseException httpEx = new(message, response); + ErrorRecord er = new(httpEx, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); string detailMsg = string.Empty; StreamReader reader = null; try @@ -1588,7 +1588,7 @@ protected override void ProcessRecord() response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.MovedPermanently) { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); + ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); WriteError(er); } @@ -1596,7 +1596,7 @@ protected override void ProcessRecord() } catch (HttpRequestException ex) { - ErrorRecord er = new ErrorRecord(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); + ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); if (ex.InnerException != null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); @@ -1622,12 +1622,12 @@ protected override void ProcessRecord() } catch (CryptographicException ex) { - ErrorRecord er = new ErrorRecord(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); + ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); ThrowTerminatingError(er); } catch (NotSupportedException ex) { - ErrorRecord er = new ErrorRecord(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); + ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); ThrowTerminatingError(er); } } @@ -1707,7 +1707,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) if (!SkipHeaderValidation) { var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new ErrorRecord(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } @@ -1716,7 +1716,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) if (!SkipHeaderValidation) { var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new ErrorRecord(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } @@ -1846,7 +1846,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr string rel = match.Groups["rel"].Value; if (url != string.Empty && rel != string.Empty && !_relationLink.ContainsKey(rel)) { - Uri absoluteUri = new Uri(requestUri, url); + Uri absoluteUri = new(requestUri, url); _relationLink.Add(rel, absoluteUri.AbsoluteUri); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs index e0c60ca8f3e..0af97b061a9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -27,7 +27,7 @@ public class ConvertFromJsonCommand : Cmdlet /// /// InputObjectBuffer buffers all InputObject contents available in the pipeline. /// - private readonly List _inputObjectBuffer = new List(); + private readonly List _inputObjectBuffer = new(); /// /// Returned data structure is a Hashtable instead a CustomPSObject. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index b741825e7e0..d15303557eb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -29,7 +29,7 @@ public class ConvertToJsonCommand : PSCmdlet private const int maxDepthAllowed = 100; - private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource(); + private readonly CancellationTokenSource _cancellationSource = new(); /// /// Gets or sets the Depth property. @@ -93,7 +93,7 @@ protected override void BeginProcessing() } } - private readonly List _inputObjects = new List(); + private readonly List _inputObjects = new(); /// /// Caching the input objects for the command. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 7e5a4ba6d63..9f1d2b1c8a2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -344,7 +344,7 @@ private static ICollection PopulateFromJArray(JArray list, out ErrorReco private static Hashtable PopulateHashTableFromJDictionary(JObject entries, out ErrorRecord error) { error = null; - Hashtable result = new Hashtable(entries.Count); + Hashtable result = new(entries.Count); foreach (var entry in entries) { // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject @@ -708,7 +708,7 @@ private static void AppendPsProperties(PSObject psObj, IDictionary receiver, int /// private static object ProcessDictionary(IDictionary dict, int depth, in ConvertToJsonContext context) { - Dictionary result = new Dictionary(dict.Count); + Dictionary result = new(dict.Count); foreach (DictionaryEntry entry in dict) { @@ -745,7 +745,7 @@ private static object ProcessDictionary(IDictionary dict, int depth, in ConvertT /// private static object ProcessEnumerable(IEnumerable enumerable, int depth, in ConvertToJsonContext context) { - List result = new List(); + List result = new(); foreach (object o in enumerable) { @@ -765,7 +765,7 @@ private static object ProcessEnumerable(IEnumerable enumerable, int depth, in Co /// private static object ProcessCustomObject(object o, int depth, in ConvertToJsonContext context) { - Dictionary result = new Dictionary(); + Dictionary result = new(); Type t = o.GetType(); foreach (FieldInfo info in t.GetFields(BindingFlags.Public | BindingFlags.Instance)) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index a730c043216..2ea29e73fa3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -131,9 +131,9 @@ internal static string PlatformName if (s_windowsUserAgent == null) { // find the version in the windows operating system description - Regex pattern = new Regex(@"\d+(\.\d+)+"); + Regex pattern = new(@"\d+(\.\d+)+"); string versionText = pattern.Match(OS).Value; - Version windowsPlatformversion = new Version(versionText); + Version windowsPlatformversion = new(versionText); s_windowsUserAgent = $"Windows NT {windowsPlatformversion.Major}.{windowsPlatformversion.Minor}"; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index bae35ac3818..43b625311b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -220,7 +220,7 @@ private void Initialize() { long totalLength = 0; byte[] buffer = new byte[StreamHelper.ChunkSize]; - ProgressRecord record = new ProgressRecord(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); + ProgressRecord record = new(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); for (int read = 1; read > 0; totalLength += read) { if (_ownerCmdlet != null) @@ -285,7 +285,7 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, Task copyTask = input.CopyToAsync(output, cancellationToken); - ProgressRecord record = new ProgressRecord( + ProgressRecord record = new( ActivityId, WebCmdletStrings.WriteRequestProgressActivity, WebCmdletStrings.WriteRequestProgressStatus); @@ -323,13 +323,13 @@ internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet c { // If the web cmdlet should resume, append the file instead of overwriting. FileMode fileMode = cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume ? FileMode.Append : FileMode.Create; - using FileStream output = new FileStream(filePath, fileMode, FileAccess.Write, FileShare.Read); + using FileStream output = new(filePath, fileMode, FileAccess.Write, FileShare.Read); WriteToStream(stream, output, cmdlet, cancellationToken); } private static string StreamToString(Stream stream, Encoding encoding) { - StringBuilder result = new StringBuilder(capacity: ChunkSize); + StringBuilder result = new(capacity: ChunkSize); Decoder decoder = encoding.GetDecoder(); int useBufferSize = 64; @@ -411,7 +411,7 @@ internal static bool TryGetEncoding(string characterSet, out Encoding encoding) return result; } - private static readonly Regex s_metaexp = new Regex( + private static readonly Regex s_metaexp = new( @"<]*charset\s*=\s*[""'\n]?(?[A-Za-z].[^\s""'\n<>]*)[\s""'\n>]", RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase ); From 9b3684186e3160b1798e435c947b5b09f4684e8d Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 03:15:37 +0000 Subject: [PATCH 071/138] Fix IDE0090: Simplify new expression part 4.3 (#14257) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../utility/trace/MshHostTraceListener.cs | 2 +- .../commands/utility/trace/TraceCommandBase.cs | 6 +++--- .../utility/trace/TraceExpressionCommand.cs | 2 +- .../utility/trace/TraceListenerCommandBase.cs | 16 ++++++++-------- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index 19cfd7c7e20..357e0222b6d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -87,7 +87,7 @@ public override void Write(string output) } } - private readonly StringBuilder _cachedWrite = new StringBuilder(); + private readonly StringBuilder _cachedWrite = new(); /// /// Sends the given output string to the host for processing. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs index 4cdee2a1517..9118fd773fd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs @@ -56,7 +56,7 @@ internal Collection GetMatchingTraceSource( { notMatched = new Collection(); - Collection results = new Collection(); + Collection results = new(); foreach (string patternToMatch in patternsToMatch) { bool matchFound = false; @@ -102,12 +102,12 @@ internal Collection GetMatchingTraceSource( !WildcardPattern.ContainsWildcardCharacters(patternToMatch)) { ItemNotFoundException itemNotFound = - new ItemNotFoundException( + new( patternToMatch, "TraceSourceNotFound", SessionStateStrings.TraceSourceNotFound); - ErrorRecord errorRecord = new ErrorRecord(itemNotFound.ErrorRecord, itemNotFound); + ErrorRecord errorRecord = new(itemNotFound.ErrorRecord, itemNotFound); WriteError(errorRecord); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index 97a398425d1..8179b9179d1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -541,6 +541,6 @@ private static ErrorRecord ConvertToErrorRecord(object obj) private readonly TraceListenerCommandBase _cmdlet; private readonly bool _writeError; private bool _isOpen = true; - private readonly Collection _matchingSources = new Collection(); + private readonly Collection _matchingSources = new(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs index d57c117ce43..abdb6ae17bc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -229,7 +229,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc try { - Collection resolvedPaths = new Collection(); + Collection resolvedPaths = new(); try { // Resolve the file path @@ -287,7 +287,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc if (ForceWrite && System.IO.File.Exists(resolvedPath)) { // remove readonly attributes on the file - System.IO.FileInfo fInfo = new System.IO.FileInfo(resolvedPath); + System.IO.FileInfo fInfo = new(resolvedPath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. @@ -300,13 +300,13 @@ internal void AddTraceListenersToSources(Collection matchingSourc } // Trace commands always append..So there is no need to set overwrite with force.. - FileStream fileStream = new FileStream(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); + FileStream fileStream = new(resolvedPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); FileStreams.Add(fileStream); // Open the file stream TextWriterTraceListener fileListener = - new TextWriterTraceListener(fileStream, resolvedPath); + new(fileStream, resolvedPath); fileListener.Name = FileListener; @@ -328,7 +328,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc if (fileOpenError != null) { ErrorRecord errorRecord = - new ErrorRecord( + new( fileOpenError, "FileListenerPathResolutionFailed", ErrorCategory.OpenError, @@ -353,7 +353,7 @@ internal void AddTraceListenersToSources(Collection matchingSourc if (error != null) { ErrorRecord errorRecord = - new ErrorRecord( + new( error, "FileListenerPathResolutionFailed", ErrorCategory.InvalidArgument, @@ -491,7 +491,7 @@ internal void TurnOnTracing(Collection matchingSources, bool preC { // Copy the listeners into a different collection - Collection listenerCollection = new Collection(); + Collection listenerCollection = new(); foreach (TraceListener listener in source.Listeners) { listenerCollection.Add(listener); @@ -596,7 +596,7 @@ protected void ClearStoredState() } private readonly Dictionary>> _storedTraceSourceState = - new Dictionary>>(); + new(); #endregion stored state } From edb70b19920e758e30a6a2426b0c0c003911d707 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 03:17:15 +0000 Subject: [PATCH 072/138] Fix IDE0090: Simplify new expression part 4.5 (#14259) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../commands/utility/GetRunspaceCommand.cs | 6 +- .../commands/utility/GetVerbCommand.cs | 2 +- .../commands/utility/Group-Object.cs | 22 +++--- .../utility/ImplicitRemotingCommands.cs | 74 +++++++++---------- .../commands/utility/Import-LocalizedData.cs | 6 +- .../commands/utility/ImportAliasCommand.cs | 24 +++--- .../commands/utility/Join-String.cs | 2 +- .../utility/MarkdownOptionCommands.cs | 2 +- .../commands/utility/MatchString.cs | 20 ++--- .../commands/utility/Measure-Object.cs | 14 ++-- .../commands/utility/New-Object.cs | 4 +- .../commands/utility/NewAliasCommand.cs | 4 +- .../utility/NewTemporaryFileCommand.cs | 2 +- .../commands/utility/ObjectCommandComparer.cs | 4 +- .../commands/utility/OrderObjectBase.cs | 30 ++++---- .../utility/PSBreakpointUpdaterCommandBase.cs | 2 +- .../commands/utility/ReadConsoleCmdlet.cs | 6 +- .../utility/RegisterPSEventCommand.cs | 2 +- .../commands/utility/RemoveAliasCommand.cs | 4 +- .../commands/utility/RemoveEventCommand.cs | 4 +- 20 files changed, 117 insertions(+), 117 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs index 0aedd4c9d06..10c050a4562 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs @@ -126,7 +126,7 @@ internal static IReadOnlyList GetAllRunspaces() internal static IReadOnlyList GetRunspacesByName(string[] names) { - List rtnRunspaces = new List(); + List rtnRunspaces = new(); IReadOnlyList runspaces = Runspace.RunspaceList; foreach (string name in names) @@ -146,7 +146,7 @@ internal static IReadOnlyList GetRunspacesByName(string[] names) internal static IReadOnlyList GetRunspacesById(int[] ids) { - List rtnRunspaces = new List(); + List rtnRunspaces = new(); foreach (int id in ids) { @@ -167,7 +167,7 @@ internal static IReadOnlyList GetRunspacesById(int[] ids) internal static IReadOnlyList GetRunspacesByInstanceId(Guid[] instanceIds) { - List rtnRunspaces = new List(); + List rtnRunspaces = new(); IReadOnlyList runspaces = Runspace.RunspaceList; foreach (Guid instanceId in instanceIds) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs index 6794e15c1d1..1ec93b0f1d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -70,7 +70,7 @@ protected override void ProcessRecord() } } - VerbInfo verb = new VerbInfo(); + VerbInfo verb = new(); verb.Verb = field.Name; verb.AliasPrefix = VerbAliasPrefixes.GetVerbAliasPrefix(field.Name); verb.Group = groupName; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs index 3a8117858bd..d63ff694281 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -140,7 +140,7 @@ internal virtual void Add(PSObject groupValue) private static string BuildName(List propValues) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); foreach (ObjectCommandPropertyValue propValue in propValues) { var propValuePropertyValue = propValue?.PropertyValue; @@ -176,7 +176,7 @@ public ArrayList Values { get { - ArrayList values = new ArrayList(); + ArrayList values = new(); foreach (ObjectCommandPropertyValue propValue in GroupValue.orderValues) { values.Add(propValue.PropertyValue); @@ -248,10 +248,10 @@ public class GroupObjectCommand : ObjectBase [Parameter(ParameterSetName = "HashTable")] public SwitchParameter AsString { get; set; } - private readonly List _groups = new List(); - private readonly OrderByProperty _orderByProperty = new OrderByProperty(); - private readonly Dictionary _tupleToGroupInfoMappingDictionary = new Dictionary(); - private readonly List _entriesToOrder = new List(); + private readonly List _groups = new(); + private readonly OrderByProperty _orderByProperty = new(); + private readonly Dictionary _tupleToGroupInfoMappingDictionary = new(); + private readonly List _entriesToOrder = new(); private OrderByPropertyComparer _orderByPropertyComparer; private bool _hasProcessedFirstInputObject; private bool _hasDifferentValueTypes; @@ -375,7 +375,7 @@ private static void DoOrderedGrouping( private void WriteNonTerminatingError(Exception exception, string resourceIdAndErrorId, ErrorCategory category) { - Exception ex = new Exception(StringUtil.Format(resourceIdAndErrorId), exception); + Exception ex = new(StringUtil.Format(resourceIdAndErrorId), exception); WriteError(new ErrorRecord(ex, resourceIdAndErrorId, category, null)); } @@ -401,15 +401,15 @@ protected override void ProcessRecord() if (AsString && !AsHashTable) { - ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectWithHashTable); - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, AsString); + ArgumentException ex = new(UtilityCommonStrings.GroupObjectWithHashTable); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, AsString); ThrowTerminatingError(er); } if (AsHashTable && !AsString && (Property != null && (Property.Length > 1 || _orderByProperty.MshParameterList.Count > 1))) { - ArgumentException ex = new ArgumentException(UtilityCommonStrings.GroupObjectSingleProperty); - ErrorRecord er = new ErrorRecord(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property); + ArgumentException ex = new(UtilityCommonStrings.GroupObjectSingleProperty); + ErrorRecord er = new(ex, "ArgumentException", ErrorCategory.InvalidArgument, Property); ThrowTerminatingError(er); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index b32ed855e60..d5d283062b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -127,7 +127,7 @@ protected override void BeginProcessing() if (IsModuleSpecified && IsFullyQualifiedModuleSpecified) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, nameof(Module), nameof(FullyQualifiedModule)); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); + ErrorRecord error = new(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } @@ -289,7 +289,7 @@ protected override void BeginProcessing() if (IsModuleSpecified && IsFullyQualifiedModuleSpecified) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, nameof(Module), nameof(FullyQualifiedModule)); - ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); + ErrorRecord error = new(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null); ThrowTerminatingError(error); } @@ -563,7 +563,7 @@ private ErrorRecord GetErrorNoCommandsImportedBecauseOfSkipping() ErrorDetails details = this.GetErrorDetails(errorId); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(details.Message), errorId, ErrorCategory.InvalidResult, @@ -584,7 +584,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) ErrorDetails details = this.GetErrorDetails(errorId, commandName); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(details.Message), errorId, ErrorCategory.InvalidResult, @@ -605,7 +605,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames ErrorDetails details = this.GetErrorDetails(errorId, commandNames); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidData, @@ -626,7 +626,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) ErrorDetails details = this.GetErrorDetails(errorId, commandName); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.ResourceExists, @@ -647,7 +647,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) ErrorDetails details = this.GetErrorDetails(errorId, typeName); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.ResourceExists, @@ -668,7 +668,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) ErrorDetails details = this.GetErrorDetails(errorId, commandName); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidData, @@ -700,7 +700,7 @@ private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, stri ErrorDetails details = this.GetErrorDetails(errorId, commandName, name); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidData, @@ -775,7 +775,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) ErrorDetails details = this.GetErrorDetails(errorId, aliasName); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(details.Message), errorId, ErrorCategory.OperationTimeout, @@ -796,7 +796,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) ErrorDetails details = this.GetErrorDetails(errorId, commandName); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(details.Message), errorId, ErrorCategory.InvalidResult, @@ -806,7 +806,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) return errorRecord; } - private readonly List _commandsSkippedBecauseOfShadowing = new List(); + private readonly List _commandsSkippedBecauseOfShadowing = new(); private void ReportSkippedCommands() { @@ -847,7 +847,7 @@ private Dictionary ExistingCommands if (_existingCommands == null) { _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); - CommandSearcher searcher = new CommandSearcher( + CommandSearcher searcher = new( "*", SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, CommandTypes.All, @@ -866,7 +866,7 @@ private bool IsShadowingExistingCommands(string commandName) { commandName = ModuleCmdletBase.AddPrefixToCommandName(commandName, this.Prefix); - CommandSearcher searcher = new CommandSearcher(commandName, SearchResolutionOptions.None, CommandTypes.All, this.Context); + CommandSearcher searcher = new(commandName, SearchResolutionOptions.None, CommandTypes.All, this.Context); foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(commandName)) { if (this.ExistingCommands.ContainsKey(expandedCommandName)) @@ -1076,7 +1076,7 @@ private Dictionary RehydrateDictionary(string commandName, PSObject valueRehydrator = (PSObject pso) => ConvertTo(commandName, pso); } - Dictionary result = new Dictionary(); + Dictionary result = new(); PSPropertyInfo deserializedDictionaryProperty = deserializedObject.Properties[propertyName]; if (deserializedDictionaryProperty != null) { @@ -1294,8 +1294,8 @@ private ParameterMetadata RehydrateParameterMetadata(PSObject deserializedParame Type parameterType = RehydrateParameterType(deserializedParameterMetadata); List aliases = RehydrateList("Get-Command", deserializedParameterMetadata, "Aliases", null); - ParameterSetMetadata parameterSetMetadata = new ParameterSetMetadata(int.MinValue, 0, null); - Dictionary parameterSets = new Dictionary(StringComparer.OrdinalIgnoreCase); + ParameterSetMetadata parameterSetMetadata = new(int.MinValue, 0, null); + Dictionary parameterSets = new(StringComparer.OrdinalIgnoreCase); parameterSets.Add(ParameterAttribute.AllParameterSets, parameterSetMetadata); return new ParameterMetadata( @@ -1349,7 +1349,7 @@ private CommandMetadata RehydrateCommandMetadata(PSObject deserializedCommandInf // add client-side AsJob parameter parameters.Remove("AsJob"); - ParameterMetadata asJobParameter = new ParameterMetadata("AsJob", typeof(SwitchParameter)); + ParameterMetadata asJobParameter = new("AsJob", typeof(SwitchParameter)); parameters.Add(asJobParameter.Name, asJobParameter); return new CommandMetadata( @@ -1622,12 +1622,12 @@ internal List GetRemoteFormatData() { DateTime startTime = DateTime.UtcNow; - PSDataCollection asyncOutput = new PSDataCollection(); + PSDataCollection asyncOutput = new(); // process output and errors as soon as possible asyncResult = powerShell.BeginInvoke(null, asyncOutput); int numberOfReceivedObjects = 0; - List result = new List(); + List result = new(); foreach (PSObject deserializedFormatData in asyncOutput) { AddRemoteTypeDefinition(result, deserializedFormatData); @@ -1733,14 +1733,14 @@ internal List GetRemoteCommandMetadata(out Dictionary name2commandMetadata = - new Dictionary(StringComparer.OrdinalIgnoreCase); + new(StringComparer.OrdinalIgnoreCase); // invoke using (new PowerShellStopper(this.Context, powerShell)) { DateTime startTime = DateTime.UtcNow; - PSDataCollection asyncOutput = new PSDataCollection(); + PSDataCollection asyncOutput = new(); // process output and errors as soon as possible asyncResult = powerShell.BeginInvoke(null, asyncOutput); @@ -1815,7 +1815,7 @@ private void WriteProgress(string statusDescription, int? percentComplete, int? _lastTimeProgressWasWritten = DateTime.UtcNow; string activityDescription = StringUtil.Format(ImplicitRemotingStrings.ProgressActivity); - ProgressRecord progressRecord = new ProgressRecord( + ProgressRecord progressRecord = new( 1905347799, // unique id for ImplicitRemoting (I just picked a random number) activityDescription, statusDescription); @@ -1890,7 +1890,7 @@ internal List GenerateProxyModule( } } - ImplicitRemotingCodeGenerator codeGenerator = new ImplicitRemotingCodeGenerator( + ImplicitRemotingCodeGenerator codeGenerator = new( this.Session, this.ModuleGuid, this.MyInvocation); @@ -1915,7 +1915,7 @@ internal List GenerateProxyModule( internal class ImplicitRemotingCodeGenerator { - internal static readonly Version VersionOfScriptWriter = new Version(1, 0); + internal static readonly Version VersionOfScriptWriter = new(1, 0); #region Constructor and shared private data @@ -1982,7 +1982,7 @@ private static string EscapeFunctionNameForRemoteHelp(string name) throw PSTraceSource.NewArgumentNullException(nameof(name)); } - StringBuilder result = new StringBuilder(name.Length); + StringBuilder result = new(name.Length); foreach (char c in name) { if (("\"'`$".IndexOf(c) == (-1)) && @@ -2247,7 +2247,7 @@ private PSPrimitiveDictionary GetApplicationArguments() private string GenerateNewPSSessionOption() { - StringBuilder result = new StringBuilder("& $script:NewPSSessionOption "); + StringBuilder result = new("& $script:NewPSSessionOption "); RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; if (runspaceConnectionInfo != null) @@ -2455,7 +2455,7 @@ private void GenerateHelperFunctionsGetImplicitRunspace(TextWriter writer) private string GenerateReimportingOfModules() { - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); if (_invocationInfo.BoundParameters.ContainsKey(nameof(Module))) { @@ -2921,7 +2921,7 @@ private static List GetListOfCommandNames(IEnumerable l throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); } - List listOfCommandNames = new List(); + List listOfCommandNames = new(); foreach (CommandMetadata commandMetadata in listOfCommandMetadata) { listOfCommandNames.Add(commandMetadata.Name); @@ -2937,7 +2937,7 @@ private static string GenerateArrayString(IEnumerable listOfStrings) throw PSTraceSource.NewArgumentNullException(nameof(listOfStrings)); } - StringBuilder arrayString = new StringBuilder(); + StringBuilder arrayString = new(); foreach (string s in listOfStrings) { if (arrayString.Length != 0) @@ -3003,7 +3003,7 @@ private static void GenerateFormatFile(TextWriter writer, List GenerateProxyModule( List listOfFormatData, X509Certificate2 certificate) { - List result = new List(); + List result = new(); Dbg.Assert(moduleRootDirectory != null, "Caller should validate moduleRootDirectory != null"); Dbg.Assert(Directory.Exists(moduleRootDirectory.FullName), "Caller should validate moduleRootDirectory exists"); @@ -3048,7 +3048,7 @@ internal List GenerateProxyModule( FileMode fileMode = force ? FileMode.OpenOrCreate : FileMode.CreateNew; result.Add(baseName + ".psm1"); - FileStream psm1 = new FileStream( + FileStream psm1 = new( baseName + ".psm1", fileMode, FileAccess.Write, @@ -3069,7 +3069,7 @@ internal List GenerateProxyModule( } result.Add(baseName + ".format.ps1xml"); - FileStream formatPs1xml = new FileStream( + FileStream formatPs1xml = new( baseName + ".format.ps1xml", fileMode, FileAccess.Write, @@ -3114,8 +3114,8 @@ internal List GenerateProxyModule( } result.Add(baseName + ".psd1"); - FileInfo manifestFile = new FileInfo(baseName + ".psd1"); - FileStream psd1 = new FileStream( + FileInfo manifestFile = new(baseName + ".psd1"); + FileStream psd1 = new( manifestFile.FullName, fileMode, FileAccess.Write, @@ -3135,7 +3135,7 @@ internal List GenerateProxyModule( using (var stream = new FileStream(applicationArgumentsFile, FileMode.Create, FileAccess.Write, FileShare.Read)) using (var xmlWriter = XmlWriter.Create(stream)) { - Serializer serializer = new Serializer(xmlWriter); + Serializer serializer = new(xmlWriter); serializer.Serialize(applicationArguments); serializer.Done(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index 4749d28322c..53ab8d32c2f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -186,7 +186,7 @@ protected override void ProcessRecord() if (_bindingVariable != null) { - VariablePath variablePath = new VariablePath(_bindingVariable); + VariablePath variablePath = new(_bindingVariable); if (variablePath.IsUnscopedVariable) { variablePath = variablePath.CloneAndSetLocal(); @@ -340,8 +340,8 @@ private string GetScript(string filePath) // 197751: WR BUG BASH: Powershell: localized text display as garbage // leaving the encoding to be decided by the StreamReader. StreamReader // will read the preamble and decide proper encoding. - using (FileStream scriptStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) - using (StreamReader scriptReader = new StreamReader(scriptStream)) + using (FileStream scriptStream = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (StreamReader scriptReader = new(scriptStream)) { return scriptReader.ReadToEnd(); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index 3da62e88d25..4252a1623d6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -154,7 +154,7 @@ protected override void ProcessRecord() // Since the alias already exists, write an error. SessionStateException aliasExists = - new SessionStateException( + new( alias.Name, SessionStateCategory.Alias, "AliasAlreadyExists", @@ -233,7 +233,7 @@ private Dictionary ExistingCommands if (_existingCommands == null) { _existingCommands = new Dictionary(StringComparer.OrdinalIgnoreCase); - CommandSearcher searcher = new CommandSearcher( + CommandSearcher searcher = new( "*", SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveAliasPatterns | SearchResolutionOptions.ResolveFunctionPatterns, CommandTypes.All ^ CommandTypes.Alias, @@ -260,7 +260,7 @@ private Dictionary ExistingCommands private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName) { - CommandSearcher searcher = new CommandSearcher(aliasName, SearchResolutionOptions.None, CommandTypes.All ^ CommandTypes.Alias, this.Context); + CommandSearcher searcher = new(aliasName, SearchResolutionOptions.None, CommandTypes.All ^ CommandTypes.Alias, this.Context); foreach (string expandedCommandName in searcher.ConstructSearchPatternsFromName(aliasName)) { CommandTypes commandTypeOfExistingCommand; @@ -268,7 +268,7 @@ private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName) { // Since the alias already exists, write an error. SessionStateException aliasExists = - new SessionStateException( + new( aliasName, SessionStateCategory.Alias, "AliasAlreadyExists", @@ -289,12 +289,12 @@ private bool VerifyShadowingExistingCommandsAndWriteError(string aliasName) private Collection GetAliasesFromFile(bool isLiteralPath) { - Collection result = new Collection(); + Collection result = new(); string filePath = null; using (StreamReader reader = OpenFile(out filePath, isLiteralPath)) { - CSVHelper csvHelper = new CSVHelper(','); + CSVHelper csvHelper = new(','); Int64 lineNumber = 0; string line = null; @@ -327,10 +327,10 @@ private Collection GetAliasesFromFile(bool isLiteralPath) string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileInvalidFormat, filePath, lineNumber); FormatException formatException = - new FormatException(message); + new(message); ErrorRecord errorRecord = - new ErrorRecord( + new( formatException, "ImportAliasFileFormatError", ErrorCategory.ReadError, @@ -352,7 +352,7 @@ private Collection GetAliasesFromFile(bool isLiteralPath) string message = StringUtil.Format(AliasCommandStrings.ImportAliasOptionsError, filePath, lineNumber); ErrorRecord errorRecord = - new ErrorRecord( + new( argException, "ImportAliasOptionsError", ErrorCategory.ReadError, @@ -364,7 +364,7 @@ private Collection GetAliasesFromFile(bool isLiteralPath) } AliasInfo newAlias = - new AliasInfo( + new( values[0], values[1], Context, @@ -427,7 +427,7 @@ private StreamReader OpenFile(out string filePath, bool isLiteralPath) try { - FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + FileStream file = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); result = new StreamReader(file); } catch (IOException ioException) @@ -451,7 +451,7 @@ private void ThrowFileOpenError(Exception e, string pathWithError) string message = StringUtil.Format(AliasCommandStrings.ImportAliasFileOpenFailed, pathWithError, e.Message); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( e, "FileOpenFailure", ErrorCategory.OpenError, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs index cab826691c9..16243fcf6ae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -23,7 +23,7 @@ public sealed class JoinStringCommand : PSCmdlet /// A bigger default to not get re-allocations in common use cases. private const int DefaultOutputStringCapacity = 256; - private readonly StringBuilder _outputBuilder = new StringBuilder(DefaultOutputStringCapacity); + private readonly StringBuilder _outputBuilder = new(DefaultOutputStringCapacity); private CultureInfo _cultureInfo = CultureInfo.InvariantCulture; private string _separator; private char _quoteChar; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs index d1e1b73c173..cd18f33c41d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -155,7 +155,7 @@ protected override void EndProcessing() { var errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(errorMessage), "InvalidObject", ErrorCategory.InvalidArgument, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index cb449a309e3..6271e6f57b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -275,7 +275,7 @@ private string ToString(string directory, string line) } // Otherwise, render the full context. - List lines = new List(Context.DisplayPreContext.Length + Context.DisplayPostContext.Length + 1); + List lines = new(Context.DisplayPreContext.Length + Context.DisplayPostContext.Length + 1); int displayLineNumber = this.LineNumber - Context.DisplayPreContext.Length; foreach (string contextLine in Context.DisplayPreContext) @@ -851,14 +851,14 @@ public LogicalContextTracker(int preContext, int postContext) public void TrackLine(string line) { - ContextEntry entry = new ContextEntry(line); + ContextEntry entry = new(line); _collectedContext.Add(entry); UpdateQueue(); } public void TrackMatch(MatchInfo match) { - ContextEntry entry = new ContextEntry(match); + ContextEntry entry = new(match); _collectedContext.Add(entry); UpdateQueue(); } @@ -1436,8 +1436,8 @@ protected override void BeginProcessing() { if (this.MyInvocation.BoundParameters.ContainsKey(nameof(Culture)) && !this.MyInvocation.BoundParameters.ContainsKey(nameof(SimpleMatch))) { - InvalidOperationException exception = new InvalidOperationException(MatchStringStrings.CannotSpecifyCultureWithoutSimpleMatch); - ErrorRecord errorRecord = new ErrorRecord(exception, "CannotSpecifyCultureWithoutSimpleMatch", ErrorCategory.InvalidData, null); + InvalidOperationException exception = new(MatchStringStrings.CannotSpecifyCultureWithoutSimpleMatch); + ErrorRecord errorRecord = new(exception, "CannotSpecifyCultureWithoutSimpleMatch", ErrorCategory.InvalidData, null); this.ThrowTerminatingError(errorRecord); } @@ -1471,7 +1471,7 @@ protected override void BeginProcessing() _globalContextTracker = GetContextTracker(); } - private readonly List _inputObjectFileList = new List(1) { string.Empty }; + private readonly List _inputObjectFileList = new(1) { string.Empty }; /// /// Process the input. @@ -1600,9 +1600,9 @@ private bool ProcessFile(string filename) return false; } - using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + using (FileStream fs = new(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { - using (StreamReader sr = new StreamReader(fs, Encoding)) + using (StreamReader sr = new(fs, Encoding)) { string line; int lineNo = 0; @@ -1940,7 +1940,7 @@ private bool DoMatchWorker(string operandString, MatchInfo matchInfo, out MatchI /// The resolved (absolute) paths. private List ResolveFilePaths(string[] filePaths, bool isLiteralPath) { - List allPaths = new List(); + List allPaths = new(); foreach (string path in filePaths) { @@ -1983,7 +1983,7 @@ private static ErrorRecord BuildErrorRecord(string messageId, string arg0, strin private static ErrorRecord BuildErrorRecord(string messageId, object[] arguments, string errorId, Exception innerException) { string fmtedMsg = StringUtil.Format(messageId, arguments); - ArgumentException e = new ArgumentException(fmtedMsg, innerException); + ArgumentException e = new(fmtedMsg, innerException); return new ErrorRecord(e, errorId, ErrorCategory.InvalidArgument, null); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 529687db68f..1947793b05b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -503,7 +503,7 @@ private void AnalyzeObjectProperties(PSObject inObj) // Keep track of which properties are counted for an // input object so that repeated properties won't be // counted twice. - MeasureObjectDictionary countedProperties = new MeasureObjectDictionary(); + MeasureObjectDictionary countedProperties = new(); // First iterate over the user-specified list of // properties... @@ -581,7 +581,7 @@ private void AnalyzeValue(string propertyName, object objValue) if (!LanguagePrimitives.TryConvertTo(objValue, out numValue)) { _nonNumericError = true; - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewInvalidOperationException(MeasureObjectStrings.NonNumericInputObject, objValue), "NonNumericInputObject", ErrorCategory.InvalidType, @@ -790,7 +790,7 @@ private void AnalyzeNumber(double numValue, Statistics stat) private void WritePropertyNotFoundError(string propertyName, string errorId) { Diagnostics.Assert(Property != null, "no property and no InputObject should have been addressed"); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewArgumentException("Property"), errorId, ErrorCategory.InvalidArgument, @@ -908,7 +908,7 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene if (shouldUseGenericMeasureInfo) { - GenericMeasureInfo gmi = new GenericMeasureInfo(); + GenericMeasureInfo gmi = new(); gmi.Count = stat.count; gmi.Sum = sum; gmi.Average = average; @@ -927,7 +927,7 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene } else { - GenericObjectMeasureInfo gomi = new GenericObjectMeasureInfo(); + GenericObjectMeasureInfo gomi = new(); gomi.Count = stat.count; gomi.Sum = sum; gomi.Average = average; @@ -945,7 +945,7 @@ private MeasureInfo CreateGenericMeasureInfo(Statistics stat, bool shouldUseGene /// A new TextMeasureInfo object. private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) { - TextMeasureInfo tmi = new TextMeasureInfo(); + TextMeasureInfo tmi = new(); if (_measureCharacters) tmi.Characters = stat.characters; @@ -961,7 +961,7 @@ private TextMeasureInfo CreateTextMeasureInfo(Statistics stat) /// The observed statistics keyed by property name. /// If Property is not set, then the key used will be the value of thisObject. /// - private readonly MeasureObjectDictionary _statistics = new MeasureObjectDictionary(); + private readonly MeasureObjectDictionary _statistics = new(); /// /// Whether or not a numeric conversion error occurred. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index b40b53952f0..0b52a68499d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -106,7 +106,7 @@ private void CreateMemberNotFoundError(PSObject pso, DictionaryEntry property, T private void CreateMemberSetValueError(SetValueException e) { - Exception ex = new Exception(StringUtil.Format(NewObjectStrings.InvalidValue, e)); + Exception ex = new(StringUtil.Format(NewObjectStrings.InvalidValue, e)); ThrowTerminatingError( new ErrorRecord(ex, "SetValueException", ErrorCategory.InvalidData, null)); } @@ -463,7 +463,7 @@ private object CreateComObject() { createInfo = new ComCreateInfo(); - Thread thread = new Thread(new ParameterizedThreadStart(STAComCreateThreadProc)); + Thread thread = new(new ParameterizedThreadStart(STAComCreateThreadProc)); thread.SetApartmentState(ApartmentState.STA); thread.Start(createInfo); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs index 8726cece2b9..8ae43a6e4fd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs @@ -43,7 +43,7 @@ protected override void ProcessRecord() // Since the alias already exists, write an error. SessionStateException aliasExists = - new SessionStateException( + new( Name, SessionStateCategory.Alias, "AliasAlreadyExists", @@ -61,7 +61,7 @@ protected override void ProcessRecord() // Create the alias info AliasInfo newAlias = - new AliasInfo( + new( Name, Value, Context, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs index c807b61d6d2..93b3eb209af 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs @@ -40,7 +40,7 @@ protected override void EndProcessing() if (!string.IsNullOrEmpty(filePath)) { - FileInfo file = new FileInfo(filePath); + FileInfo file = new(filePath); WriteObject(file); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index 21cf7f3e15c..6bf54039260 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -65,8 +65,8 @@ internal CultureInfo Culture } } - internal static readonly ObjectCommandPropertyValue NonExistingProperty = new ObjectCommandPropertyValue(); - internal static readonly ObjectCommandPropertyValue ExistingNullProperty = new ObjectCommandPropertyValue(null); + internal static readonly ObjectCommandPropertyValue NonExistingProperty = new(); + internal static readonly ObjectCommandPropertyValue ExistingNullProperty = new(null); private readonly bool _caseSensitive; internal CultureInfo cultureInfo = null; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index b3f768f1a65..172c9c98ab5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -211,7 +211,7 @@ private static void ProcessExpressionParameter( out List mshParameterList) { mshParameterList = null; - TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); + TerminatingErrorContext invocationContext = new(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : @@ -235,7 +235,7 @@ internal void ProcessExpressionParameter( PSCmdlet cmdlet, object[] expr) { - TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); + TerminatingErrorContext invocationContext = new(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : @@ -272,7 +272,7 @@ internal void ProcessExpressionParameter( // match property names on the incoming objects. private static List ExpandExpressions(List inputObjects, List unexpandedParameterList) { - List expandedParameterList = new List(); + List expandedParameterList = new(); if (unexpandedParameterList != null) { @@ -285,7 +285,7 @@ private static List ExpandExpressions(List inputObjects, } else { - SortedDictionary expandedPropertyNames = new SortedDictionary(StringComparer.OrdinalIgnoreCase); + SortedDictionary expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase); if (inputObjects != null) { foreach (object inputObject in inputObjects) @@ -304,7 +304,7 @@ private static List ExpandExpressions(List inputObjects, foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values) { - MshParameter expandedParameter = new MshParameter(); + MshParameter expandedParameter = new(); expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; @@ -327,7 +327,7 @@ private static void ExpandExpressions(PSObject inputObject, List U { PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); - SortedDictionary expandedPropertyNames = new SortedDictionary(StringComparer.OrdinalIgnoreCase); + SortedDictionary expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase); if (inputObject == null) { continue; @@ -340,7 +340,7 @@ private static void ExpandExpressions(PSObject inputObject, List U foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values) { - MshParameter expandedParameter = new MshParameter(); + MshParameter expandedParameter = new(); expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; @@ -376,14 +376,14 @@ internal static List CreateOrderMatrix( List mshParameterList ) { - List orderMatrixToCreate = new List(); + List orderMatrixToCreate = new(); for (int index = 0; index < inputObjects.Count; index++) { PSObject so = inputObjects[index]; if (so == null || so == AutomationNull.Value) continue; - List evaluationErrors = new List(); - List propertyNotFoundMsgs = new List(); + List evaluationErrors = new(); + List propertyNotFoundMsgs = new(); OrderByPropertyEntry result = OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs, originalIndex: index); foreach (ErrorRecord err in evaluationErrors) @@ -507,8 +507,8 @@ internal OrderByPropertyEntry CreateOrderByPropertyEntry( ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList); } - List evaluationErrors = new List(); - List propertyNotFoundMsgs = new List(); + List evaluationErrors = new(); + List propertyNotFoundMsgs = new(); OrderByPropertyEntry result = OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo); foreach (ErrorRecord err in evaluationErrors) @@ -543,7 +543,7 @@ internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List orderValues = new List(); + internal List orderValues = new(); // The originalIndex field was added to enable stable heap-sorts (Top N/Bottom N) internal int originalIndex = -1; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs index 0b1452b0709..f186fbe1baa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointUpdaterCommandBase.cs @@ -88,7 +88,7 @@ protected override void ProcessRecord() #region private data - private readonly Dictionary runspaces = new Dictionary(); + private readonly Dictionary runspaces = new(); #endregion private data diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index a627e80733e..3fabe75de24 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -97,7 +97,7 @@ protected override void BeginProcessing() IEnumerator e = LanguagePrimitives.GetEnumerator(_prompt); if (e != null) { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new(); while (e.MoveNext()) { @@ -125,7 +125,7 @@ protected override void BeginProcessing() promptString = (string)LanguagePrimitives.ConvertTo(_prompt, typeof(string), CultureInfo.InvariantCulture); } - FieldDescription fd = new FieldDescription(promptString); + FieldDescription fd = new(promptString); if (AsSecureString || MaskInput) { fd.SetParameterType(typeof(SecureString)); @@ -135,7 +135,7 @@ protected override void BeginProcessing() fd.SetParameterType(typeof(string)); } - Collection fdc = new Collection(); + Collection fdc = new(); fdc.Add(fd); Dictionary result = Host.UI.Prompt(string.Empty, string.Empty, fdc); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs index f04124e9a4c..6e4ced90760 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs @@ -42,7 +42,7 @@ protected override object GetSourceObject() (!(bool)Forward) ) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException(EventingStrings.ActionMandatoryForLocal), "ACTION_MANDATORY_FOR_LOCAL", ErrorCategory.InvalidArgument, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs index a342c8e9461..7cec08e1b10 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs @@ -61,8 +61,8 @@ protected override void ProcessRecord() } else { - ItemNotFoundException notAliasFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, "name", aliasName)); - ErrorRecord error = new ErrorRecord(notAliasFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, aliasName); + ItemNotFoundException notAliasFound = new(StringUtil.Format(AliasCommandStrings.NoAliasFound, "name", aliasName)); + ErrorRecord error = new(notAliasFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, aliasName); WriteError(error); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs index 14acbbdf6af..4b8ade4a94a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs @@ -111,7 +111,7 @@ protected override void ProcessRecord() (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && (!foundMatch)) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException( string.Format( System.Globalization.CultureInfo.CurrentCulture, @@ -124,7 +124,7 @@ protected override void ProcessRecord() } else if ((_eventIdentifier >= 0) && (!foundMatch)) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException( string.Format( System.Globalization.CultureInfo.CurrentCulture, From 1de0b64bc91e1ca2b0a484c9e959f85b6d05a701 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 03:20:36 +0000 Subject: [PATCH 073/138] Fix IDE0090: Simplify new expression part 4.6 (#14260) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../commands/utility/Select-Object.cs | 24 ++++++------ .../commands/utility/Send-MailMessage.cs | 20 +++++----- .../commands/utility/Set-PSBreakpoint.cs | 2 +- .../commands/utility/SetAliasCommand.cs | 2 +- .../commands/utility/SetDateCommand.cs | 6 +-- .../utility/ShowCommand/ShowCommand.cs | 14 +++---- .../commands/utility/ShowMarkdownCommand.cs | 2 +- .../commands/utility/Sort-Object.cs | 2 +- .../commands/utility/StartSleepCommand.cs | 2 +- .../commands/utility/TestJsonCommand.cs | 10 ++--- .../commands/utility/TimeExpressionCommand.cs | 2 +- .../commands/utility/UnblockFile.cs | 6 +-- .../utility/UnregisterEventCommand.cs | 4 +- .../commands/utility/Update-Data.cs | 6 +-- .../commands/utility/Update-List.cs | 8 ++-- .../commands/utility/Update-TypeData.cs | 38 +++++++++---------- .../commands/utility/UtilityCommon.cs | 10 ++--- .../commands/utility/Var.cs | 16 ++++---- .../commands/utility/WaitEventCommand.cs | 4 +- .../commands/utility/Write.cs | 8 ++-- .../commands/utility/WriteConsoleCmdlet.cs | 4 +- .../commands/utility/WriteProgressCmdlet.cs | 2 +- .../commands/utility/XmlCommands.cs | 28 +++++++------- 23 files changed, 110 insertions(+), 110 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index 4fd27e4d007..ddd527380f1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -341,9 +341,9 @@ internal UniquePSObjectHelper(PSObject o, int notePropertyCount) private void ProcessExpressionParameter() { - TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); + TerminatingErrorContext invocationContext = new(this); ParameterProcessor processor = - new ParameterProcessor(new SelectObjectExpressionParameterDefinition()); + new(new SelectObjectExpressionParameterDefinition()); if ((Property != null) && (Property.Length != 0)) { // Build property list taking into account the wildcards and @{name=;expression=} @@ -382,7 +382,7 @@ private void ProcessObject(PSObject inputObject) } // If property parameter is mentioned - List matchedProperties = new List(); + List matchedProperties = new(); foreach (MshParameter p in _propertyMshParameterList) { ProcessParameter(p, inputObject, matchedProperties); @@ -390,10 +390,10 @@ private void ProcessObject(PSObject inputObject) if (string.IsNullOrEmpty(ExpandProperty)) { - PSObject result = new PSObject(); + PSObject result = new(); if (matchedProperties.Count != 0) { - HashSet propertyNames = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet propertyNames = new(StringComparer.OrdinalIgnoreCase); foreach (PSNoteProperty noteProperty in matchedProperties) { @@ -431,7 +431,7 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List expressionResults = new List(); + List expressionResults = new(); foreach (PSPropertyExpression resolvedName in ex.ResolveNames(inputObject)) { if (_exclusionFilter == null || !_exclusionFilter.IsMatch(resolvedName)) @@ -456,7 +456,7 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List 1) { string errorMsg = SelectObjectStrings.RenamingMultipleResults; - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(errorMsg), "RenamingMultipleResults", ErrorCategory.InvalidOperation, @@ -506,7 +506,7 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, if (expressionResults.Count == 0) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.PropertyNotFound, ExpandProperty), "ExpandPropertyNotFound", ErrorCategory.InvalidArgument, @@ -516,7 +516,7 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, if (expressionResults.Count > 1) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewArgumentException("ExpandProperty", SelectObjectStrings.MutlipleExpandProperties, ExpandProperty), "MutlipleExpandProperties", ErrorCategory.InvalidArgument, @@ -563,7 +563,7 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, } else { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( r.Exception, "PropertyEvaluationExpand", ErrorCategory.InvalidResult, @@ -596,7 +596,7 @@ private void AddNoteProperties(PSObject expandedObject, PSObject inputObject, IE private void WriteAlreadyExistingPropertyError(string name, object inputObject, string errorId) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewArgumentException("Property", SelectObjectStrings.AlreadyExistingProperty, name), errorId, ErrorCategory.InvalidOperation, @@ -624,7 +624,7 @@ private void FilteredWriteObject(PSObject obj, List addedNotePro bool isObjUnique = true; foreach (UniquePSObjectHelper uniqueObj in _uniques) { - ObjectCommandComparer comparer = new ObjectCommandComparer(true, CultureInfo.CurrentCulture, true); + ObjectCommandComparer comparer = new(true, CultureInfo.CurrentCulture, true); if ((comparer.Compare(obj.BaseObject, uniqueObj.WrittenObject.BaseObject) == 0) && (uniqueObj.NotePropertyCount == addedNoteProperties.Count)) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 90d34be2ff3..975fd68ebfa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -173,7 +173,7 @@ public Encoding Encoding #region Private variables and methods // Instantiate a new instance of MailMessage - private readonly MailMessage _mMailMessage = new MailMessage(); + private readonly MailMessage _mMailMessage = new(); private SmtpClient _mSmtpClient = null; @@ -216,7 +216,7 @@ private void AddAddressesToMailMessage(object address, string param) } catch (FormatException e) { - ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, null); + ErrorRecord er = new(e, "FormatException", ErrorCategory.InvalidType, null); WriteError(er); continue; } @@ -239,7 +239,7 @@ protected override void BeginProcessing() } catch (FormatException e) { - ErrorRecord er = new ErrorRecord(e, "FormatException", ErrorCategory.InvalidType, From); + ErrorRecord er = new(e, "FormatException", ErrorCategory.InvalidType, From); ThrowTerminatingError(er); } @@ -294,7 +294,7 @@ protected override void BeginProcessing() if (string.IsNullOrEmpty(SmtpServer)) { - ErrorRecord er = new ErrorRecord(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null); + ErrorRecord er = new(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null); this.ThrowTerminatingError(er); } @@ -344,7 +344,7 @@ protected override void ProcessRecord() PathUtils.ReportFileOpenFailure(this, filepath, e); } - Attachment mailAttachment = new Attachment(filepath); + Attachment mailAttachment = new(filepath); _mMailMessage.Attachments.Add(mailAttachment); } } @@ -362,30 +362,30 @@ protected override void EndProcessing() } catch (SmtpFailedRecipientsException ex) { - ErrorRecord er = new ErrorRecord(ex, "SmtpFailedRecipientsException", ErrorCategory.InvalidOperation, _mSmtpClient); + ErrorRecord er = new(ex, "SmtpFailedRecipientsException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } catch (SmtpException ex) { if (ex.InnerException != null) { - ErrorRecord er = new ErrorRecord(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); + ErrorRecord er = new(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } else { - ErrorRecord er = new ErrorRecord(ex, "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); + ErrorRecord er = new(ex, "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } } catch (InvalidOperationException ex) { - ErrorRecord er = new ErrorRecord(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _mSmtpClient); + ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } catch (System.Security.Authentication.AuthenticationException ex) { - ErrorRecord er = new ErrorRecord(ex, "AuthenticationException", ErrorCategory.InvalidOperation, _mSmtpClient); + ErrorRecord er = new(ex, "AuthenticationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } finally diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs index e628da48244..ccf17652c79 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -123,7 +123,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { // If there is a script, resolve its path - Collection scripts = new Collection(); + Collection scripts = new(); if (Script != null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs index 060f309e447..6c0007fa2a2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs @@ -23,7 +23,7 @@ protected override void ProcessRecord() // Create the alias info AliasInfo aliasToSet = - new AliasInfo( + new( Name, Value, Context, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs index e00a3bda2d9..77b0dce3470 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -77,7 +77,7 @@ protected override void ProcessRecord() } #else // build up the SystemTime struct to pass to SetSystemTime - NativeMethods.SystemTime systemTime = new NativeMethods.SystemTime(); + NativeMethods.SystemTime systemTime = new(); systemTime.Year = (UInt16)dateToUse.Year; systemTime.Month = (UInt16)dateToUse.Month; systemTime.Day = (UInt16)dateToUse.Day; @@ -102,8 +102,8 @@ protected override void ProcessRecord() } // output DateTime object wrapped in an PSObject with DisplayHint attached - PSObject outputObj = new PSObject(dateToUse); - PSNoteProperty note = new PSNoteProperty("DisplayHint", DisplayHint); + PSObject outputObj = new(dateToUse); + PSNoteProperty note = new("DisplayHint", DisplayHint); outputObj.Properties.Add(note); WriteObject(outputObj); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index 6306b7913f9..330716af151 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -50,7 +50,7 @@ public class ShowCommandCommand : PSCmdlet, IDisposable /// /// Record the EndProcessing error. /// - private PSDataCollection _errors = new PSDataCollection(); + private PSDataCollection _errors = new(); /// /// Field used for the NoCommonParameter parameter. @@ -174,7 +174,7 @@ protected override void BeginProcessing() if (_showCommandProxy.ScreenHeight < this.Height) { - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( new NotSupportedException(string.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Height", _showCommandProxy.ScreenHeight)), "PARAMETER_DATA_ERROR", ErrorCategory.InvalidData, @@ -184,7 +184,7 @@ protected override void BeginProcessing() if (_showCommandProxy.ScreenWidth < this.Width) { - ErrorRecord error = new ErrorRecord( + ErrorRecord error = new( new NotSupportedException(string.Format(CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.PropertyValidate, "Width", _showCommandProxy.ScreenWidth)), "PARAMETER_DATA_ERROR", ErrorCategory.InvalidData, @@ -233,7 +233,7 @@ protected override void EndProcessing() return; } - StringBuilder errorString = new StringBuilder(); + StringBuilder errorString = new(); for (int i = 0; i < _errors.Count; i++) { @@ -268,7 +268,7 @@ protected override void StopProcessing() private void RunScriptSilentlyAndWithErrorHookup(string script) { // errors are not created here, because there is a field for it used in the final pop up - PSDataCollection output = new PSDataCollection(); + PSDataCollection output = new(); output.DataAdded += this.Output_DataAdded; _errors.DataAdded += this.Error_DataAdded; @@ -286,7 +286,7 @@ private void RunScriptSilentlyAndWithErrorHookup(string script) /// private void IssueErrorForNoCommand() { - InvalidOperationException errorException = new InvalidOperationException( + InvalidOperationException errorException = new( string.Format( CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.CommandNotFound, @@ -299,7 +299,7 @@ private void IssueErrorForNoCommand() /// private void IssueErrorForMoreThanOneCommand() { - InvalidOperationException errorException = new InvalidOperationException( + InvalidOperationException errorException = new( string.Format( CultureInfo.CurrentUICulture, FormatAndOut_out_gridview.MoreThanOneCommand, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs index 302c7bacd2f..63ee15f6f59 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -168,7 +168,7 @@ private void ProcessMarkdownInfo(MarkdownInfo markdownInfo) try { - ProcessStartInfo startInfo = new ProcessStartInfo(); + ProcessStartInfo startInfo = new(); startInfo.FileName = tmpFilePath; startInfo.UseShellExecute = true; Process.Start(startInfo); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs index 5f66b39753f..60b656d890c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs @@ -239,7 +239,7 @@ private int Heapify(List dataToSort, OrderByPropertyCompar /// protected override void EndProcessing() { - OrderByProperty orderByProperty = new OrderByProperty( + OrderByProperty orderByProperty = new( this, InputObjects, Property, !Descending, ConvertedCulture, CaseSensitive); var dataToProcess = orderByProperty.OrderMatrix; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index da65c683616..a57d635f3eb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -64,7 +64,7 @@ public void Dispose() // object used for synchronizes pipeline thread and stop thread // access to waitHandle - private readonly object _syncObject = new object(); + private readonly object _syncObject = new(); // this is set to true by stopProcessing private bool _stopping = false; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index 3b9655cadc8..c8ba1e7ea48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -115,7 +115,7 @@ e is NotSupportedException || e is SecurityException ) { - Exception exception = new Exception( + Exception exception = new( string.Format( CultureInfo.CurrentUICulture, TestJsonCmdletStrings.JsonSchemaFileOpenFailure, @@ -125,7 +125,7 @@ e is SecurityException } catch (Exception e) { - Exception exception = new Exception(TestJsonCmdletStrings.InvalidJsonSchema, e); + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); ThrowTerminatingError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, resolvedpath)); } } @@ -149,11 +149,11 @@ protected override void ProcessRecord() { result = false; - Exception exception = new Exception(TestJsonCmdletStrings.InvalidJsonAgainstSchema); + Exception exception = new(TestJsonCmdletStrings.InvalidJsonAgainstSchema); foreach (var message in errorMessages) { - ErrorRecord errorRecord = new ErrorRecord(exception, "InvalidJsonAgainstSchema", ErrorCategory.InvalidData, null); + ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchema", ErrorCategory.InvalidData, null); errorRecord.ErrorDetails = new ErrorDetails(message.ToString()); WriteError(errorRecord); } @@ -164,7 +164,7 @@ protected override void ProcessRecord() { result = false; - Exception exception = new Exception(TestJsonCmdletStrings.InvalidJson, exc); + Exception exception = new(TestJsonCmdletStrings.InvalidJson, exc); WriteError(new ErrorRecord(exception, "InvalidJson", ErrorCategory.InvalidData, Json)); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs index 655598e9036..24ed81995d1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs @@ -37,7 +37,7 @@ public sealed class MeasureCommandCommand : PSCmdlet #region private members - private readonly System.Diagnostics.Stopwatch _stopWatch = new System.Diagnostics.Stopwatch(); + private readonly System.Diagnostics.Stopwatch _stopWatch = new(); #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index 78160785d98..1d77f88b880 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -74,7 +74,7 @@ public string[] LiteralPath /// protected override void ProcessRecord() { - List pathsToProcess = new List(); + List pathsToProcess = new(); ProviderInfo provider = null; if (string.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase)) @@ -110,7 +110,7 @@ protected override void ProcessRecord() { if (!WildcardPattern.ContainsWildcardCharacters(path)) { - ErrorRecord errorRecord = new ErrorRecord(e, + ErrorRecord errorRecord = new(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); @@ -180,7 +180,7 @@ private bool IsValidFileForUnblocking(string resolvedpath) { if (!System.IO.File.Exists(resolvedpath)) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new System.IO.FileNotFoundException(resolvedpath), "FileNotFound", ErrorCategory.ObjectNotFound, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs index f89b3d6e4cc..f0f87eb9f66 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -97,7 +97,7 @@ protected override void ProcessRecord() (!WildcardPattern.ContainsWildcardCharacters(_sourceIdentifier)) && (!_foundMatch)) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException( string.Format( System.Globalization.CultureInfo.CurrentCulture, @@ -111,7 +111,7 @@ protected override void ProcessRecord() else if ((SubscriptionId >= 0) && (!_foundMatch)) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new ArgumentException( string.Format( System.Globalization.CultureInfo.CurrentCulture, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs index 0565d6d7d41..4a3198d2911 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs @@ -35,7 +35,7 @@ public class UpdateData : PSCmdlet private static void ReportWrongExtension(string file, string errorId, PSCmdlet cmdlet) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongExtension, file, "ps1xml"), errorId, ErrorCategory.InvalidArgument, @@ -45,7 +45,7 @@ private static void ReportWrongExtension(string file, string errorId, PSCmdlet c private static void ReportWrongProviderType(string providerId, string errorId, PSCmdlet cmdlet) { - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( PSTraceSource.NewInvalidOperationException(UpdateDataStrings.UpdateData_WrongProviderError, providerId), errorId, ErrorCategory.InvalidArgument, @@ -61,7 +61,7 @@ private static void ReportWrongProviderType(string providerId, string errorId, P /// internal static Collection Glob(string[] files, string errorId, PSCmdlet cmdlet) { - Collection retValue = new Collection(); + Collection retValue = new(); foreach (string file in files) { Collection providerPaths; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs index dbff09ef36a..5850eaca7db 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs @@ -129,7 +129,7 @@ protected override void EndProcessing() private Hashtable CreateHashtable() { - Hashtable hash = new Hashtable(2); + Hashtable hash = new(2); if (Add != null) { hash.Add("Add", Add); @@ -150,7 +150,7 @@ private Hashtable CreateHashtable() private PSListModifier CreatePSListModifier() { - PSListModifier listModifier = new PSListModifier(); + PSListModifier listModifier = new(); if (Add != null) { foreach (object obj in Add) @@ -180,8 +180,8 @@ private PSListModifier CreatePSListModifier() private ErrorRecord NewError(string errorId, string resourceId, object targetObject, params object[] args) { - ErrorDetails details = new ErrorDetails(this.GetType().Assembly, "UpdateListStrings", resourceId, args); - ErrorRecord errorRecord = new ErrorRecord( + ErrorDetails details = new(this.GetType().Assembly, "UpdateListStrings", resourceId, args); + ErrorRecord errorRecord = new( new InvalidOperationException(details.Message), errorId, ErrorCategory.InvalidOperation, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index 9f7e10b4dc7..7ada7d4b947 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -28,7 +28,7 @@ public class UpdateTypeDataCommand : UpdateData private const string DynamicTypeSet = "DynamicTypeSet"; private const string TypeDataSet = "TypeDataSet"; - private static readonly object s_notSpecified = new object(); + private static readonly object s_notSpecified = new(); private static bool HasBeenSpecified(object obj) { @@ -372,7 +372,7 @@ private void ProcessStrongTypeData() { foreach (string s in errors) { - RuntimeException rte = new RuntimeException(s); + RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } @@ -411,7 +411,7 @@ private void ProcessDynamicType() ThrowTerminatingError(NewError("TargetTypeNameEmpty", UpdateDataStrings.TargetTypeNameEmpty, _typeName)); } - TypeData type = new TypeData(_typeName) { IsOverride = _force }; + TypeData type = new(_typeName) { IsOverride = _force }; GetMembers(type.Members); @@ -457,19 +457,19 @@ private void ProcessDynamicType() if (_defaultDisplayPropertySet != null) { - PropertySetData defaultDisplayPropertySet = new PropertySetData(_defaultDisplayPropertySet); + PropertySetData defaultDisplayPropertySet = new(_defaultDisplayPropertySet); type.DefaultDisplayPropertySet = defaultDisplayPropertySet; } if (_defaultKeyPropertySet != null) { - PropertySetData defaultKeyPropertySet = new PropertySetData(_defaultKeyPropertySet); + PropertySetData defaultKeyPropertySet = new(_defaultKeyPropertySet); type.DefaultKeyPropertySet = defaultKeyPropertySet; } if (_propertySerializationSet != null) { - PropertySetData propertySerializationSet = new PropertySetData(_propertySerializationSet); + PropertySetData propertySerializationSet = new(_propertySerializationSet); type.PropertySerializationSet = propertySerializationSet; } @@ -496,7 +496,7 @@ private void ProcessDynamicType() { foreach (string s in errors) { - RuntimeException rte = new RuntimeException(s); + RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicUpdateException", ErrorCategory.InvalidOperation, null)); } } @@ -690,7 +690,7 @@ private ScriptPropertyData GetScriptProperty() value2ScriptBlock = GetParameterType(_value2); } - ScriptPropertyData scriptProperty = new ScriptPropertyData(_memberName, value1ScriptBlock, value2ScriptBlock); + ScriptPropertyData scriptProperty = new(_memberName, value1ScriptBlock, value2ScriptBlock); return scriptProperty; } @@ -712,7 +712,7 @@ private CodePropertyData GetCodeProperty() value2CodeReference = GetParameterType(_value2); } - CodePropertyData codeProperty = new CodePropertyData(_memberName, value1CodeReference, value2CodeReference); + CodePropertyData codeProperty = new(_memberName, value1CodeReference, value2CodeReference); return codeProperty; } @@ -723,7 +723,7 @@ private ScriptMethodData GetScriptMethod() EnsureValue2HasNotBeenSpecified(); ScriptBlock method = GetParameterType(_value1); - ScriptMethodData scriptMethod = new ScriptMethodData(_memberName, method); + ScriptMethodData scriptMethod = new(_memberName, method); return scriptMethod; } @@ -734,7 +734,7 @@ private CodeMethodData GetCodeMethod() EnsureValue2HasNotBeenSpecified(); MethodInfo codeReference = GetParameterType(_value1); - CodeMethodData codeMethod = new CodeMethodData(_memberName, codeReference); + CodeMethodData codeMethod = new(_memberName, codeReference); return codeMethod; } @@ -749,7 +749,7 @@ private CodeMethodData GetCodeMethod() private static ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, @@ -866,7 +866,7 @@ private void ProcessTypeFiles() { foreach (string s in errors) { - RuntimeException rte = new RuntimeException(s); + RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesXmlUpdateException", ErrorCategory.InvalidOperation, null)); } @@ -1119,8 +1119,8 @@ protected override void ProcessRecord() // Key of the map is the name of the file that is in the cache. Value of the map is a index list. Duplicate files might // exist in the cache because the user can add arbitrary files to the cache by $host.Runspace.InitialSessionState.Types.Add() - Dictionary> fileToIndexMap = new Dictionary>(StringComparer.OrdinalIgnoreCase); - List indicesToRemove = new List(); + Dictionary> fileToIndexMap = new(StringComparer.OrdinalIgnoreCase); + List indicesToRemove = new(); if (Context.InitialSessionState != null) { @@ -1209,7 +1209,7 @@ protected override void ProcessRecord() } Dbg.Assert(!string.IsNullOrEmpty(typeNameToRemove), "TypeNameToRemove should be not null and not empty at this point"); - TypeData type = new TypeData(typeNameToRemove); + TypeData type = new(typeNameToRemove); string removeTypeFormattedTarget = string.Format(CultureInfo.InvariantCulture, removeTypeTarget, typeNameToRemove); if (ShouldProcess(removeTypeFormattedTarget, removeTypeAction)) @@ -1223,7 +1223,7 @@ protected override void ProcessRecord() { foreach (string s in errors) { - RuntimeException rte = new RuntimeException(s); + RuntimeException rte = new(s); this.WriteError(new ErrorRecord(rte, "TypesDynamicRemoveException", ErrorCategory.InvalidOperation, null)); } } @@ -1258,7 +1258,7 @@ protected override void EndProcessing() private static ErrorRecord NewError(string errorId, string template, object targetObject, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, template, args); - ErrorRecord errorRecord = new ErrorRecord( + ErrorRecord errorRecord = new( new InvalidOperationException(message), errorId, ErrorCategory.InvalidOperation, @@ -1334,7 +1334,7 @@ protected override void ProcessRecord() ValidateTypeName(); Dictionary alltypes = Context.TypeTable.GetAllTypeData(); - Collection typedefs = new Collection(); + Collection typedefs = new(); foreach (string type in alltypes.Keys) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index f2cf7bfb672..0658c7014c4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -241,7 +241,7 @@ public string HexBytes { if (_hexBytes == string.Empty) { - StringBuilder line = new StringBuilder(BytesPerLine * 3); + StringBuilder line = new(BytesPerLine * 3); foreach (var currentByte in Bytes) { @@ -267,7 +267,7 @@ public string Ascii { if (_ascii == string.Empty) { - StringBuilder ascii = new StringBuilder(BytesPerLine); + StringBuilder ascii = new(BytesPerLine); foreach (var currentByte in Bytes) { @@ -304,11 +304,11 @@ public override string ToString() // '16 + 3' comes from format "{0:X16} ". // '16' comes from '[Uint64]::MaxValue.ToString("X").Length'. - StringBuilder nextLine = new StringBuilder(16 + 3 + (BytesPerLine * 3)); - StringBuilder asciiEnd = new StringBuilder(BytesPerLine); + StringBuilder nextLine = new(16 + 3 + (BytesPerLine * 3)); + StringBuilder asciiEnd = new(BytesPerLine); // '+1' comes from 'result.Append(nextLine.ToString() + " " + asciiEnd.ToString());' below. - StringBuilder result = new StringBuilder(nextLine.Capacity + asciiEnd.Capacity + 1); + StringBuilder result = new(nextLine.Capacity + asciiEnd.Capacity + 1); if (Bytes.Length > 0) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index 6f379462cfe..20f8f847475 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -99,7 +99,7 @@ internal List GetMatchingVariables(string name, string lookupScope, { wasFiltered = false; - List result = new List(); + List result = new(); if (string.IsNullOrEmpty(name)) { @@ -355,7 +355,7 @@ protected override void ProcessRecord() if (!matchFound && !wasFiltered) { ItemNotFoundException itemNotFound = - new ItemNotFoundException( + new( varName, "VariableNotFound", SessionStateStrings.VariableNotFound); @@ -490,7 +490,7 @@ protected override void ProcessRecord() if (varFound != null) { SessionStateException sessionStateException = - new SessionStateException( + new( Name, SessionStateCategory.Variable, "VariableAlreadyExists", @@ -514,7 +514,7 @@ protected override void ProcessRecord() if (ShouldProcess(target, action)) { - PSVariable newVariable = new PSVariable(Name, Value, Option); + PSVariable newVariable = new(Name, Value, Option); if (_visibility != null) { @@ -810,7 +810,7 @@ private void SetVariable(string[] varNames, object varValue) { // First look for existing variables to set. - List matchingVariables = new List(); + List matchingVariables = new(); bool wasFiltered = false; @@ -865,7 +865,7 @@ private void SetVariable(string[] varNames, object varValue) } PSVariable varToSet = - new PSVariable( + new( varName, newVarValue, newOptions); @@ -1121,7 +1121,7 @@ protected override void ProcessRecord() // characters were specified, write an error. ItemNotFoundException itemNotFound = - new ItemNotFoundException( + new( varName, "VariableNotFound", SessionStateStrings.VariableNotFound); @@ -1283,7 +1283,7 @@ protected override void ProcessRecord() // characters were specified, write an error. ItemNotFoundException itemNotFound = - new ItemNotFoundException( + new( varName, "VariableNotFound", SessionStateStrings.VariableNotFound); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 77f6283f9fb..70ac9e4ae95 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -60,9 +60,9 @@ public int Timeout #endregion parameters - private readonly AutoResetEvent _eventArrived = new AutoResetEvent(false); + private readonly AutoResetEvent _eventArrived = new(false); private PSEventArgs _receivedEvent = null; - private readonly object _receivedEventLock = new object(); + private readonly object _receivedEventLock = new(); private WildcardPattern _matchPattern; /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index c812d47ec7f..2d1b26391a7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -37,7 +37,7 @@ protected override void ProcessRecord() if (mshCommandRuntime != null) { - DebugRecord record = new DebugRecord(Message); + DebugRecord record = new(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; @@ -85,7 +85,7 @@ protected override void ProcessRecord() if (mshCommandRuntime != null) { - VerboseRecord record = new VerboseRecord(Message); + VerboseRecord record = new(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; @@ -133,7 +133,7 @@ protected override void ProcessRecord() if (mshCommandRuntime != null) { - WarningRecord record = new WarningRecord(Message); + WarningRecord record = new(Message); InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; @@ -184,7 +184,7 @@ protected override void BeginProcessing() { if (tag.StartsWith("PS", StringComparison.OrdinalIgnoreCase)) { - ErrorRecord er = new ErrorRecord( + ErrorRecord er = new( new InvalidOperationException(StringUtil.Format(UtilityCommonStrings.PSPrefixReservedInInformationTag, tag)), "PSPrefixReservedInInformationTag", ErrorCategory.InvalidArgument, tag); ThrowTerminatingError(er); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 6bfad511406..aabd3637ec5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -66,7 +66,7 @@ private string ProcessObject(object o) // unroll enumerables, including arrays. bool printSeparator = false; - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); foreach (object element in enumerable) { @@ -102,7 +102,7 @@ protected override void ProcessRecord() { string result = ProcessObject(Object) ?? string.Empty; - HostInformationMessage informationMessage = new HostInformationMessage(); + HostInformationMessage informationMessage = new(); informationMessage.Message = result; informationMessage.NoNewLine = NoNewline.IsPresent; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index 93a1c392c11..ac4e1e33aff 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -96,7 +96,7 @@ protected override void ProcessRecord() { - ProgressRecord pr = new ProgressRecord(Id, Activity, Status); + ProgressRecord pr = new(Id, Activity, Status); pr.ParentActivityId = ParentId; pr.PercentComplete = PercentComplete; pr.SecondsRemaining = SecondsRemaining; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 0e86cdbfa18..1a091008f95 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -226,7 +226,7 @@ private void CreateFileStream() ); // create xml writer - XmlWriterSettings xmlSettings = new XmlWriterSettings(); + XmlWriterSettings xmlSettings = new(); xmlSettings.CloseOutput = true; xmlSettings.Encoding = sw.Encoding; xmlSettings.Indent = true; @@ -463,7 +463,7 @@ protected override void ProcessRecord() } // Loading to the XML Document _ms.Position = 0; - StreamReader read = new StreamReader(_ms); + StreamReader read = new(_ms); string data = read.ReadToEnd(); WriteObject(data); @@ -498,13 +498,13 @@ protected override void EndProcessing() if (As.Equals("Document", StringComparison.OrdinalIgnoreCase)) { // this is a trusted xml doc - the cmdlet generated the doc into a private memory stream - XmlDocument xmldoc = new XmlDocument(); + XmlDocument xmldoc = new(); xmldoc.Load(_ms); WriteObject(xmldoc); } else if (As.Equals("String", StringComparison.OrdinalIgnoreCase)) { - StreamReader read = new StreamReader(_ms); + StreamReader read = new(_ms); string data = read.ReadToEnd(); WriteObject(data); } @@ -892,7 +892,7 @@ private void WriteResults(XmlNodeList foundXmlNodes, string filePath) foreach (XmlNode foundXmlNode in foundXmlNodes) { - SelectXmlInfo selectXmlInfo = new SelectXmlInfo(); + SelectXmlInfo selectXmlInfo = new(); selectXmlInfo.Node = foundXmlNode; selectXmlInfo.Pattern = XPath; selectXmlInfo.Path = filePath; @@ -968,8 +968,8 @@ private void WriteFileReadError(string filePath, Exception exception) filePath, exception.Message); - ArgumentException argumentException = new ArgumentException(errorMessage, exception); - ErrorRecord errorRecord = new ErrorRecord(argumentException, "ProcessingFile", ErrorCategory.InvalidArgument, filePath); + ArgumentException argumentException = new(errorMessage, exception); + ErrorRecord errorRecord = new(argumentException, "ProcessingFile", ErrorCategory.InvalidArgument, filePath); this.WriteError(errorRecord); } @@ -996,15 +996,15 @@ private XmlNamespaceManager AddNameSpaceTable(string parametersetname, XmlDocume catch (NullReferenceException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); - InvalidOperationException e = new InvalidOperationException(message); - ErrorRecord er = new ErrorRecord(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); + InvalidOperationException e = new(message); + ErrorRecord er = new(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } catch (ArgumentNullException) { string message = StringUtil.Format(UtilityCommonStrings.SearchXMLPrefixNullError); - InvalidOperationException e = new InvalidOperationException(message); - ErrorRecord er = new ErrorRecord(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); + InvalidOperationException e = new(message); + ErrorRecord er = new(e, "PrefixError", ErrorCategory.InvalidOperation, namespacetable); WriteError(er); } } @@ -1033,7 +1033,7 @@ protected override void ProcessRecord() (ParameterSetName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)))) { // If any file not resolved, execution stops. this is to make consistent with select-string. - List fullresolvedPaths = new List(); + List fullresolvedPaths = new(); foreach (string fpath in Path) { if (_isLiteralPath) @@ -1049,8 +1049,8 @@ protected override void ProcessRecord() { // Cannot open File error string message = StringUtil.Format(UtilityCommonStrings.FileOpenError, provider.FullName); - InvalidOperationException e = new InvalidOperationException(message); - ErrorRecord er = new ErrorRecord(e, "ProcessingFile", ErrorCategory.InvalidOperation, fpath); + InvalidOperationException e = new(message); + ErrorRecord er = new(e, "ProcessingFile", ErrorCategory.InvalidOperation, fpath); WriteError(er); continue; } From dc9ecd9a85ab78b7e0d3ab58f03f35ef1692ab44 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 08:05:41 +0000 Subject: [PATCH 074/138] Use AsSpan/AsMemory slice constructor (#14265) * Use AsSpan slice constructor * Use AsMemory slice constructor --- .../commands/management/Computer.cs | 2 +- .../utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 +- .../host/msh/CommandLineParameterParser.cs | 2 +- .../host/msh/UpdatesNotification.cs | 2 +- src/Microsoft.WSMan.Management/ConfigProvider.cs | 8 ++++---- .../engine/CommandCompletion/CompletionCompleters.cs | 4 ++-- src/System.Management.Automation/engine/regex.cs | 2 +- .../engine/runtime/Operations/ArrayOps.cs | 2 +- .../engine/runtime/Operations/MiscOps.cs | 2 +- .../namespaces/FileSystemProvider.cs | 2 +- 10 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index d4763bb84f0..9d30f5b3a08 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -1806,7 +1806,7 @@ internal static string GetLocalAdminUserName(string computerName, PSCredential p } else { - localUserName = string.Concat(computerName.AsSpan().Slice(0, dotIndex), "\\", psLocalCredential.UserName); + localUserName = string.Concat(computerName.AsSpan(0, dotIndex), "\\", psLocalCredential.UserName); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 144c4cc9f3c..a5edb07190e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -736,7 +736,7 @@ private Uri PrepareUri(Uri uri) UriBuilder uriBuilder = new(uri); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) { - uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan().Slice(1), "&", FormatDictionary(bodyAsDictionary)); + uriBuilder.Query = string.Concat(uriBuilder.Query.AsSpan(1), "&", FormatDictionary(bodyAsDictionary)); } else { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 1e39fd7370a..7b75123c2a6 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -1077,7 +1077,7 @@ private bool ParseFile(string[] args, ref int i, bool noexitSeen) static object ConvertToBoolIfPossible(string arg) { // Before parsing we skip '$' if present. - return arg.Length > 0 && bool.TryParse(arg.AsSpan().Slice(arg[0] == '$' ? 1 : 0), out bool boolValue) + return arg.Length > 0 && bool.TryParse(arg.AsSpan(arg[0] == '$' ? 1 : 0), out bool boolValue) ? (object)boolValue : (object)arg; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index 5c202eb32b1..08e0ed8e1ee 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -315,7 +315,7 @@ private static bool TryParseUpdateFile( int dateStartIndex = updateFileName.LastIndexOf('_') + 1; if (!DateTime.TryParse( - updateFileName.AsSpan().Slice(dateStartIndex), + updateFileName.AsSpan(dateStartIndex), CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out lastUpdateDate)) diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 2d6d87a0e82..208303d9b88 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -3647,13 +3647,13 @@ private string GetCorrectCaseOfName(string ChildName, string hostname, string pa else { if (ChildName.StartsWith(WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerListener, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerListener, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); if (ChildName.StartsWith(WSManStringLiterals.containerSingleResource, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerSingleResource, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerSingleResource, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); if (ChildName.StartsWith(WSManStringLiterals.containerSecurity, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerSecurity, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerSecurity, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); if (ChildName.StartsWith(WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) - result = string.Concat(WSManStringLiterals.containerClientCertificate, "_", ChildName.AsSpan().Slice(ChildName.IndexOf('_') + 1)); + result = string.Concat(WSManStringLiterals.containerClientCertificate, "_", ChildName.AsSpan(ChildName.IndexOf('_') + 1)); } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 44ba01db63d..f5c276466be 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -511,7 +511,7 @@ internal static List CompleteCommandParameter(CompletionContex && !string.IsNullOrWhiteSpace(context.WordToComplete) && context.WordToComplete.StartsWith('-')) { var lastAst = context.RelatedAsts.Last(); - var wordToMatch = string.Concat(context.WordToComplete.AsSpan().Slice(1), "*"); + var wordToMatch = string.Concat(context.WordToComplete.AsSpan(1), "*"); var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase); var parameterNames = keywordAst.CommandElements.Where(ast => ast is CommandParameterAst).Select(ast => (ast as CommandParameterAst).ParameterName); foreach (var parameterName in s_parameterNamesOfImportDSCResource) @@ -4707,7 +4707,7 @@ internal static List CompleteVariable(CompletionContext contex provider = wordToComplete.Substring(0, colon + 1); if (s_variableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) { - pattern = string.Concat("variable:", wordToComplete.AsSpan().Slice(colon + 1), "*"); + pattern = string.Concat("variable:", wordToComplete.AsSpan(colon + 1), "*"); } else { diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index d8ef7a3a240..b5fc4d42dad 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -184,7 +184,7 @@ StringComparison GetStringComparison() if (index == Pattern.Length - 1 && Pattern[index] == '*') { // No special characters present in the pattern before last position and last character is asterisk. - var patternWithoutAsterisk = Pattern.AsMemory().Slice(0, index); + var patternWithoutAsterisk = Pattern.AsMemory(0, index); _isMatch = str => str.AsSpan().StartsWith(patternWithoutAsterisk.Span, GetStringComparison()); return; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index f6b71fad1ef..fa4c2c2b565 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -234,7 +234,7 @@ internal static string IndexStringMessage(object index) // Convert this index into something printable (we hope)... string msgString = PSObject.ToString(null, index, ",", null, null, true, true); if (msgString.Length > 20) - msgString = string.Concat(msgString.AsSpan().Slice(0, 20), " ..."); + msgString = string.Concat(msgString.AsSpan(0, 20), " ..."); return msgString; } diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 0e84f3dab58..df8b36eb40f 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -407,7 +407,7 @@ private static string GetParameterText(string parameterName) else { string whitespaces = parameterName.Substring(endPosition); - parameterText = string.Concat("-", parameterName.AsSpan().Slice(0, endPosition), ":", whitespaces); + parameterText = string.Concat("-", parameterName.AsSpan(0, endPosition), ":", whitespaces); } return parameterText; diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index a3acc0abb82..987faf46858 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2376,7 +2376,7 @@ protected override void NewItem( if (strTargetPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || strTargetPath.StartsWith("./", StringComparison.OrdinalIgnoreCase)) { - normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan().Slice(2)); + normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan(2)); } GetFileSystemInfo(normalizedTargetPath, out isDirectory); From 908cf899e14da62ff1b999a41d0548c4b516c99a Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 08:07:58 +0000 Subject: [PATCH 075/138] Fix SA1642 for Microsoft.Management.Infrastructure.CimCmdlets (#14239) https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1642.md --- .../CimAsyncOperation.cs | 2 +- .../CimBaseAction.cs | 4 +- .../CimCommandBase.cs | 14 +-- .../CimGetAssociatedInstance.cs | 4 +- .../CimGetCimClass.cs | 8 +- .../CimGetInstance.cs | 1 + .../CimIndicationWatcher.cs | 16 +--- .../CimInvokeCimMethod.cs | 8 +- .../CimNewCimInstance.cs | 5 +- .../CimPromptUser.cs | 2 +- .../CimRegisterCimIndication.cs | 8 +- .../CimRemoveCimInstance.cs | 8 +- .../CimResultObserver.cs | 30 +++---- .../CimSessionOperations.cs | 20 ++--- .../CimSessionProxy.cs | 88 ++++++++++++++----- .../CimSetCimInstance.cs | 8 +- .../CimWriteError.cs | 6 +- .../CimWriteMessage.cs | 2 +- .../CimWriteProgress.cs | 2 +- .../CimWriteResultObject.cs | 2 +- .../CmdletOperation.cs | 10 +-- .../GetCimAssociatedInstanceCommand.cs | 2 +- .../GetCimClassCommand.cs | 2 +- .../GetCimInstanceCommand.cs | 1 + .../GetCimSessionCommand.cs | 2 +- .../InvokeCimMethodCommand.cs | 2 +- .../NewCimInstanceCommand.cs | 2 +- .../NewCimSessionOptionCommand.cs | 2 +- .../RemoveCimInstanceCommand.cs | 2 +- .../RemoveCimSessionCommand.cs | 2 +- .../SetCimInstanceCommand.cs | 2 +- 31 files changed, 141 insertions(+), 126 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index b0ee5009891..49f39c8c019 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -26,7 +26,7 @@ internal abstract class CimAsyncOperation : IDisposable #region Constructor /// - /// The constructor. + /// Initializes a new instance of the class. /// protected CimAsyncOperation() { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index a635e5ae765..e3e487a9533 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -17,7 +17,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal abstract class CimBaseAction { /// - /// Constructor method. + /// Initializes a new instance of the class. /// protected CimBaseAction() { @@ -56,7 +56,7 @@ public virtual void Execute(CmdletOperationBase cmdlet) internal class CimSyncAction : CimBaseAction, IDisposable { /// - /// The constructor. + /// Initializes a new instance of the class. /// public CimSyncAction() { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 4744e319c3e..2690c209f89 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -25,7 +25,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal class ParameterDefinitionEntry { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -54,7 +54,7 @@ internal ParameterDefinitionEntry(string parameterSetName, bool mandatory) internal class ParameterSetEntry { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// internal ParameterSetEntry(UInt32 mandatoryParameterCount) @@ -65,7 +65,7 @@ internal ParameterSetEntry(UInt32 mandatoryParameterCount) } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// internal ParameterSetEntry(ParameterSetEntry toClone) @@ -76,7 +76,7 @@ internal ParameterSetEntry(ParameterSetEntry toClone) } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -133,7 +133,7 @@ internal void reset() internal class ParameterBinder { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -483,7 +483,7 @@ internal void SetParameter(object value, string parameterName) #region constructors /// - /// Constructor. + /// Initializes a new instance of the class. /// internal CimBaseCommand() { @@ -492,7 +492,7 @@ internal CimBaseCommand() } /// - /// Constructor. + /// Initializes a new instance of the class. /// internal CimBaseCommand(Dictionary> parameters, Dictionary sets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs index 69e332e0cf0..0ab4988c57d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs @@ -17,9 +17,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal sealed class CimGetAssociatedInstance : CimAsyncOperation { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// public CimGetAssociatedInstance() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index 7cd9657eed8..386482f11c5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -17,9 +17,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal class CimGetCimClassContext : XOperationContextBase { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// /// @@ -82,9 +80,7 @@ internal CimGetCimClassContext( internal sealed class CimGetCimClass : CimAsyncOperation { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// public CimGetCimClass() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index 745062908bc..184a3537fec 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -51,6 +51,7 @@ public object Process(object resultObject) internal class CimGetInstance : CimAsyncOperation { /// + /// Initializes a new instance of the class. /// /// Constructor /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 88f7cd3e89c..0c847265cfe 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -48,9 +48,7 @@ public class CimIndicationEventExceptionEventArgs : CimIndicationEventArgs public Exception Exception { get; } /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// public CimIndicationEventExceptionEventArgs(Exception theException) @@ -100,9 +98,7 @@ public string Bookmark } /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// public CimIndicationEventInstanceEventArgs(CimSubscriptionResult result) @@ -146,9 +142,7 @@ internal enum Status public event EventHandler CimIndicationArrived; /// - /// - /// Constructor with given computerName, namespace, queryExpression and timeout - /// + /// Initializes a new instance of the class. /// /// /// @@ -168,9 +162,7 @@ public CimIndicationWatcher( } /// - /// - /// Constructor with given cimsession, namespace, queryExpression and timeout - /// + /// Initializes a new instance of the class. /// /// /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index c90e7800c2d..50f4d12dd74 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -27,9 +27,7 @@ internal sealed class CimInvokeCimMethod : CimAsyncOperation internal class CimInvokeCimMethodContext : XOperationContextBase { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// /// @@ -57,9 +55,7 @@ internal CimInvokeCimMethodContext(string theNamespace, } /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// public CimInvokeCimMethod() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index d9d9603a2b1..d7436fc0ec8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -20,9 +20,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal class CimNewCimInstanceContext : XOperationContextBase { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// /// @@ -44,6 +42,7 @@ internal CimNewCimInstanceContext( internal sealed class CimNewCimInstance : CimAsyncOperation { /// + /// Initializes a new instance of the class. /// /// Constructor /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs index c70de0029b6..48b887f00b4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs @@ -22,7 +22,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal sealed class CimPromptUser : CimSyncAction { /// - /// Constructor. + /// Initializes a new instance of the class. /// public CimPromptUser(string message, CimPromptType prompt) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 8dd054698a8..e0fbb1aa095 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -50,7 +50,7 @@ internal class CimSubscriptionResultEventArgs : CimSubscriptionEventArgs public CimSubscriptionResult Result { get; } /// - /// Constructor + /// Initializes a new instance of the class. /// /// public CimSubscriptionResultEventArgs( @@ -76,7 +76,7 @@ internal class CimSubscriptionExceptionEventArgs : CimSubscriptionEventArgs public Exception Exception { get; } /// - /// Constructor + /// Initializes a new instance of the class. /// /// public CimSubscriptionExceptionEventArgs( @@ -102,9 +102,7 @@ internal sealed class CimRegisterCimIndication : CimAsyncOperation public event EventHandler OnNewSubscriptionResult; /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// public CimRegisterCimIndication() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs index 8af239ef67c..a6182166170 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs @@ -17,9 +17,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal class CimRemoveCimInstanceContext : XOperationContextBase { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// /// @@ -39,9 +37,7 @@ internal CimRemoveCimInstanceContext(string theNamespace, internal sealed class CimRemoveCimInstance : CimGetInstance { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// public CimRemoveCimInstance() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index 72f14982f2e..5e548a405ac 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -32,7 +32,7 @@ public enum AsyncResultType internal class CimResultContext { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// internal CimResultContext(object ErrorSource) @@ -56,7 +56,7 @@ internal CimResultContext(object ErrorSource) internal abstract class AsyncResultEventArgsBase : EventArgs { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -72,7 +72,7 @@ protected AsyncResultEventArgsBase( } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -109,9 +109,7 @@ protected AsyncResultEventArgsBase( internal class AsyncResultCompleteEventArgs : AsyncResultEventArgsBase { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// object. /// @@ -131,7 +129,7 @@ public AsyncResultCompleteEventArgs( internal class AsyncResultObjectEventArgs : AsyncResultEventArgsBase { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -156,7 +154,7 @@ public AsyncResultObjectEventArgs( internal class AsyncResultErrorEventArgs : AsyncResultEventArgsBase { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -171,7 +169,7 @@ public AsyncResultErrorEventArgs( } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -214,7 +212,7 @@ internal class CimResultObserver : IObserver public event EventHandler OnNewResult; /// - /// Constructor. + /// Initializes a new instance of the class. /// /// object that issued the operation. /// Operation that can be observed. @@ -225,7 +223,7 @@ public CimResultObserver(CimSession session, IObservable observable) } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// object that issued the operation. /// Operation that can be observed. @@ -346,7 +344,7 @@ public virtual void OnNext(T value) internal class CimSubscriptionResultObserver : CimResultObserver { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -356,7 +354,7 @@ public CimSubscriptionResultObserver(CimSession session, IObservable obs } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -385,7 +383,7 @@ public override void OnNext(CimSubscriptionResult value) internal class CimMethodResultObserver : CimResultObserver { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -395,7 +393,7 @@ public CimMethodResultObserver(CimSession session, IObservable observabl } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// @@ -478,7 +476,7 @@ internal string ClassName internal class IgnoreResultObserver : CimResultObserver { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 57a3ce6e99e..f03f76c09dd 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -224,9 +224,7 @@ internal class CimSessionState : IDisposable #endregion /// - /// - /// The constructor. - /// + /// Initializes a new instance of the class. /// internal CimSessionState() { @@ -745,7 +743,7 @@ internal class CimSessionBase #region constructor /// - /// The constructor. + /// Initializes a new instance of the class. /// public CimSessionBase() { @@ -868,9 +866,7 @@ internal class CimNewSession : CimSessionBase, IDisposable internal class CimTestCimSessionContext : XOperationContextBase { /// - /// - /// The constructor. - /// + /// Initializes a new instance of the class. /// /// /// @@ -890,9 +886,7 @@ internal CimTestCimSessionContext( } /// - /// - /// The constructor. - /// + /// Initializes a new instance of the class. /// internal CimNewSession() : base() { @@ -1074,7 +1068,7 @@ protected virtual void Dispose(bool disposing) internal class CimGetSession : CimSessionBase { /// - /// The constructor. + /// Initializes a new instance of the class. /// public CimGetSession() : base() { @@ -1156,7 +1150,7 @@ internal class CimRemoveSession : CimSessionBase internal static readonly string RemoveCimSessionActionName = "Remove CimSession"; /// - /// Constructor. + /// Initializes a new instance of the class. /// public CimRemoveSession() : base() { @@ -1226,7 +1220,7 @@ public void RemoveCimSession(RemoveCimSessionCommand cmdlet) internal class CimTestSession : CimAsyncOperation { /// - /// Constructor. + /// Initializes a new instance of the class. /// internal CimTestSession() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index cf869c5c89f..a442d354f4c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -65,7 +65,7 @@ internal CimSessionProxy Proxy internal class InvocationContext { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// internal InvocationContext(CimSessionProxy proxy) @@ -78,7 +78,7 @@ internal InvocationContext(CimSessionProxy proxy) } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// internal InvocationContext(string computerName, CimInstance targetCimInstance) @@ -135,7 +135,7 @@ internal interface IObjectPreProcess internal sealed class CmdletActionEventArgs : EventArgs { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// CimBaseAction object bound to the event. public CmdletActionEventArgs(CimBaseAction action) @@ -152,7 +152,7 @@ public CmdletActionEventArgs(CimBaseAction action) internal sealed class OperationEventArgs : EventArgs { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// Object used to cancel the operation. /// Async observable operation. @@ -317,8 +317,11 @@ internal static void RemoveCimSessionFromTemporaryCache(CimSession session) #region constructors /// - /// Then create wrapper object by given CimSessionProxy object. + /// Initializes a new instance of the class. /// + /// + /// Then create wrapper object by given CimSessionProxy object. + /// /// public CimSessionProxy(CimSessionProxy proxy) { @@ -331,9 +334,12 @@ public CimSessionProxy(CimSessionProxy proxy) } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name. /// Then create wrapper object. - /// + /// /// public CimSessionProxy(string computerName) { @@ -342,10 +348,13 @@ public CimSessionProxy(string computerName) } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name /// and session options. /// Then create wrapper object. - /// + /// /// /// public CimSessionProxy(string computerName, CimSessionOptions sessionOptions) @@ -355,9 +364,12 @@ public CimSessionProxy(string computerName, CimSessionOptions sessionOptions) } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name /// and cimInstance. Then create wrapper object. - /// + /// /// /// public CimSessionProxy(string computerName, CimInstance cimInstance) @@ -397,9 +409,12 @@ public CimSessionProxy(string computerName, CimInstance cimInstance) } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name, /// session options. - /// + /// /// /// /// Used when create async operation. @@ -410,9 +425,12 @@ public CimSessionProxy(string computerName, CimSessionOptions sessionOptions, Ci } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name. /// Then create wrapper object. - /// + /// /// /// Used when create async operation. public CimSessionProxy(string computerName, CimOperationOptions operOptions) @@ -422,8 +440,11 @@ public CimSessionProxy(string computerName, CimOperationOptions operOptions) } /// - /// Create wrapper object by given session object. + /// Initializes a new instance of the class. /// + /// + /// Create wrapper object by given session object. + /// /// public CimSessionProxy(CimSession session) { @@ -431,8 +452,11 @@ public CimSessionProxy(CimSession session) } /// - /// Create wrapper object by given session object. + /// Initializes a new instance of the class. /// + /// + /// Create wrapper object by given session object. + /// /// /// Used when create async operation. public CimSessionProxy(CimSession session, CimOperationOptions operOptions) @@ -1900,10 +1924,13 @@ internal class CimSessionProxyTestConnection : CimSessionProxy #region constructors /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name /// and session options. /// Then create wrapper object. - /// + /// /// /// public CimSessionProxyTestConnection(string computerName, CimSessionOptions sessionOptions) @@ -1949,9 +1976,12 @@ internal class CimSessionProxyGetCimClass : CimSessionProxy #region constructors /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name. /// Then create wrapper object. - /// + /// /// public CimSessionProxyGetCimClass(string computerName) : base(computerName) @@ -1959,10 +1989,13 @@ public CimSessionProxyGetCimClass(string computerName) } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name /// and session options. /// Then create wrapper object. - /// + /// /// /// public CimSessionProxyGetCimClass(CimSession session) @@ -2100,9 +2133,12 @@ internal class CimSessionProxyNewCimInstance : CimSessionProxy #region constructors /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name. /// Then create wrapper object. - /// + /// /// public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance operation) : base(computerName) @@ -2111,10 +2147,13 @@ public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance oper } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name /// and session options. /// Then create wrapper object. - /// + /// /// /// public CimSessionProxyNewCimInstance(CimSession session, CimNewCimInstance operation) @@ -2172,9 +2211,12 @@ internal class CimSessionProxySetCimInstance : CimSessionProxy { #region constructors /// + /// Initializes a new instance of the class. + /// + /// /// Create by given object. /// Then create wrapper object. - /// + /// /// object to clone. /// PassThru, true means output the modified instance; otherwise does not output. public CimSessionProxySetCimInstance(CimSessionProxy originalProxy, bool passThru) @@ -2184,9 +2226,12 @@ public CimSessionProxySetCimInstance(CimSessionProxy originalProxy, bool passThr } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name. /// Then create wrapper object. - /// + /// /// /// /// @@ -2199,10 +2244,13 @@ public CimSessionProxySetCimInstance(string computerName, } /// + /// Initializes a new instance of the class. + /// + /// /// Create by given computer name /// and session options. /// Then create wrapper object. - /// + /// /// /// public CimSessionProxySetCimInstance(CimSession session, bool passThru) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index 1ad72e46c79..91cf332bde9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -19,9 +19,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal class CimSetCimInstanceContext : XOperationContextBase { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// /// /// @@ -63,9 +61,7 @@ internal CimSetCimInstanceContext(string theNamespace, internal sealed class CimSetCimInstance : CimGetInstance { /// - /// - /// Constructor - /// + /// Initializes a new instance of the class. /// public CimSetCimInstance() : base() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index cf922aea143..d3ae3419fa4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -317,7 +317,8 @@ internal static ErrorCategory ConvertCimErrorToErrorCategory(CimInstance cimErro internal sealed class CimWriteError : CimSyncAction { /// - /// Constructor with an error. + /// Initializes a new instance of the class + /// with the specified . /// /// public CimWriteError(CimInstance error, InvocationContext context) @@ -327,7 +328,8 @@ public CimWriteError(CimInstance error, InvocationContext context) } /// - /// Construct with an exception object. + /// Initializes a new instance of the class + /// with the specified . /// /// public CimWriteError(Exception exception, InvocationContext context, CimResultContext cimResultContext) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs index 0b64f9b56a1..cf927617235 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -33,7 +33,7 @@ internal sealed class CimWriteMessage : CimBaseAction #endregion /// - /// Constructor method. + /// Initializes a new instance of the class. /// public CimWriteMessage(UInt32 channel, string message) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index bda41668b80..8e5632215a0 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -18,7 +18,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal sealed class CimWriteProgress : CimBaseAction { /// - /// Constructor. + /// Initializes a new instance of the class. /// /// /// Activity identifier of the given activity diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs index 95bf7432291..a4dcdfaa5c4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs @@ -15,7 +15,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets internal sealed class CimWriteResultObject : CimBaseAction { /// - /// Constructor. + /// Initializes a new instance of the class. /// public CimWriteResultObject(object result, XOperationContextBase theContext) { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index 7379ce898f1..3c49b1dcbb8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -123,7 +123,7 @@ internal void ThrowTerminatingError(Exception exception, string operation) #endregion /// - /// Constructor method. + /// Initializes a new instance of the class. /// public CmdletOperationBase(Cmdlet cmdlet) { @@ -143,7 +143,7 @@ public CmdletOperationBase(Cmdlet cmdlet) internal class CmdletOperationRemoveCimInstance : CmdletOperationBase { /// - /// Constructor method. + /// Initializes a new instance of the class. /// /// public CmdletOperationRemoveCimInstance(Cmdlet cmdlet, @@ -207,7 +207,7 @@ public override void WriteObject(object sendToPipeline, bool enumerateCollection internal class CmdletOperationSetCimInstance : CmdletOperationBase { /// - /// Constructor method. + /// Initializes a new instance of the class. /// /// public CmdletOperationSetCimInstance(Cmdlet cmdlet, @@ -285,7 +285,7 @@ public override void WriteObject(object sendToPipeline, bool enumerateCollection internal class CmdletOperationInvokeCimMethod : CmdletOperationBase { /// - /// Constructor method. + /// Initializes a new instance of the class. /// /// public CmdletOperationInvokeCimMethod(Cmdlet cmdlet, @@ -350,7 +350,7 @@ public override void WriteObject(object sendToPipeline, bool enumerateCollection internal class CmdletOperationTestCimSession : CmdletOperationBase { /// - /// Constructor method. + /// Initializes a new instance of the class. /// /// public CmdletOperationTestCimSession(Cmdlet cmdlet, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index ace8d9ef563..306bb57e288 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -33,7 +33,7 @@ public class GetCimAssociatedInstanceCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public GetCimAssociatedInstanceCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index c80596ed7a1..0d9de236f05 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -31,7 +31,7 @@ public class GetCimClassCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public GetCimClassCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index d22f8cdc693..b2f00a0e624 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -25,6 +25,7 @@ public class GetCimInstanceCommand : CimBaseCommand #region constructor /// + /// Initializes a new instance of the class. /// Constructor. /// public GetCimInstanceCommand() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs index 9ce9b7c0269..0be1b643f79 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -22,7 +22,7 @@ public sealed class GetCimSessionCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public GetCimSessionCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index 2c245b8d2b2..4377aeacfa4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -27,7 +27,7 @@ public class InvokeCimMethodCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public InvokeCimMethodCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index d524f6b5102..e3daf3e0ede 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -29,7 +29,7 @@ public class NewCimInstanceCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public NewCimInstanceCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index 063b477e2e7..7fb8f91b9dc 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -45,7 +45,7 @@ public sealed class NewCimSessionOptionCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public NewCimSessionOptionCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index 113a31ba93f..dcdcbd405f7 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -27,7 +27,7 @@ public class RemoveCimInstanceCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public RemoveCimInstanceCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs index f717cd899d0..00f575c41c8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -29,7 +29,7 @@ public sealed class RemoveCimSessionCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public RemoveCimSessionCommand() : base(parameters, parameterSets) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index c208f43b6ea..03c01785f1c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -29,7 +29,7 @@ public class SetCimInstanceCommand : CimBaseCommand #region constructor /// - /// Constructor. + /// Initializes a new instance of the class. /// public SetCimInstanceCommand() : base(parameters, parameterSets) From c909541b7797b60462188a4abe9592a8763c1fbb Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 08:10:43 +0000 Subject: [PATCH 076/138] Mark private members as static part 9 (#14234) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822 --- .../engine/Attributes.cs | 2 +- .../engine/CmdletParameterBinderController.cs | 2 +- .../CommandCompletion/CompletionAnalysis.cs | 14 +++++++------- .../engine/CommandDiscovery.cs | 2 +- .../engine/CommandSearcher.cs | 2 +- .../engine/EnumExpressionEvaluator.cs | 12 ++++++------ .../engine/InitialSessionState.cs | 4 ++-- .../engine/ManagementObjectAdapter.cs | 2 +- .../engine/Modules/GetModuleCommand.cs | 2 +- .../engine/Modules/ImportModuleCommand.cs | 4 ++-- .../engine/Modules/ModuleCmdletBase.cs | 10 +++++----- .../engine/Modules/NewModuleManifestCommand.cs | 14 +++++++------- .../engine/Modules/PSModuleInfo.cs | 2 +- .../engine/Modules/ScriptAnalysis.cs | 2 +- .../engine/Modules/TestModuleManifestCommand.cs | 2 +- .../engine/NativeCommandProcessor.cs | 6 +++++- .../engine/PSClassSearcher.cs | 2 +- .../engine/PSConfiguration.cs | 2 +- src/System.Management.Automation/engine/Pipe.cs | 2 +- .../engine/SessionState.cs | 2 +- .../engine/SessionStateContainer.cs | 6 +++--- .../engine/SessionStateFunctionAPIs.cs | 2 +- .../engine/SessionStateNavigation.cs | 4 ++-- .../engine/SessionStateVariableAPIs.cs | 2 +- .../engine/TypeMetadata.cs | 4 ++-- .../engine/TypeTable.cs | 4 ++-- .../engine/debugger/debugger.cs | 16 ++++++++-------- .../engine/hostifaces/Command.cs | 2 +- .../engine/hostifaces/History.cs | 4 ++-- .../hostifaces/InternalHostUserInterface.cs | 3 +-- .../engine/hostifaces/LocalConnection.cs | 2 +- .../engine/hostifaces/PSDataCollection.cs | 4 ++-- .../engine/hostifaces/PowerShell.cs | 4 ++-- .../engine/interpreter/InstructionList.cs | 2 +- .../engine/interpreter/LightCompiler.cs | 5 +++-- .../engine/parser/Compiler.cs | 6 +++--- .../engine/parser/PSType.cs | 2 +- .../engine/parser/Parser.cs | 8 ++++---- .../engine/parser/SafeValues.cs | 4 ++-- .../engine/parser/SemanticChecks.cs | 8 ++++---- .../engine/parser/TypeInferenceVisitor.cs | 10 +++++----- .../engine/pipeline.cs | 4 ++-- .../engine/runtime/Binding/Binders.cs | 8 ++++---- .../engine/serialization.cs | 12 ++++++++---- 44 files changed, 112 insertions(+), 104 deletions(-) diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index d097cf039b4..19a7aa881e7 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -1083,7 +1083,7 @@ public ValidateRangeAttribute(ValidateRangeKind kind) : base() _rangeKind = kind; } - private void ValidateRange(object element, ValidateRangeKind rangeKind) + private static void ValidateRange(object element, ValidateRangeKind rangeKind) { Type commonType = GetCommonType(typeof(int), element.GetType()); if (commonType == null) diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 452cd34f5b6..440b9ead537 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -2450,7 +2450,7 @@ private void IgnoreOtherMandatoryParameterSets(uint otherMandatorySetsToBeIgnore } } - private uint NewParameterSetPromptingData( + private static uint NewParameterSetPromptingData( Dictionary promptingData, MergedCompiledCommandParameter parameter, ParameterSetSpecificMetadata parameterSetMetadata, diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 46e2f5b518f..95b26ff6907 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -936,7 +936,7 @@ internal List GetResultHelper(CompletionContext completionCont } // Helper method to auto complete hashtable key - private List GetResultForHashtable(CompletionContext completionContext) + private static List GetResultForHashtable(CompletionContext completionContext) { var lastAst = completionContext.RelatedAsts.Last(); HashtableAst tempHashtableAst = null; @@ -997,7 +997,7 @@ private List GetResultForHashtable(CompletionContext completio } // Helper method to look for an incomplete assignment pair in hash table. - private bool CheckForPendingAssignment(HashtableAst hashTableAst) + private static bool CheckForPendingAssignment(HashtableAst hashTableAst) { foreach (var keyValue in hashTableAst.KeyValuePairs) { @@ -1065,7 +1065,7 @@ private static string GetFirstLineSubString(string stringToComplete, out bool ha return stringToComplete; } - private Tuple GetHashEntryContainsCursor( + private static Tuple GetHashEntryContainsCursor( IScriptPosition cursor, HashtableAst hashTableAst, bool isCursorInString) @@ -1356,7 +1356,7 @@ private static List GetResultForEnum( return GetMatchedResults(allNames, completionContext); } - private List GetResultForEnumPropertyValueOfDSCResource( + private static List GetResultForEnumPropertyValueOfDSCResource( CompletionContext completionContext, string stringToComplete, ref int replacementIndex, @@ -1643,7 +1643,7 @@ private List GetResultForString(CompletionContext completionCo /// /// /// - private ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( + private static ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( IScriptPosition cursorPosition, Ast ast, out DynamicKeywordStatementAst keywordAst) @@ -1679,7 +1679,7 @@ private ConfigurationDefinitionAst GetAncestorConfigurationAstAndKeywordAst( /// /// /// - private List GetResultForIdentifierInConfiguration( + private static List GetResultForIdentifierInConfiguration( CompletionContext completionContext, ConfigurationDefinitionAst configureAst, DynamicKeywordStatementAst keywordAst, @@ -2093,7 +2093,7 @@ private List GetResultForIdentifier(CompletionContext completi return result; } - private List GetResultForAttributeArgument(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) + private static List GetResultForAttributeArgument(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) { // Attribute member arguments Type attributeType = null; diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index be855147037..2b328767f4c 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -149,7 +149,7 @@ internal CommandDiscovery(ExecutionContext context) /// /// True if the cmdlet is a special cmdlet that shouldn't be part of the discovery list. Or false otherwise. /// - private bool IsSpecialCmdlet(Type implementingType) + private static bool IsSpecialCmdlet(Type implementingType) { // These commands should never be put in the discovery list. They are an internal implementation // detail of the formatting and output component. That component uses these cmdlets by creating diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index d3a1033c932..b349255bab8 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -842,7 +842,7 @@ private static bool checkPath(string path, string commandName) // Don't return commands to the user if that might result in: // - Trusted commands calling untrusted functions that the user has overridden // - Debug prompts calling internal functions that are likely to have code injection - private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext) + private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext) { if (result == null) { diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index ae1bcecd550..056372ac63e 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -309,7 +309,7 @@ internal override bool ExistEnum(object enumVal) return exist; } - private bool isUnsigned(Type type) + private static bool isUnsigned(Type type) { return (type == typeof(ulong) || type == typeof(uint) || type == typeof(ushort) || type == typeof(byte)); } @@ -386,7 +386,7 @@ internal bool ExistsInExpression(T flagName) /// /// A generic list of tokenized input. /// - private List TokenizeInput(string input) + private static List TokenizeInput(string input) { List tokenList = new List(); int _offset = 0; @@ -412,7 +412,7 @@ private List TokenizeInput(string input) /// /// Current offset position for the string parser. /// - private void FindNextToken(string input, ref int _offset) + private static void FindNextToken(string input, ref int _offset) { while (_offset < input.Length) { @@ -439,7 +439,7 @@ private void FindNextToken(string input, ref int _offset) /// /// The next token on the input string /// - private Token GetNextToken(string input, ref int _offset) + private static Token GetNextToken(string input, ref int _offset) { StringBuilder sb = new StringBuilder(); // bool singleQuoted = false; @@ -522,7 +522,7 @@ private Token GetNextToken(string input, ref int _offset) /// /// A list of tokenized input. /// - private void CheckSyntaxError(List tokenList) + private static void CheckSyntaxError(List tokenList) { // Initialize, assuming preceded by OR TokenKind previous = TokenKind.Or; @@ -577,7 +577,7 @@ private void CheckSyntaxError(List tokenList) /// /// Tokenized list of the input string. /// - private Node ConstructExpressionTree(List tokenList) + private static Node ConstructExpressionTree(List tokenList) { bool notFlag = false; Queue andQueue = new Queue(); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 24fec940099..74fb6f87037 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -2584,7 +2584,7 @@ HashSet GetPublicCommands() return null; } - private string[] GetModulesForUnResolvedCommands(IEnumerable unresolvedCommands, ExecutionContext context) + private static string[] GetModulesForUnResolvedCommands(IEnumerable unresolvedCommands, ExecutionContext context) { Collection modulesToImport = new Collection(); HashSet commandsToResolve = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -3072,7 +3072,7 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( /// /// /// - private IEnumerable LookupCommands( + private static IEnumerable LookupCommands( string commandPattern, string moduleName, ExecutionContext context) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index d1669bb4593..c591a6963ec 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -77,7 +77,7 @@ public WMIParameterInformation(string name, Type ty) : base(ty, true, null, fals /// /// /// - private IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObject managementObj, + private static IEnumerable GetTypeNameHierarchyFromDerivation(ManagementBaseObject managementObj, string dotnetBaseType, bool shouldIncludeNamespace) { StringBuilder type = new StringBuilder(200); diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 4651f0c79de..663e1f4b0fe 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -174,7 +174,7 @@ PSObject outputObject in } } - private PSModuleInfo GetModuleInfoForRemoteModuleWithoutManifest(RemoteDiscoveryHelper.CimModule cimModule) + private static PSModuleInfo GetModuleInfoForRemoteModuleWithoutManifest(RemoteDiscoveryHelper.CimModule cimModule) { return new PSModuleInfo(cimModule.ModuleName, null, null); } diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index c5b7ef6ac4e..35e0b61ab20 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -1401,7 +1401,7 @@ private static bool IsCmdletizationFile(RemoteDiscoveryHelper.CimModuleFile cimM return cimModuleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.CmdletizationV1; } - private IEnumerable CreateCimModuleFiles( + private static IEnumerable CreateCimModuleFiles( RemoteDiscoveryHelper.CimModule remoteCimModule, RemoteDiscoveryHelper.CimFileCode fileCode, Func filesFilter, @@ -2076,7 +2076,7 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable GetModuleForRootedPaths(List modulePat } } - private ErrorRecord CreateModuleNotFoundError(string modulePath) + private static ErrorRecord CreateModuleNotFoundError(string modulePath) { string errorMessage = StringUtil.Format(Modules.ModuleNotFoundForGetModule, modulePath); FileNotFoundException fnf = new FileNotFoundException(errorMessage); @@ -1422,7 +1422,7 @@ private IEnumerable CreateFakeModuleObject(IEnumerable - private ExternalScriptInfo FindLocalizedModuleManifest(string path) + private static ExternalScriptInfo FindLocalizedModuleManifest(string path) { string dir = Path.GetDirectoryName(path); string file = Path.GetFileName(path); @@ -4454,7 +4454,7 @@ internal void SetModuleLoggingInformation(PSModuleInfo m) } } - private void SetModuleLoggingInformation(ModuleLoggingGroupPolicyStatus status, PSModuleInfo m, IEnumerable moduleNames) + private static void SetModuleLoggingInformation(ModuleLoggingGroupPolicyStatus status, PSModuleInfo m, IEnumerable moduleNames) { // TODO, insivara : What happens when Enabled but none of the other options (DefaultSystemModules, NonDefaultSystemModule, NonSystemModule, SpecificModules) are set? // After input from GP team for this behavior, need to revisit the commented out part @@ -6104,7 +6104,7 @@ private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref boo private static readonly object s_lockObject = new object(); - private void ClearAnalysisCaches() + private static void ClearAnalysisCaches() { lock (s_lockObject) { diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index a1907a034ac..bf2e76501cc 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -534,7 +534,7 @@ public string DefaultCommandPrefix /// /// The string to quote. /// The quoted string. - private string QuoteName(string name) + private static string QuoteName(string name) { if (name == null) return "''"; @@ -546,7 +546,7 @@ private string QuoteName(string name) /// /// The Uri to quote. /// The quoted AbsoluteUri. - private string QuoteName(Uri name) + private static string QuoteName(Uri name) { if (name == null) return "''"; @@ -558,7 +558,7 @@ private string QuoteName(Uri name) /// /// The Version object to quote. /// The quoted Version string. - private string QuoteName(Version name) + private static string QuoteName(Version name) { if (name == null) return "''"; @@ -572,7 +572,7 @@ private string QuoteName(Version name) /// The list to quote. /// Streamwriter to get end of line character from. /// The quoted list. - private string QuoteNames(IEnumerable names, StreamWriter streamWriter) + private static string QuoteNames(IEnumerable names, StreamWriter streamWriter) { if (names == null) return "@()"; @@ -622,7 +622,7 @@ private string QuoteNames(IEnumerable names, StreamWriter streamWriter) /// /// /// - private IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) + private static IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) { if (moduleSpecs != null) { @@ -647,7 +647,7 @@ private IEnumerable PreProcessModuleSpec(IEnumerable moduleSpecs) /// The list to quote. /// Streamwriter to get end of line character from. /// The quoted list. - private string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) + private static string QuoteModules(IEnumerable moduleSpecs, StreamWriter streamWriter) { StringBuilder result = new StringBuilder(); result.Append("@("); @@ -897,7 +897,7 @@ private string ManifestFragmentForNonSpecifiedManifestMember(string key, string _indent, resourceString, streamWriter.NewLine, key, value); } - private string ManifestComment(string insert, StreamWriter streamWriter) + private static string ManifestComment(string insert, StreamWriter streamWriter) { // Prefix a non-empty string with a space for formatting reasons... if (!string.IsNullOrEmpty(insert)) diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 9827a06b99a..f2ab485aef0 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -581,7 +581,7 @@ public Dictionary ExportedFunctions } } - private bool IsScriptModuleFile(string path) + private static bool IsScriptModuleFile(string path) { var ext = System.IO.Path.GetExtension(path); return ext != null && s_scriptModuleExtensions.Contains(ext); diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 74b774e0726..f2005400c9d 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -462,7 +462,7 @@ private void ProcessCmdletArguments(object value, Action onEachArgument) // // It also only populates the bound parameters for a limited set of parameters needed // for module analysis. - private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName) + private static Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 06a5789d629..b31ec151af5 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -404,7 +404,7 @@ private bool IsValidFilePath(string path, PSModuleInfo module, bool verifyPathSc /// /// /// - private bool IsValidGacAssembly(string assemblyName) + private static bool IsValidGacAssembly(string assemblyName) { #if UNIX return false; diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index fa9621a6631..96ad84a6c46 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1169,7 +1169,7 @@ private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectE return startInfo; } - private bool IsDownstreamOutDefault(Pipe downstreamPipe) + private static bool IsDownstreamOutDefault(Pipe downstreamPipe) { Diagnostics.Assert(downstreamPipe != null, "Caller makes sure the passed-in parameter is not null."); @@ -1316,6 +1316,10 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect // On Windows, check the extension list and see if we should try to execute this directly. // Otherwise, use the platform library to check executability + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Accesses instance members in preprocessor branch.")] private bool IsExecutable(string path) { #if UNIX diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index 82c96c8a350..ce47ae93e16 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -288,7 +288,7 @@ private Collection GetPSModuleInfo(string modulePath) return modules; } - private PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, TypeDefinitionAst statement) + private static PSClassInfo ConvertToClassInfo(PSModuleInfo module, ScriptBlockAst ast, TypeDefinitionAst statement) { PSClassInfo classInfo = new PSClassInfo(statement.Name); Dbg.Assert(statement.Name != null, "statement should have a name."); diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 632e331fae6..16273979a69 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -174,7 +174,7 @@ internal void SetExecutionPolicy(ConfigScope scope, string shellId, string execu WriteValueToFile(scope, key, executionPolicy); } - private string GetExecutionPolicySettingKey(string shellId) + private static string GetExecutionPolicySettingKey(string shellId) { return string.Equals(shellId, Utils.DefaultPowerShellShellID, StringComparison.Ordinal) ? ExecutionPolicyDefaultShellKey diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index e3405837007..c930a43ef99 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -299,7 +299,7 @@ internal void SetVariableListForTemporaryPipe(Pipe tempPipe) CopyVariableToTempPipe(VariableStreamKind.Information, _informationVariableList, tempPipe); } - private void CopyVariableToTempPipe(VariableStreamKind streamKind, List variableList, Pipe tempPipe) + private static void CopyVariableToTempPipe(VariableStreamKind streamKind, List variableList, Pipe tempPipe) { if (variableList != null && variableList.Count > 0) { diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index 8efe2c94b65..e0bdbd23ee0 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -389,7 +389,7 @@ internal SessionStateEntryVisibility CheckApplicationVisibility(string applicati return checkPathVisibility(Applications, applicationPath); } - private SessionStateEntryVisibility checkPathVisibility(List list, string path) + private static SessionStateEntryVisibility checkPathVisibility(List list, string path) { if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index feb80bbc73f..ca7f03a42ca 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -2061,7 +2061,7 @@ internal object GetChildItemsDynamicParameters( } // Detect if the GetChildItemDynamicParameters has been overridden. - private bool HasGetChildItemDynamicParameters(ProviderInfo providerInfo) + private static bool HasGetChildItemDynamicParameters(ProviderInfo providerInfo) { Type providerType = providerInfo.ImplementingType; @@ -4776,7 +4776,7 @@ private object CopyItemDynamicParameters( // This function validates a remote path, and if it exists, it returns the root path. // - private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession session, CmdletProviderContext context, PSLanguageMode? languageMode, bool sourceIsRemote) + private static string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession session, CmdletProviderContext context, PSLanguageMode? languageMode, bool sourceIsRemote) { Hashtable op = null; @@ -4892,7 +4892,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses return root; } - private bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode) + private static bool isValidSession(PSSession session, CmdletProviderContext context, out PSLanguageMode? languageMode) { // session == null is validated by the parameter binding if (session.Availability != RunspaceAvailability.Available) diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 42d3607cadb..adf4c396473 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -220,7 +220,7 @@ internal FunctionInfo GetFunction(string name) return GetFunction(name, CommandOrigin.Internal); } - private IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) + private static IEnumerable GetFunctionAliases(IParameterMetadataProvider ipmp) { if (ipmp == null || ipmp.Body.ParamBlock == null) yield break; diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index 4afb9218dd7..f6d1a28eb1c 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -190,7 +190,7 @@ internal string GetParentPath( } } - private string AddQualifier(string path, ProviderInfo provider, string qualifier, bool isProviderQualified, bool isDriveQualified) + private static string AddQualifier(string path, ProviderInfo provider, string qualifier, bool isProviderQualified, bool isDriveQualified) { string result = path; @@ -640,7 +640,7 @@ internal string NormalizeRelativePath( /// /// The character to test. /// True if the character is a path separator. - private bool IsPathSeparator(char c) + private static bool IsPathSeparator(char c) { return c == StringLiterals.DefaultPathSeparator || c == StringLiterals.AlternatePathSeparator; } diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index bf3321b5b71..8cc9e4bafa4 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -1816,7 +1816,7 @@ internal IDictionary GetVariableTable() return result; } - private void GetScopeVariableTable(SessionStateScope scope, Dictionary result, bool includePrivate) + private static void GetScopeVariableTable(SessionStateScope scope, Dictionary result, bool includePrivate) { foreach (KeyValuePair entry in scope.Variables) { diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 04ada04c56e..ce5bb55432a 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -895,7 +895,7 @@ internal string GetProxyParameterData(string prefix, string paramNameOverride, b /// /// Attribute's proxy string. /// - private string GetProxyAttributeData(Attribute attrib, string prefix) + private static string GetProxyAttributeData(Attribute attrib, string prefix) { string result; @@ -1367,7 +1367,7 @@ private void ConstructCompiledParametersUsingReflection(bool processingDynamicPa } } - private void CheckForReservedParameter(string name) + private static void CheckForReservedParameter(string name) { if (name.Equals("SelectProperty", StringComparison.OrdinalIgnoreCase) || diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 3d40a915f14..0e407d57ac4 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -277,7 +277,7 @@ private void CheckStandardNote(TypeMemberData member, TypeData typeData, Acti } } - private bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) + private static bool CheckStandardPropertySet(TypeMemberData member, TypeData typeData, Action setter) { var propertySet = member as PropertySetData; if (propertySet != null) @@ -4567,7 +4567,7 @@ internal void Initialize( /// /// Helper method to load content for a module. /// - private string GetModuleContents( + private static string GetModuleContents( string moduleName, string fileToLoad, ConcurrentBag errors, diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index d015cd3e45f..30e83c38f90 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -2868,7 +2868,7 @@ public override Breakpoint DisableBreakpoint(Breakpoint breakpoint, int? runspac return null; } - private Debugger GetRunspaceDebugger(int runspaceId) + private static Debugger GetRunspaceDebugger(int runspaceId) { if (!Runspace.RunspaceDictionary.TryGetValue(runspaceId, out WeakReference wr)) { @@ -4650,7 +4650,7 @@ private object DrainAndBlockRemoteOutput() return null; } - private void RestoreRemoteOutput(object runningCmd) + private static void RestoreRemoteOutput(object runningCmd) { if (runningCmd == null) { return; } @@ -4908,7 +4908,7 @@ private InvocationInfo CreateInvocationInfoFromParent( return null; } - private string FixUpStatementExtent(int startColNum, string stateExtentText) + private static string FixUpStatementExtent(int startColNum, string stateExtentText) { Text.StringBuilder sb = new Text.StringBuilder(); sb.Append(' ', startColNum); @@ -4947,7 +4947,7 @@ private object DrainAndBlockRemoteOutput() return null; } - private void RestoreRemoteOutput(object runningCmd) + private static void RestoreRemoteOutput(object runningCmd) { if (runningCmd == null) { return; } @@ -5207,7 +5207,7 @@ private DebuggerCommand DoProcessCommand(PSHost host, string command, Invocation /// /// Displays the help text for the debugger commands. /// - private void DisplayHelp(PSHost host, IList output) + private static void DisplayHelp(PSHost host, IList output) { WriteLine(string.Empty, host, output); WriteLine(StringUtil.Format(DebuggerStrings.StepHelp, StepShortcut, StepCommand), host, output); @@ -5335,7 +5335,7 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i WriteCR(host, output); } - private void WriteLine(string line, PSHost host, IList output) + private static void WriteLine(string line, PSHost host, IList output) { if (host != null) { @@ -5348,7 +5348,7 @@ private void WriteLine(string line, PSHost host, IList output) } } - private void WriteCR(PSHost host, IList output) + private static void WriteCR(PSHost host, IList output) { if (host != null) { @@ -5361,7 +5361,7 @@ private void WriteCR(PSHost host, IList output) } } - private void WriteErrorLine(string error, PSHost host, IList output) + private static void WriteErrorLine(string error, PSHost host, IList output) { if (host != null) { diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 4af611980d3..6d8cd526486 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -422,7 +422,7 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR } } - private Pipe GetRedirectionPipe( + private static Pipe GetRedirectionPipe( PipelineResultTypes toType, MshCommandRuntime mcr) { diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 5af0cf2747d..160857a3a0a 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -755,7 +755,7 @@ private void IncrementCountOfEntriesInBuffer() /// Get the current history size. /// /// - private int GetHistorySize() + private static int GetHistorySize() { int historySize = 0; var executionContext = LocalPipeline.GetExecutionContextFromTLS(); @@ -1315,7 +1315,7 @@ private void PopulateIdAndCommandLine() /// in the pipeline. If there are more than one element in pipeline /// (ex A | Invoke-History 2 | B) then we cannot do this replacement. /// - private void ReplaceHistoryString(HistoryInfo entry, LocalRunspace localRunspace) + private static void ReplaceHistoryString(HistoryInfo entry, LocalRunspace localRunspace) { var pipeline = (LocalPipeline)localRunspace.GetCurrentlyRunningPipeline(); if (pipeline.AddToHistory) diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index dcfe06245af..96379ee853f 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -49,8 +49,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh _internalRawUI.ThrowNotInteractive(); } - private - void + private static void ThrowPromptNotInteractive(string promptMessage) { string message = StringUtil.Format(HostInterfaceExceptionsStrings.HostFunctionPromptNotImplemented, promptMessage); diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 22a0ab07d05..7f10b75525c 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -941,7 +941,7 @@ private void DoCloseHelper() /// function. If a remote runspace supports disconnect then it will be disconnected /// rather than closed. /// - private void CloseOrDisconnectAllRemoteRunspaces(Func> getRunspaces) + private static void CloseOrDisconnectAllRemoteRunspaces(Func> getRunspaces) { List runspaces = getRunspaces(); if (runspaces.Count == 0) { return; } diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 6d690d1206e..1743e6d4678 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -1629,7 +1629,7 @@ private static void VerifyValueType(object value) } // Serializes an object, as long as it's not serialized. - private PSObject GetSerializedObject(object value) + private static PSObject GetSerializedObject(object value) { // This is a safe cast, as this method is only called with "SerializeInput" is set, // and that method throws if the collection type is not PSObject. @@ -1654,7 +1654,7 @@ private PSObject GetSerializedObject(object value) } } - private bool SerializationWouldHaveNoEffect(PSObject result) + private static bool SerializationWouldHaveNoEffect(PSObject result) { if (result == null) { diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index c5248e106b7..627ca221fa3 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -4931,7 +4931,7 @@ private IAsyncResult CoreInvokeAsync(PSDataCollection i /// /// Verifies the settings for ThreadOptions and ApartmentState. /// - private void VerifyThreadSettings(PSInvocationSettings settings, ApartmentState runspaceApartmentState, PSThreadOptions runspaceThreadOptions, bool isRemote) + private static void VerifyThreadSettings(PSInvocationSettings settings, ApartmentState runspaceApartmentState, PSThreadOptions runspaceThreadOptions, bool isRemote) { ApartmentState apartmentState; @@ -5827,7 +5827,7 @@ internal PSObject ToPSObjectForRemoting() return powerShellAsPSObject; } - private List CommandsAsListOfPSObjects(CommandCollection commands, Version psRPVersion) + private static List CommandsAsListOfPSObjects(CommandCollection commands, Version psRPVersion) { List commandsAsListOfPSObjects = new List(commands.Count); foreach (Command command in commands) diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index f4e7a454cfa..a29434d0d4a 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -925,7 +925,7 @@ public void EmitLoadField(FieldInfo field) Emit(GetLoadField(field)); } - private Instruction GetLoadField(FieldInfo field) + private static Instruction GetLoadField(FieldInfo field) { lock (s_loadFields) { diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 400313fe76a..0fc928d444b 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -1025,7 +1025,7 @@ private void CompileConditionalExpression(Expression expr, bool asVoid) #region Loops - private void CompileLoopExpression(Expression expr) + private static void CompileLoopExpression(Expression expr) { // var node = (LoopExpression)expr; // var enterLoop = new EnterLoopInstruction(node, _locals, _compilationThreshold, _instructions.Count); @@ -2004,7 +2004,8 @@ private void CompileNoLabelPush(Expression expr) case ExpressionType.Index: CompileIndexExpression(expr); break; case ExpressionType.Label: CompileLabelExpression(expr); break; case ExpressionType.RuntimeVariables: CompileRuntimeVariablesExpression(expr); break; - case ExpressionType.Loop: CompileLoopExpression(expr); break; + case ExpressionType.Loop: + CompileLoopExpression(expr); break; case ExpressionType.Switch: CompileSwitchExpression(expr); break; case ExpressionType.Throw: CompileThrowUnaryExpression(expr, expr.Type == typeof(void)); break; case ExpressionType.Try: CompileTryExpression(expr); break; diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index a9a87eee1c0..5d632d55a38 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -2045,7 +2045,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) } } - private Action CompileTree(Expression> lambda, CompileInterpretChoice compileInterpretChoice) + private static Action CompileTree(Expression> lambda, CompileInterpretChoice compileInterpretChoice) { if (lambda == null) { @@ -2589,7 +2589,7 @@ private Expression> CompileSingleLambda( return Expression.Lambda>(body, funcName, new[] { s_functionContext }); } - private void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List exprs) + private static void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAndUsings, List exprs) { // We don't postpone load assemblies, import modules from 'using' to the moment, when enclosed scriptblock is executed. // We do loading, when root of the script is compiled. @@ -6353,7 +6353,7 @@ internal Expression InvokeMember( return nullConditional ? GetNullConditionalWrappedExpression(target, dynamicExprFromBinder) : dynamicExprFromBinder; } - private Expression InvokeBaseCtorMethod(PSMethodInvocationConstraints constraints, Expression target, IEnumerable args) + private static Expression InvokeBaseCtorMethod(PSMethodInvocationConstraints constraints, Expression target, IEnumerable args) { var callInfo = new CallInfo(args.Count()); var binder = PSInvokeBaseCtorBinder.Get(callInfo, constraints); diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index cffb32e7092..7ffc308369f 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -921,7 +921,7 @@ private void DefineConstructor(IParameterMetadataProvider ipmp, ReadOnlyCollecti (i, n) => ctor.DefineParameter(i, ParameterAttributes.None, n)); } - private string GetMetaDataName(string name, int numberOfParameters) + private static string GetMetaDataName(string name, int numberOfParameters) { int currentId = Interlocked.Increment(ref s_globalCounter); string metaDataName = name + "_" + numberOfParameters + "_" + currentId; diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index eea0c4958c7..cac1019ea67 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -4574,7 +4574,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) return null; } - private bool TryUseTokenAsSimpleName(Token token) + private static bool TryUseTokenAsSimpleName(Token token) { if (token.Kind == TokenKind.Identifier || token.Kind == TokenKind.DynamicKeyword @@ -4587,7 +4587,7 @@ private bool TryUseTokenAsSimpleName(Token token) return false; } - private void RecordErrorAsts(Ast errAst, ref List astsOnError) + private static void RecordErrorAsts(Ast errAst, ref List astsOnError) { if (errAst == null) { @@ -4602,7 +4602,7 @@ private void RecordErrorAsts(Ast errAst, ref List astsOnError) astsOnError.Add(errAst); } - private void RecordErrorAsts(IEnumerable errAsts, ref List astsOnError) + private static void RecordErrorAsts(IEnumerable errAsts, ref List astsOnError) { if (errAsts == null || !errAsts.Any()) { @@ -8013,7 +8013,7 @@ internal void ReportError(ParseError error) SaveError(error); } - private void ReportErrorsAsWarnings(Collection errors) + private static void ReportErrorsAsWarnings(Collection errors) { var executionContext = Runspaces.Runspace.DefaultRunspace.ExecutionContext; if (executionContext != null && executionContext.InternalHost != null && executionContext.InternalHost.UI != null) diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 37320de83d1..d7ef5b4cae6 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -480,7 +480,7 @@ public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueCo // this can throw, but there really isn't useful information we can add, as the // offending expression will be presented in the case of any failure // - private object GetSingleValueFromTarget(object target, object index) + private static object GetSingleValueFromTarget(object target, object index) { var targetString = target as string; if (targetString != null) @@ -517,7 +517,7 @@ private object GetSingleValueFromTarget(object target, object index) throw new Exception(); } - private object GetIndexedValueFromTarget(object target, object index) + private static object GetIndexedValueFromTarget(object target, object index) { var indexArray = index as object[]; return indexArray != null ? ((object[])indexArray).Select(i => GetSingleValueFromTarget(target, i)).ToArray() : GetSingleValueFromTarget(target, index); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index cd91dd1331a..3afd10ff6e2 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -62,12 +62,12 @@ private bool AnalyzingStaticMember() return fnMemberAst != null ? fnMemberAst.IsStatic : ((PropertyMemberAst)currentMember).IsStatic; } - private bool IsValidAttributeArgument(Ast ast, IsConstantValueVisitor visitor) + private static bool IsValidAttributeArgument(Ast ast, IsConstantValueVisitor visitor) { return (bool)ast.Accept(visitor); } - private (string id, string msg) GetNonConstantAttributeArgErrorExpr(IsConstantValueVisitor visitor) + private static (string id, string msg) GetNonConstantAttributeArgErrorExpr(IsConstantValueVisitor visitor) { if (visitor.CheckingClassAttributeArguments) { @@ -1183,7 +1183,7 @@ public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressio return AstVisitAction.Continue; } - private void CheckMemberAccess(MemberExpressionAst ast) + private static void CheckMemberAccess(MemberExpressionAst ast) { // If the member access is not constant, it may be considered suspicious if (ast.Member is not ConstantExpressionAst) @@ -1201,7 +1201,7 @@ private void CheckMemberAccess(MemberExpressionAst ast) } // Mark all of the parents of an AST as suspicious - private void MarkAstParentsAsSuspicious(Ast ast) + private static void MarkAstParentsAsSuspicious(Ast ast) { Ast targetAst = ast; var parent = ast; diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index ca4acbb0269..45f278b6b5a 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1699,7 +1699,7 @@ private bool TryGetTypeFromMember( return false; } - private void AddTypesFromMethodCacheEntry( + private static void AddTypesFromMethodCacheEntry( DotNetAdapter.MethodCacheEntry methodCacheEntry, List result, bool isInvokeMemberExpressionAst) @@ -2021,7 +2021,7 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List /// The inferred types all the items in the array. /// The inferred strongly typed array type. - private PSTypeName GetArrayType(IEnumerable inferredTypes) + private static PSTypeName GetArrayType(IEnumerable inferredTypes) { PSTypeName foundType = null; foreach (PSTypeName inferredType in inferredTypes) @@ -2077,7 +2077,7 @@ private PSTypeName GetArrayType(IEnumerable inferredTypes) /// /// The type to infer enumerated item type from. /// The inferred enumerated item type. - private Type GetMostSpecificEnumeratedItemType(Type enumerableType) + private static Type GetMostSpecificEnumeratedItemType(Type enumerableType) { if (enumerableType.IsArray) { @@ -2153,7 +2153,7 @@ private Type GetMostSpecificEnumeratedItemType(Type enumerableType) /// The value of if it can be used to infer a specific /// enumerated type, otherwise . /// - private Type GetGenericCollectionLikeInterface( + private static Type GetGenericCollectionLikeInterface( Type interfaceType, ref bool hasSeenNonGeneric, ref bool hasSeenDictionaryEnumerator) @@ -2257,7 +2257,7 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression /// The potentially enumerable types to infer enumerated type from. /// /// The enumerated item types. - private IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) + private static IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) { foreach (PSTypeName maybeEnumerableType in enumerableTypes) { diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 00ea51f71e4..fb753652c93 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -166,7 +166,7 @@ internal void LogExecutionException(Exception exception) Log(message, null, PipelineExecutionStatus.Error); } - private string GetCommand(InvocationInfo invocationInfo) + private static string GetCommand(InvocationInfo invocationInfo) { if (invocationInfo == null) return string.Empty; @@ -179,7 +179,7 @@ private string GetCommand(InvocationInfo invocationInfo) return string.Empty; } - private string GetCommand(Exception exception) + private static string GetCommand(Exception exception) { IContainsErrorRecord icer = exception as IContainsErrorRecord; if (icer != null && icer.ErrorRecord != null) diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 2238fe8eff4..b32e2e38733 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -5998,7 +5998,7 @@ public override string ToString() return string.Format(CultureInfo.InvariantCulture, "SetMember: {0}{1} ver:{2}", _static ? "static " : string.Empty, Name, _getMemberBinder._version); } - private Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) + private static Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) { if (transformationAttributes == null) { @@ -6286,7 +6286,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy if (value.Value == null) { expr = Expression.Block( - Expression.Assign(lhs, this.GetTransformedExpression(argumentTransformationAttributes, Expression.Constant(null, lhsType))), + Expression.Assign(lhs, GetTransformedExpression(argumentTransformationAttributes, Expression.Constant(null, lhsType))), ExpressionCache.NullConstant); } else @@ -6295,7 +6295,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy Expression assignmentExpression; if (transformationNeeded) { - var transformedExpr = this.GetTransformedExpression(argumentTransformationAttributes, value.Expression); + var transformedExpr = GetTransformedExpression(argumentTransformationAttributes, value.Expression); assignmentExpression = DynamicExpression.Dynamic(PSConvertBinder.Get(nullableUnderlyingType), nullableUnderlyingType, transformedExpr); } else @@ -6317,7 +6317,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy if (transformationNeeded) { assignedValue = DynamicExpression.Dynamic(PSConvertBinder.Get(lhsType), lhsType, - this.GetTransformedExpression(argumentTransformationAttributes, value.Expression)); + GetTransformedExpression(argumentTransformationAttributes, value.Expression)); } else { diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index 30537cbc619..a01f67b81e2 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -2955,6 +2955,10 @@ private bool UnknownTagsAllowed } } + [SuppressMessage( + "Performance", + "CA1822:Mark members as static", + Justification = "Accesses instance members in preprocessor branch.")] private bool DuplicateRefIdsAllowed { get @@ -3194,7 +3198,7 @@ private void CheckIfStopping() internal const string CimHashCodeProperty = "Hash"; internal const string CimMiXmlProperty = "MiXml"; - private bool RehydrateCimInstanceProperty( + private static bool RehydrateCimInstanceProperty( CimInstance cimInstance, PSPropertyInfo deserializedProperty, HashSet namesOfModifiedProperties) @@ -5928,7 +5932,7 @@ private PSPrimitiveDictionary(System.Runtime.Serialization.SerializationInfo inf #region Plumbing to make Hashtable reject all non-primitive types - private string VerifyKey(object key) + private static string VerifyKey(object key) { key = PSObject.Base(key); string keyAsString = key as string; @@ -6028,7 +6032,7 @@ private void VerifyValue(object value) /// public override void Add(object key, object value) { - string keyAsString = this.VerifyKey(key); + string keyAsString = VerifyKey(key); this.VerifyValue(value); base.Add(keyAsString, value); } @@ -6056,7 +6060,7 @@ public override object this[object key] set { - string keyAsString = this.VerifyKey(key); + string keyAsString = VerifyKey(key); this.VerifyValue(value); base[keyAsString] = value; } From 8d4869372e2dd3b53880202290af3a8f4eb1513e Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 08:16:31 +0000 Subject: [PATCH 077/138] Mark private members as static part 10 (#14235) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822 --- .../CoreCLR/CorePsAssemblyLoadContext.cs | 12 +++++----- .../common/DisplayDatabase/XmlLoaderBase.cs | 2 +- .../displayResourceManagerCache.cs | 2 +- .../common/DisplayDatabase/typeDataQuery.cs | 2 +- .../DisplayDatabase/typeDataXmlLoader.cs | 4 ++-- .../common/Utilities/Mshexpression.cs | 2 +- .../cimSupport/cmdletization/ScriptWriter.cs | 10 ++++----- .../other/ciminstancetypeadapter.cs | 4 ++-- .../help/CommandHelpProvider.cs | 4 ++-- .../help/HelpFileHelpProvider.cs | 2 +- .../help/MUIFileSearcher.cs | 2 +- .../help/MamlNode.cs | 2 +- .../help/SaveHelpCommand.cs | 2 +- .../help/UpdatableHelpSystem.cs | 8 +++---- .../help/UpdateHelpCommand.cs | 2 +- .../namespaces/FileSystemProvider.cs | 10 ++++----- .../namespaces/LocationGlobber.cs | 2 +- .../namespaces/RegistryProvider.cs | 6 ++--- .../security/SecurityManager.cs | 22 +++++++++---------- .../utils/ObjectReader.cs | 4 ++-- .../utils/PowerShellETWTracer.cs | 2 +- 21 files changed, 53 insertions(+), 53 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 12f575b5175..adc57710620 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -393,7 +393,7 @@ private bool TryFindInGAC(AssemblyName assemblyName, out string assemblyFilePath } // Find the assembly under 'gacRoot' and select the latest version. - private bool FindInGac(string gacRoot, AssemblyName assemblyName, out string assemblyPath) + private static bool FindInGac(string gacRoot, AssemblyName assemblyName, out string assemblyPath) { bool assemblyFound = false; assemblyPath = null; @@ -430,7 +430,7 @@ private bool FindInGac(string gacRoot, AssemblyName assemblyName, out string ass /// /// Try to get the specified assembly from cache. /// - private bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asmLoaded) + private static bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asmLoaded) { if (s_assemblyCache.TryGetValue(assemblyName.Name, out asmLoaded)) { @@ -454,7 +454,7 @@ private bool TryGetAssemblyFromCache(AssemblyName assemblyName, out Assembly asm /// AssemblyName of the requested assembly. /// AssemblyName of the loaded assembly. /// - private bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loadedAssembly) + private static bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loadedAssembly) { // // We use the same rules as CoreCLR loader to compare the requested assembly and loaded assembly: @@ -501,7 +501,7 @@ private bool IsAssemblyMatching(AssemblyName requestedAssembly, AssemblyName loa /// /// The assembly strong name of a CoreCLR Trusted_Platform_Assembly /// - private Assembly GetTrustedPlatformAssembly(string tpaStrongName) + private static Assembly GetTrustedPlatformAssembly(string tpaStrongName) { // We always depend on the default context to load the TPAs that are recorded in // the type catalog. @@ -517,7 +517,7 @@ private Assembly GetTrustedPlatformAssembly(string tpaStrongName) /// /// Throw FileLoadException. /// - private void ThrowFileLoadException(string errorTemplate, params object[] args) + private static void ThrowFileLoadException(string errorTemplate, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, errorTemplate, args); throw new FileLoadException(message); @@ -526,7 +526,7 @@ private void ThrowFileLoadException(string errorTemplate, params object[] args) /// /// Throw FileNotFoundException. /// - private void ThrowFileNotFoundException(string errorTemplate, params object[] args) + private static void ThrowFileNotFoundException(string errorTemplate, params object[] args) { string message = string.Format(CultureInfo.CurrentCulture, errorTemplate, args); throw new FileNotFoundException(message); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 742f9936ea8..a7e7df0a5d7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -100,7 +100,7 @@ internal void LogEntry(XmlLoaderLoggerEntry entry) WriteToTracer(entry); } - private void WriteToTracer(XmlLoaderLoggerEntry entry) + private static void WriteToTracer(XmlLoaderLoggerEntry entry) { if (entry.entryType == XmlLoaderLoggerEntry.EntryType.Error) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 43e1d0ea6fc..fbdd1287a02 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -176,7 +176,7 @@ internal Assembly ResolveAssemblyName(string assemblyName) return retVal; } - private Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName) + private static Assembly ResolveAssemblyNameInLoadedAssemblies(string assemblyName, bool fullName) { Assembly result = null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 9547ac1e072..60953d22c26 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -219,7 +219,7 @@ private int MatchTypeIndex(string typeName, PSObject currentObject, PSPropertyEx return BestMatchIndexUndefined; } - private bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) + private static bool MatchCondition(PSObject currentObject, PSPropertyExpression ex) { if (ex == null) return true; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 90a44c848b2..b68288ff9ab 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -586,7 +586,7 @@ private ControlBase LoadTableControlFromObjectModel(TableControl table, int view /// /// /// - private void LoadHeadersSectionFromObjectModel(TableControlBody tableBody, List headers) + private static void LoadHeadersSectionFromObjectModel(TableControlBody tableBody, List headers) { foreach (TableControlColumnHeader header in headers) { @@ -746,7 +746,7 @@ private ExpressionToken LoadExpressionFromObjectModel(DisplayEntry displayEntry, /// Load EntrySelectedBy (TypeName) into AppliesTo. /// /// - private AppliesTo LoadAppliesToSectionFromObjectModel(List selectedBy, List condition) + private static AppliesTo LoadAppliesToSectionFromObjectModel(List selectedBy, List condition) { AppliesTo appliesTo = new AppliesTo(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 8f296b11e85..68921ddb0e8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -354,7 +354,7 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) } } - private PSObject IfHashtableWrapAsPSCustomObject(PSObject target, out bool wrapped) + private static PSObject IfHashtableWrapAsPSCustomObject(PSObject target, out bool wrapped) { wrapped = false; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index 1d5bf0e26da..e72f9606e12 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -234,7 +234,7 @@ private string GetCmdletName(CommonCmdletMetadata cmdletMetadata) return verb + "-" + noun; } - private string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) + private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) { // Generate the script for the Alias and Obsolete Attribute if any is declared in CDXML StringBuilder attributes = new StringBuilder(150); @@ -1444,7 +1444,7 @@ private void GenerateMethodParametersProcessing( } } - private void GenerateIfBoundParameter( + private static void GenerateIfBoundParameter( IEnumerable commonParameterSets, IEnumerable methodParameterSets, ParameterMetadata cmdletParameterMetadata, @@ -1874,7 +1874,7 @@ private string GetHelpDirectiveForExternalHelp() private void WriteCmdlet(TextWriter output, StaticCmdletMetadata staticCmdlet) { - string attributeString = this.GetCmdletAttributes(staticCmdlet.CmdletMetadata); + string attributeString = GetCmdletAttributes(staticCmdlet.CmdletMetadata); Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); @@ -1959,7 +1959,7 @@ private static void AddPassThruParameter(IDictionary private void WriteCmdlet(TextWriter output, InstanceCmdletMetadata instanceCmdlet) { - string attributeString = this.GetCmdletAttributes(instanceCmdlet.CmdletMetadata); + string attributeString = GetCmdletAttributes(instanceCmdlet.CmdletMetadata); Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); @@ -2066,7 +2066,7 @@ private void WriteGetCmdlet(TextWriter output) CommonCmdletMetadata cmdletMetadata = this.GetGetCmdletMetadata(); Dbg.Assert(cmdletMetadata != null, "xsd should ensure that cmdlet metadata element is always present"); CommandMetadata commandMetadata = this.GetCommandMetadata(cmdletMetadata); - string attributeString = this.GetCmdletAttributes(cmdletMetadata); + string attributeString = GetCmdletAttributes(cmdletMetadata); GetCmdletParameters getCmdletParameters = this.GetGetCmdletParameters(null); if (!string.IsNullOrEmpty(getCmdletParameters.DefaultCmdletParameterSet)) diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index c05ced76d20..4220c3b62bd 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -242,7 +242,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) throw new ArgumentNullException(nameof(adaptedProperty)); } - private void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList typeNamesWithoutNamespace, string namespaceName, string className) + private static void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList typeNamesWithoutNamespace, string namespaceName, string className) { if (!string.IsNullOrEmpty(namespaceName)) { @@ -258,7 +258,7 @@ private void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList GetInheritanceChain(CimInstance cimInstance) + private static List GetInheritanceChain(CimInstance cimInstance) { List inheritanceChain = new List(); CimClass cimClass = cimInstance.CimClass; diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 5feb3c00189..05a4e48af70 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -84,7 +84,7 @@ internal override HelpCategory HelpCategory #region Help Provider Interface - private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out string moduleDir, out string nestedModulePath) + private static void GetModulePaths(CommandInfo commandInfo, out string moduleName, out string moduleDir, out string nestedModulePath) { Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); @@ -132,7 +132,7 @@ private void GetModulePaths(CommandInfo commandInfo, out string moduleName, out } } - private string GetHelpName(CommandInfo commandInfo) + private static string GetHelpName(CommandInfo commandInfo) { Dbg.Assert(commandInfo != null, "Caller should verify that commandInfo != null"); diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 36ffeb58675..8900a7167b3 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -268,7 +268,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool } } - private void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion) + private static void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion) { moduleVersion = null; moduleName = null; diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 301369959aa..bf6244fe3eb 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -113,7 +113,7 @@ private void SearchForFiles() } } - private string[] GetFiles(string path, string pattern) + private static string[] GetFiles(string path, string pattern) { #if UNIX // On Linux, file names are case sensitive, so we need to add diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 4392dffd0ca..fe4e803a294 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -646,7 +646,7 @@ private PSObject[] GetMamlFormattingPSObjects(XmlNode xmlNode) /// /// /// - private int GetParaMamlNodeCount(XmlNodeList nodes) + private static int GetParaMamlNodeCount(XmlNodeList nodes) { int i = 0; diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 3c4d18af00a..7059550730b 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -484,7 +484,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input return inputData; } - private bool TryConvertFromDeserializedModuleInfo(object inputData, out PSModuleInfo moduleInfo) + private static bool TryConvertFromDeserializedModuleInfo(object inputData, out PSModuleInfo moduleInfo) { moduleInfo = null; PSObject pso = inputData as PSObject; diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index f7a476d5d07..d302f7b9cae 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -621,7 +621,7 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo /// Xml schema. /// Validation event handler. /// HelpInfo or HelpContent? - private XmlDocument CreateValidXmlDocument(string xml, string ns, string schema, ValidationEventHandler handler, + private static XmlDocument CreateValidXmlDocument(string xml, string ns, string schema, ValidationEventHandler handler, bool helpInfo) { XmlReaderSettings settings = new XmlReaderSettings(); @@ -998,7 +998,7 @@ internal void GenerateHelpInfo(string moduleName, Guid moduleGuid, string conten /// Removes the read only attribute. /// /// - private void RemoveReadOnly(string path) + private static void RemoveReadOnly(string path) { if (File.Exists(path)) { @@ -1093,7 +1093,7 @@ internal void InstallHelpContent(UpdatableHelpCommandType commandType, Execution } #if UNIX - private bool ExpandArchive(string source, string destination) + private static bool ExpandArchive(string source, string destination) { bool sucessfulDecompression = false; @@ -1125,7 +1125,7 @@ private bool ExpandArchive(string source, string destination) /// Source path. /// Destination path. /// Is set to false if we find a single file placeholder.txt in cab. This means we no longer need to install help files. - private void UnzipHelpContent(ExecutionContext context, string srcPath, string destPath, out bool needToCopy) + private static void UnzipHelpContent(ExecutionContext context, string srcPath, string destPath, out bool needToCopy) { needToCopy = true; diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 9580027e989..01b17cbad7e 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -488,7 +488,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, /// /// /// - private void ThrowPathMustBeValidContainersException(string path, Exception e) + private static void ThrowPathMustBeValidContainersException(string path, Exception e) { throw new UpdatableHelpSystemException("PathMustBeValidContainers", StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument, diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 987faf46858..501a3aa5c25 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -709,7 +709,7 @@ private void WinMapNetworkDrive(PSDriveInfo drive) /// /// /// - private bool IsNetworkMappedDrive(PSDriveInfo drive) + private static bool IsNetworkMappedDrive(PSDriveInfo drive) { bool shouldMapNetworkDrive = (drive != null && !string.IsNullOrEmpty(drive.Root) && PathIsNetworkPath(drive.Root)) && (drive.Persist || (drive.Credential != null && !drive.Credential.Equals(PSCredential.Empty))); @@ -789,7 +789,7 @@ private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) /// PS Drive Info. /// /// True if the drive can be persisted or else false. - private bool IsSupportedDriveForPersistence(PSDriveInfo drive) + private static bool IsSupportedDriveForPersistence(PSDriveInfo drive) { bool isSupportedDriveForPersistence = false; if (drive != null && !string.IsNullOrEmpty(drive.Name) && drive.Name.Length == 1) @@ -4203,7 +4203,7 @@ private void RemoveFunctionsPSCopyFileFromRemoteSession(System.Management.Automa SafeInvokeCommand.Invoke(ps, this, null, false); } - private bool ValidRemoteSessionForScripting(Runspace runspace) + private static bool ValidRemoteSessionForScripting(Runspace runspace) { if (runspace is not RemoteRunspace) { @@ -4768,7 +4768,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath // Returns a hash table with metadata about this file info. // - private Hashtable GetFileMetadata(FileInfo file) + private static Hashtable GetFileMetadata(FileInfo file) { Hashtable metadata = new Hashtable(); @@ -6137,7 +6137,7 @@ private void CopyAndDelete(DirectoryInfo directory, string destination, bool for } #if !UNIX - private bool IsSameWindowsVolume(string source, string destination) + private static bool IsSameWindowsVolume(string source, string destination) { FileInfo src = new FileInfo(source); FileInfo dest = new FileInfo(destination); diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 1282b999031..e4ab1f3cfc5 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -2272,7 +2272,7 @@ internal string GenerateRelativePath( return driveRootRelativeWorkingPath; } - private bool HasRelativePathTokens(string path) + private static bool HasRelativePathTokens(string path) { string comparePath = path.Replace('/', '\\'); diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 29e37a163e4..1898c960620 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -2956,7 +2956,7 @@ private string NormalizePath(string path) return result; } - private bool HasRelativePathTokens(string path) + private static bool HasRelativePathTokens(string path) { return ( path.StartsWith('\\') || @@ -3195,7 +3195,7 @@ private object ResetRegistryKeyValue(IRegistryWrapper key, string valueName) /// /// true if the path is empty, a \ or a /, else false /// - private bool IsHiveContainer(string path) + private static bool IsHiveContainer(string path) { bool result = false; if (path == null) @@ -4114,7 +4114,7 @@ private bool ParseKind(string type, out RegistryValueKind kind) /// /// A string containing the default value name. /// - private string LocalizedDefaultToken => "(default)"; + private static string LocalizedDefaultToken => "(default)"; /// /// Converts an empty or null userEnteredPropertyName to the localized diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 1de51558040..1b554ad3940 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -368,7 +368,7 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r return policyCheckPassed; } - private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature) + private static bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Exception reason, Signature signature) { bool policyCheckPassed = false; @@ -405,7 +405,7 @@ private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Excep return policyCheckPassed; } - private bool IsLocalFile(string filename) + private static bool IsLocalFile(string filename) { #if UNIX return true; @@ -425,7 +425,7 @@ private bool IsLocalFile(string filename) // Checks that a publisher is trusted by the system or is one of // the signed product binaries - private bool IsTrustedPublisher(Signature signature, string file) + private static bool IsTrustedPublisher(Signature signature, string file) { // Get the thumbprint of the current signature X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -444,7 +444,7 @@ private bool IsTrustedPublisher(Signature signature, string file) return false; } - private bool IsUntrustedPublisher(Signature signature, string file) + private static bool IsUntrustedPublisher(Signature signature, string file) { // Get the thumbprint of the current signature X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -467,7 +467,7 @@ private bool IsUntrustedPublisher(Signature signature, string file) /// Trust a publisher by adding it to the "Trusted Publishers" store. /// /// - private void TrustPublisher(Signature signature) + private static void TrustPublisher(Signature signature) { // Get the certificate of the signer X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -485,7 +485,7 @@ private void TrustPublisher(Signature signature) } } - private void UntrustPublisher(Signature signature) + private static void UntrustPublisher(Signature signature) { // Get the certificate of the signer X509Certificate2 signerCertificate = signature.SignerCertificate; @@ -516,7 +516,7 @@ private void UntrustPublisher(Signature signature) } } - private Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) + private static Signature GetSignatureWithEncodingRetry(string path, ExternalScriptInfo script) { string verificationContents = System.Text.Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; Signature signature = SignatureHelper.GetSignature(path, verificationContents); @@ -640,7 +640,7 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, return allowRun; } - private RunPromptDecision AuthenticodePrompt(string path, + private static RunPromptDecision AuthenticodePrompt(string path, Signature signature, PSHost host) { @@ -713,7 +713,7 @@ private RunPromptDecision AuthenticodePrompt(string path, return decision; } - private RunPromptDecision RemoteFilePrompt(string path, PSHost host) + private static RunPromptDecision RemoteFilePrompt(string path, PSHost host) { if ((host == null) || (host.UI == null)) { @@ -743,7 +743,7 @@ private RunPromptDecision RemoteFilePrompt(string path, PSHost host) } } - private Collection GetAuthenticodePromptChoices() + private static Collection GetAuthenticodePromptChoices() { Collection choices = new Collection(); @@ -764,7 +764,7 @@ private Collection GetAuthenticodePromptChoices() return choices; } - private Collection GetRemoteFilePromptChoices() + private static Collection GetRemoteFilePromptChoices() { Collection choices = new Collection(); diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index ccbc176406b..f06243ddd5b 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -617,7 +617,7 @@ protected override void Dispose(bool disposing) } } - private ReturnType ConvertToReturnType(object inputObject) + private static ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) @@ -793,7 +793,7 @@ public override ReturnType Peek() /// /// Input object to convert. /// Input object converted to the specified return type. - private ReturnType ConvertToReturnType(object inputObject) + private static ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index 7631d760b2d..e7172cfd666 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -988,7 +988,7 @@ public void Dispose() /// public PowerShellTraceTask Task { get; set; } = PowerShellTraceTask.None; - private bool IsEtwSupported + private static bool IsEtwSupported { get { From 0fd914fee16ae3eb7a4c5e9bd24629f7c2e2c482 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 27 Nov 2020 08:17:38 +0000 Subject: [PATCH 078/138] Fix RCS1188: Remove redundant auto-property initialization part 1 (#14261) https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/RCS1188.md --- .../CimCommandBase.cs | 10 +++++----- .../CimSessionProxy.cs | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 2690c209f89..059f58a97b2 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -38,12 +38,12 @@ internal ParameterDefinitionEntry(string parameterSetName, bool mandatory) /// /// Property ParameterSetName. /// - internal string ParameterSetName { get; } = null; + internal string ParameterSetName { get; } /// /// Whether the parameter is mandatory to the set. /// - internal bool IsMandatory { get; } = false; + internal bool IsMandatory { get; } } /// @@ -99,7 +99,7 @@ internal void reset() /// /// Property DefaultParameterSet /// - internal bool IsDefaultParameterSet { get; } = false; + internal bool IsDefaultParameterSet { get; } /// /// Property MandatoryParameterCount @@ -109,12 +109,12 @@ internal void reset() /// /// Property IsValueSet /// - internal bool IsValueSet { get; set; } = false; + internal bool IsValueSet { get; set; } /// /// Property IsValueSetAtBeginProcess /// - internal bool IsValueSetAtBeginProcess { get; set; } = false; + internal bool IsValueSetAtBeginProcess { get; set; } /// /// Property SetMandatoryParameterCount diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index a442d354f4c..40a1f390b0d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -1481,7 +1481,7 @@ protected virtual void PostOperationDeleteEvent(OperationEventArgs args) /// The current CimInstance object, against which issued /// current operation, it could be null. /// - internal CimInstance TargetCimInstance { get; private set; } = null; + internal CimInstance TargetCimInstance { get; private set; } internal bool IsTemporaryCimSession { get; private set; } @@ -2193,7 +2193,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) #region private members - internal CimNewCimInstance NewCimInstanceOperation { get; } = null; + internal CimNewCimInstance NewCimInstanceOperation { get; } #endregion } From db94377b3a69511280d329e64375475f6d7513b8 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 30 Nov 2020 17:13:12 +0000 Subject: [PATCH 079/138] Enable SA1000: Keywords should be spaced correctly (#13973) https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1000.md --- .globalconfig | 2 +- .../commands/utility/UnblockFile.cs | 4 ++-- .../host/msh/ProgressPane.cs | 4 ++-- src/System.Management.Automation/engine/TypeMetadata.cs | 2 +- test/tools/TestExe/TestExe.cs | 2 +- test/tools/WebListener/Controllers/ResumeController.cs | 8 ++++---- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.globalconfig b/.globalconfig index 6e4858fb0e4..e853c28d46a 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1012,7 +1012,7 @@ dotnet_diagnostic.SA0001.severity = none dotnet_diagnostic.SA0002.severity = none # SA1000: Keywords should be spaced correctly -dotnet_diagnostic.SA1000.severity = none +dotnet_diagnostic.SA1000.severity = warning # SA1001: Commas should be spaced correctly dotnet_diagnostic.SA1001.severity = none diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index 1d77f88b880..5c297ed86d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -147,10 +147,10 @@ protected override void ProcessRecord() foreach (string path in pathsToProcess) { - if(IsBlocked(path)) + if (IsBlocked(path)) { UInt32 result = RemoveXattr(path, MacBlockAttribute, RemovexattrFollowSymLink); - if(result != 0) + if (result != 0) { string errorMessage = string.Format(CultureInfo.CurrentUICulture, UnblockFileStrings.UnblockError, path); Exception e = new InvalidOperationException(errorMessage); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 9edc44a0aab..7918f6f6814 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -102,9 +102,9 @@ class ProgressPane // create cleared region to clear progress bar later _savedRegion = tempProgressRegion; - for(int row = 0; row < rows; row++) + for (int row = 0; row < rows; row++) { - for(int col = 0; col < cols; col++) + for (int col = 0; col < cols; col++) { _savedRegion[row, col].Character = ' '; } diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index ce5bb55432a..31a6adeab73 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -978,7 +978,7 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) string or = string.Empty; string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); - foreach(string regexOption in regexOptionEnumValues) + foreach (string regexOption in regexOptionEnumValues) { System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions) Enum.Parse( typeof(System.Text.RegularExpressions.RegexOptions), diff --git a/test/tools/TestExe/TestExe.cs b/test/tools/TestExe/TestExe.cs index c8f91d4d38e..0eac8074de0 100644 --- a/test/tools/TestExe/TestExe.cs +++ b/test/tools/TestExe/TestExe.cs @@ -13,7 +13,7 @@ private static int Main(string[] args) { if (args.Length > 0) { - switch(args[0].ToLowerInvariant()) + switch (args[0].ToLowerInvariant()) { case "-echoargs": EchoArgs(args); diff --git a/test/tools/WebListener/Controllers/ResumeController.cs b/test/tools/WebListener/Controllers/ResumeController.cs index ebcfad40d78..623744ab7d8 100644 --- a/test/tools/WebListener/Controllers/ResumeController.cs +++ b/test/tools/WebListener/Controllers/ResumeController.cs @@ -30,12 +30,12 @@ public async void Index() if (TryGetRangeHeader(out rangeHeader)) { var range = GetRange(rangeHeader); - if(range.From != null) + if (range.From != null) { from = (int)range.From; } - if(range.To != null) + if (range.To != null) { to = (int)range.To; } @@ -49,7 +49,7 @@ public async void Index() return; } - if(to >= FileBytes.Length || from >= FileBytes.Length) + if (to >= FileBytes.Length || from >= FileBytes.Length) { Response.StatusCode = StatusCodes.Status416RequestedRangeNotSatisfiable; Response.Headers[HeaderNames.ContentRange] = $"bytes */{FileBytes.Length}"; @@ -113,7 +113,7 @@ private void SetResumeResponseHeaders() private bool TryGetRangeHeader(out string rangeHeader) { var rangeHeaderSv = new StringValues(); - if(Request.Headers.TryGetValue("Range", out rangeHeaderSv)) + if (Request.Headers.TryGetValue("Range", out rangeHeaderSv)) { rangeHeader = rangeHeaderSv.FirstOrDefault(); return true; From 00c70f9b62f2730d50a52646d1d23f9f9c1b5518 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 30 Nov 2020 20:51:48 +0000 Subject: [PATCH 080/138] Fix StyleCop and MarkdownLint CI failures (#14297) * Update link to xunit docs * Upgrade StyleCopAnalyzers to v1.2.0-beta.261 --- Analyzers.props | 2 +- docs/testing-guidelines/testing-guidelines.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Analyzers.props b/Analyzers.props index a6188d481fc..d0b16622b8c 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,5 +1,5 @@ - + diff --git a/docs/testing-guidelines/testing-guidelines.md b/docs/testing-guidelines/testing-guidelines.md index ce987beb6d0..e00c8352ee7 100755 --- a/docs/testing-guidelines/testing-guidelines.md +++ b/docs/testing-guidelines/testing-guidelines.md @@ -88,7 +88,7 @@ When you would want to do this: ### xUnit -For those tests which are not easily run via Pester, we have decided to use [xUnit](https://xunit.github.io/) as the test framework. +For those tests which are not easily run via Pester, we have decided to use [xUnit](https://xunit.net/) as the test framework. Currently, we have a minuscule number of tests which are run by using xUnit. ## Running tests outside of CI From 02ae54726e43057c6a39c640a19edbe5ef0945fb Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 1 Dec 2020 03:20:11 +0000 Subject: [PATCH 081/138] Remove unnecessary usings part 9 (#14288) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0005 --- src/Microsoft.WSMan.Runtime/WSManSessionOption.cs | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs index 79f0c0045e1..13dc8bbea2c 100644 --- a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs +++ b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -2,19 +2,8 @@ // Licensed under the MIT License. using System; -using System.ComponentModel; -using System.IO; -using System.Net; -using System.Reflection; -using System.Resources; -using System.Xml; - -using System.Collections; -using System.Collections.Generic; - -using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; +using System.Net; [assembly: CLSCompliant(true)] From 18717c529b90f69f4e3ab67ca238100b84064e71 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 2 Dec 2020 03:25:56 +0000 Subject: [PATCH 082/138] Enable IDE0075: SimplifyConditionalExpression (#14078) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0075 --- .globalconfig | 2 +- .../commands/utility/CsvCommands.cs | 2 +- .../commands/utility/Get-Error.cs | 2 +- .../host/msh/ProgressPane.cs | 3 +-- .../DotNetCode/Eventing/EventProvider.cs | 2 +- .../DotNetCode/Eventing/Reader/NativeWrapper.cs | 2 +- .../EmphasisInlineRenderer.cs | 2 +- .../common/FormattingObjectsDeserializer.cs | 2 +- .../engine/CommandParameter.cs | 2 +- .../engine/ExecutionContext.cs | 6 ++---- .../engine/ExternalScriptInfo.cs | 2 +- .../engine/GetCommandCommand.cs | 3 +-- .../engine/ScriptCommandProcessor.cs | 2 +- .../engine/hostifaces/InternalHostUserInterface.cs | 2 +- .../engine/hostifaces/PowerShell.cs | 2 +- .../engine/parser/ast.cs | 2 +- .../engine/remoting/client/ClientMethodExecutor.cs | 3 +-- .../engine/remoting/client/Job.cs | 2 +- .../remoting/client/RemoteRunspacePoolInternal.cs | 9 +++------ .../engine/remoting/client/RemotingProtocol2.cs | 4 ++-- .../engine/remoting/client/RunspaceRef.cs | 2 +- .../engine/remoting/commands/PSRemotingCmdlet.cs | 12 ++++++------ .../engine/remoting/commands/newrunspacecommand.cs | 2 +- .../engine/remoting/common/fragmentor.cs | 2 +- .../engine/remoting/fanin/WSManTransportManager.cs | 2 +- .../engine/remoting/server/ServerRemoteHost.cs | 2 +- .../remoting/server/ServerRunspacePoolDriver.cs | 6 ++---- .../engine/runtime/CompiledScriptBlock.cs | 4 ++-- .../namespaces/FileSystemProvider.cs | 2 +- 29 files changed, 40 insertions(+), 50 deletions(-) diff --git a/.globalconfig b/.globalconfig index e853c28d46a..1deb8dd7fbe 100644 --- a/.globalconfig +++ b/.globalconfig @@ -952,7 +952,7 @@ dotnet_diagnostic.IDE0073.severity = suggestion dotnet_diagnostic.IDE0074.severity = warning # IDE0075: SimplifyConditionalExpression -dotnet_diagnostic.IDE0075.severity = silent +dotnet_diagnostic.IDE0075.severity = warning # IDE0076: InvalidSuppressMessageAttribute dotnet_diagnostic.IDE0076.severity = silent diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 4b86f9d1a29..cbd9d4c36b4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -358,7 +358,7 @@ private void CreateFileStream() { using (StreamReader streamReader = PathUtils.OpenStreamReader(this, this.Path, Encoding, _isLiteralPath)) { - isCsvFileEmpty = streamReader.Peek() == -1 ? true : false; + isCsvFileEmpty = streamReader.Peek() == -1; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs index 7c2fdbe0c14..053f99f897d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs @@ -72,7 +72,7 @@ protected override void ProcessRecord() } index = 0; - bool addErrorIdentifier = errorRecords.Count > 1 ? true : false; + bool addErrorIdentifier = errorRecords.Count > 1; foreach (object errorRecord in errorRecords) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index 7918f6f6814..65f0267d0ed 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -208,8 +208,7 @@ class ProgressPane bool sizeChanged = (newRegion.GetLength(0) != _progressRegion.GetLength(0)) - || (newRegion.GetLength(1) != _progressRegion.GetLength(1)) - ? true : false; + || (newRegion.GetLength(1) != _progressRegion.GetLength(1)); _progressRegion = newRegion; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 072e6935624..5b8bd88d0fc 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -202,7 +202,7 @@ [In] void* callbackContext /// public bool IsEnabled() { - return (_enabled != 0) ? true : false; + return _enabled != 0; } /// diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 720af780642..ee29eb8ab10 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -1396,7 +1396,7 @@ public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) bool[] array = new bool[val.Count]; for (int i = 0; i < val.Count; i++) { - bool value = (Marshal.ReadInt32(ptr) != 0) ? true : false; + bool value = Marshal.ReadInt32(ptr) != 0; array[i] = value; ptr = new IntPtr((Int64)ptr + 4); } diff --git a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs index b1c4777a194..95a2bd1c7e8 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs @@ -12,7 +12,7 @@ internal class EmphasisInlineRenderer : VT100ObjectRenderer { protected override void Write(VT100Renderer renderer, EmphasisInline obj) { - renderer.Write(renderer.EscapeSequences.FormatEmphasis(obj.FirstChild.ToString(), isBold: obj.DelimiterCount == 2 ? true : false)); + renderer.Write(renderer.EscapeSequences.FormatEmphasis(obj.FirstChild.ToString(), isBold: obj.DelimiterCount == 2)); } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index d1b9523138b..285e4d4c02b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -290,7 +290,7 @@ internal int DeserializeIntMemberVariable(PSObject so, string property) internal bool DeserializeBoolMemberVariable(PSObject so, string property, bool cannotBeNull = true) { var val = DeserializeMemberVariable(so, property, typeof(bool), cannotBeNull); - return (val == null) ? false : (bool)val; + return val != null && (bool)val; } internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index b13cc94ad40..e6752ff023b 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -116,7 +116,7 @@ internal object ArgumentValue /// internal bool ArgumentToBeSplatted { - get { return _argument != null ? _argument.splatted : false; } + get { return _argument != null && _argument.splatted; } } /// diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 3f8156e32a4..9c484a7c56f 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -113,9 +113,7 @@ internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) context = LocalPipeline.GetExecutionContextFromTLS(); } - return (context != null) - ? context.IsStrictVersion(majorVersion) - : false; + return (context != null) && context.IsStrictVersion(majorVersion); } /// /// Check to see a specific version of strict mode is enabled. The check is always scoped, @@ -488,7 +486,7 @@ internal bool UseFullLanguageModeInDebugger { get { - return InitialSessionState != null ? InitialSessionState.UseFullLanguageModeInDebugger : false; + return InitialSessionState != null && InitialSessionState.UseFullLanguageModeInDebugger; } } diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 03e17d74dd5..b97da3b9970 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -443,7 +443,7 @@ internal bool RequiresElevation get { var data = GetRequiresData(); - return data == null ? false : data.IsElevationRequired; + return data != null && data.IsElevationRequired; } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 96be302f5e8..17efeb4ac73 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -1632,8 +1632,7 @@ private static PSObject GetParameterType(Type parameterType) new ArrayList(Enum.GetValues(parameterType)) : new ArrayList(); returnParameterType.Properties.Add(new PSNoteProperty("EnumValues", enumValues)); - bool hasFlagAttribute = (isArray) ? - ((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Length > 0) : false; + bool hasFlagAttribute = (isArray) && ((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Length > 0); returnParameterType.Properties.Add(new PSNoteProperty("HasFlagAttribute", hasFlagAttribute)); // Recurse into array elements. diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index 6b2e4d5d81c..99b685e07d2 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -274,7 +274,7 @@ private void Init() { _scriptBlock = base._scriptBlock; _obsoleteAttribute = _scriptBlock.ObsoleteAttribute; - _runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode > 0 ? false : UseLocalScope); + _runOptimizedCode = _scriptBlock.Compile(optimized: _context._debuggingMode <= 0 && UseLocalScope); _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimizedCode); if (UseLocalScope) diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 96379ee853f..b30d64d04db 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -78,7 +78,7 @@ public override public override bool SupportsVirtualTerminal { - get { return (_externalUI != null) ? _externalUI.SupportsVirtualTerminal : false; } + get { return _externalUI != null && _externalUI.SupportsVirtualTerminal; } } /// diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 627ca221fa3..a76dbe1c0b1 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -5546,7 +5546,7 @@ internal bool ConstructPipelineAndDoWork(Runspace rs, bool performSyncInvoke) LocalPipeline localPipeline = new LocalPipeline( lrs, _shell.Commands.Commands, - ((_settings != null) && (_settings.AddToHistory)) ? true : false, + (_settings != null && _settings.AddToHistory), _shell.IsNested, _inputStream, _outputStream, diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 60fac20f4bd..b9404afa738 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -3449,7 +3449,7 @@ internal bool IsReturnTypeVoid() if (ReturnType == null) return true; var typeName = ReturnType.TypeName as TypeName; - return typeName == null ? false : typeName.IsType(typeof(void)); + return typeName != null && typeName.IsType(typeof(void)); } internal Type GetReturnType() diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index b6c794f5474..120ca07a5af 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -98,8 +98,7 @@ internal static void Dispatch( if (hostPrivateData != null) { PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty; - hostAllowSetShouldExit = (allowSetShouldExit != null && allowSetShouldExit.Value is bool) ? - (bool)allowSetShouldExit.Value : false; + hostAllowSetShouldExit = allowSetShouldExit != null && allowSetShouldExit.Value is bool && (bool)allowSetShouldExit.Value; } } diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 6ca8ec75f4f..7fcc78a1c75 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -2968,7 +2968,7 @@ internal override bool CanDisconnect get { RemoteRunspace remoteRS = Runspace as RemoteRunspace; - return (remoteRS != null) ? remoteRS.CanDisconnect : false; + return remoteRS != null && remoteRS.CanDisconnect; } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 2e23d8ac667..94584c613f5 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -1426,8 +1426,7 @@ private static void UpdateWSManConnectionInfo( string compressionModeString = pspCompressionMode.Value as string; if (compressionModeString != null) { - wsmanConnectionInfo.UseCompression = compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase) - ? false : true; + wsmanConnectionInfo.UseCompression = !compressionModeString.Equals("NoCompression", StringComparison.OrdinalIgnoreCase); } } @@ -1436,8 +1435,7 @@ private static void UpdateWSManConnectionInfo( string encodingString = pspEncoding.Value as string; if (encodingString != null) { - wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase) - ? true : false; + wsmanConnectionInfo.UseUTF16 = encodingString.Equals("UTF16", StringComparison.OrdinalIgnoreCase); } } @@ -1446,8 +1444,7 @@ private static void UpdateWSManConnectionInfo( string machineProfileLoadedString = pspProfile.Value as string; if (machineProfileLoadedString != null) { - wsmanConnectionInfo.NoMachineProfile = machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase) - ? false : true; + wsmanConnectionInfo.NoMachineProfile = !machineProfileLoadedString.Equals("Yes", StringComparison.OrdinalIgnoreCase); } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index 512189dd71d..8b8908b6e61 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -233,7 +233,7 @@ internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) // Find out if this is an invoke and disconnect operation and if so whether the endpoint // supports disconnect. Throw exception if disconnect is not supported. - bool invokeAndDisconnect = (shell.Settings != null) ? shell.Settings.InvokeAndDisconnect : false; + bool invokeAndDisconnect = shell.Settings != null && shell.Settings.InvokeAndDisconnect; if (invokeAndDisconnect && !EndpointSupportsDisconnect) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.EndpointDoesNotSupportDisconnect); @@ -938,7 +938,7 @@ internal bool EndpointSupportsDisconnect get { WSManClientSessionTransportManager wsmanTransportManager = _transportManager as WSManClientSessionTransportManager; - return (wsmanTransportManager != null) ? wsmanTransportManager.SupportsDisconnect : false; + return wsmanTransportManager != null && wsmanTransportManager.SupportsDisconnect; } } diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index 8fb2fc014dc..dfd1cd3bf7f 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -93,7 +93,7 @@ private PSCommand ParsePsCommandUsingScriptBlock(string line, bool? useLocalScop // and if we are not in a loopback configuration mode, in which case we always force remote script commands // to be parsed and evaluated on the remote session (not in the current local session). RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; - bool isConfiguredLoopback = (remoteRunspace != null) ? remoteRunspace.IsConfiguredLoopBack : false; + bool isConfiguredLoopback = remoteRunspace != null && remoteRunspace.IsConfiguredLoopBack; bool isTrustedInput = !isConfiguredLoopback && (localRunspace.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage); // Create PowerShell from ScriptBlock. diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 9cbd8afbc3b..bbb2056189c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -3003,9 +3003,9 @@ private Dictionary GetMatchingRunspacesByVMNameContainerId(bool var matchingRunspaceInfos = remoteRunspaceInfos .Where(session => (supportWildChar ? inputNamePattern.IsMatch(session.VMName) : inputName.Equals(session.ContainerId)) && - ((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) && + (sessionNamePattern == null || sessionNamePattern.IsMatch(session.Name)) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == computerType)) .ToList(); @@ -3063,7 +3063,7 @@ private Dictionary GetMatchingRunspacesByVMNameContainerIdSessi : inputName.Equals(session.ContainerId)) && sessionInstanceId.Equals(session.InstanceId) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == computerType)) .ToList(); @@ -3106,9 +3106,9 @@ private Dictionary GetMatchingRunspacesByVMId(bool writeobject, var matchingRunspaceInfos = remoteRunspaceInfos .Where(session => vmId.Equals(session.VMId) && - ((sessionNamePattern == null) ? true : sessionNamePattern.IsMatch(session.Name)) && + (sessionNamePattern == null || sessionNamePattern.IsMatch(session.Name)) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == TargetMachineType.VirtualMachine)) .ToList(); @@ -3143,7 +3143,7 @@ private Dictionary GetMatchingRunspacesByVMIdSessionInstanceId( .Where(session => vmId.Equals(session.VMId) && sessionInstanceId.Equals(session.InstanceId) && QueryRunspaces.TestRunspaceState(session.Runspace, filterState) && - ((configurationNamePattern == null) ? true : configurationNamePattern.IsMatch(session.ConfigurationName)) && + (configurationNamePattern == null || configurationNamePattern.IsMatch(session.ConfigurationName)) && (session.ComputerType == TargetMachineType.VirtualMachine)) .ToList(); diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 9ce1cb4b08f..3122d7e1176 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -661,7 +661,7 @@ private List CreateRunspacesWhenRunspaceParameterSpecified() if (originalWSManConnectionInfo != null) { newWSManConnectionInfo = originalWSManConnectionInfo.Copy(); - newWSManConnectionInfo.EnableNetworkAccess = (newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess) ? true : false; + newWSManConnectionInfo.EnableNetworkAccess = newWSManConnectionInfo.EnableNetworkAccess || EnableNetworkAccess; newConnectionInfo = newWSManConnectionInfo; } else diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index abcb32966f3..4685af1e75d 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -105,7 +105,7 @@ internal FragmentedRemoteObject(byte[] blob, long objectId, long fragmentId, ObjectId = objectId; FragmentId = fragmentId; - IsStartFragment = (fragmentId == 0) ? true : false; + IsStartFragment = fragmentId == 0; IsEndFragment = isEndFragment; _blob = blob; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index e980de069d5..20db6a1dd1d 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -1925,7 +1925,7 @@ private static void OnCreateSessionCallback(IntPtr operationContext, } // check if the session supports disconnect - sessionTM.SupportsDisconnect = ((flags & (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT) != 0) ? true : false; + sessionTM.SupportsDisconnect = (flags & (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_SUPPORTS_DISCONNECT) != 0; // openContent is used by redirection ie., while redirecting to // a new machine.. this is not needed anymore as the connection diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 9ad9967bf03..ca7ff805c02 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -335,7 +335,7 @@ public override void PushRunspace(Runspace runspace) // PSEdit support. Existence of RemoteSessionOpenFileEvent event indicates host supports PSEdit _hostSupportsPSEdit = false; PSEventManager localEventManager = Runspace?.Events; - _hostSupportsPSEdit = (localEventManager != null) ? localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext() : false; + _hostSupportsPSEdit = localEventManager != null && localEventManager.GetEventSubscribers(HostUtilities.RemoteSessionOpenFileEvent).GetEnumerator().MoveNext(); if (_hostSupportsPSEdit) { AddPSEditForRunspace(remoteRunspace); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index b70f0cb4b4d..21cb200e561 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -1486,9 +1486,7 @@ private static PreProcessCommandResult PreProcessDebuggerCommand( Breakpoint breakpoint = serverRemoteDebugger.GetBreakpoint(breakpointId, runspaceId); preProcessOutput.Add( - breakpoint == null - ? false - : serverRemoteDebugger.RemoveBreakpoint(breakpoint, runspaceId)); + breakpoint != null && serverRemoteDebugger.RemoveBreakpoint(breakpoint, runspaceId)); result = PreProcessCommandResult.BreakpointManagement; } @@ -1628,7 +1626,7 @@ public bool IsAvailable pump = null; } - return (pump != null) ? !(pump.IsBusy) : false; + return (pump != null) && !(pump.IsBusy); } } diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 133dd10c38a..97625a9e46a 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -1004,7 +1004,7 @@ internal void InvokeWithPipeImpl( args = Array.Empty(); } - bool runOptimized = context._debuggingMode > 0 ? false : createLocalScope; + bool runOptimized = context._debuggingMode <= 0 && createLocalScope; var codeToInvoke = GetCodeToInvoke(ref runOptimized, clauseToInvoke); if (codeToInvoke == null) { @@ -2207,7 +2207,7 @@ public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScript _scriptBlock = scriptBlock; _useLocalScope = useNewScope; _fromScriptFile = fromScriptFile; - _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode > 0 ? false : useNewScope); + _runOptimized = _scriptBlock.Compile(optimized: context._debuggingMode <= 0 && useNewScope); _localsTuple = _scriptBlock.MakeLocalsTuple(_runOptimized); _localsTuple.SetAutomaticVariable(AutomaticVariable.PSCmdlet, this, context); _scriptBlock.SetPSScriptRootAndPSCommandPath(_localsTuple, context); diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 501a3aa5c25..4a8b846b08b 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -2019,7 +2019,7 @@ string ToModeString(FileSystemInfo fileSystemInfo) FileAttributes fileAttributes = fileSystemInfo.Attributes; bool isReparsePoint = InternalSymbolicLinkLinkCodeMethods.IsReparsePoint(fileSystemInfo); - bool isLink = isReparsePoint || (excludeHardLink ? false : InternalSymbolicLinkLinkCodeMethods.IsHardLink(fileSystemInfo)); + bool isLink = isReparsePoint || (!excludeHardLink && InternalSymbolicLinkLinkCodeMethods.IsHardLink(fileSystemInfo)); if (!isLink) { // special casing for the common cases - no allocations From e0cda04d86297df8a07cd85ca73387f7bf185ceb Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 2 Dec 2020 04:52:05 +0000 Subject: [PATCH 083/138] Fix IDE0090: Simplify new expression part 5 (#14301) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../DotNetCode/Eventing/EventProvider.cs | 2 +- .../Eventing/EventProviderTraceListener.cs | 10 +++++----- .../Eventing/Reader/NativeWrapper.cs | 18 +++++++++--------- .../DotNetCode/Eventing/UnsafeNativeMethods.cs | 2 +- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 5b8bd88d0fc..cd87c0898fd 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -779,7 +779,7 @@ public static void SetActivityId(ref Guid id) [System.Security.SecurityCritical] public static Guid CreateActivityId() { - Guid newId = new Guid(); + Guid newId = new(); UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newId); return newId; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 60ebad783c5..7264e485468 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -84,7 +84,7 @@ public EventProviderTraceListener(string providerId, string name, string delimit private void InitProvider(string providerId) { - Guid controlGuid = new Guid(providerId); + Guid controlGuid = new(providerId); // // Create The ETW TraceProvider // @@ -148,7 +148,7 @@ public sealed override void TraceData(TraceEventCache eventCache, string source, return; } - StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); + StringBuilder dataString = new(s_defaultPayloadSize); if (data != null) { @@ -177,7 +177,7 @@ public sealed override void TraceData(TraceEventCache eventCache, string source, } int index; - StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); + StringBuilder dataString = new(s_defaultPayloadSize); if ((data != null) && (data.Length > 0)) { @@ -242,7 +242,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source return; } - StringBuilder dataString = new StringBuilder(s_defaultPayloadSize); + StringBuilder dataString = new(s_defaultPayloadSize); dataString.Append(message); _provider.WriteMessageEvent(dataString.ToString(), @@ -278,7 +278,7 @@ public sealed override void TraceEvent(TraceEventCache eventCache, string source public override void Fail(string message, string detailMessage) { - StringBuilder failMessage = new StringBuilder(message); + StringBuilder failMessage = new(message); if (detailMessage != null) { failMessage.Append(' '); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index ee29eb8ab10..c9cd4d255eb 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -514,7 +514,7 @@ public static string EvtFormatMessage(EventLogHandle handle, uint msgId) { int bufferNeeded; - StringBuilder sb = new StringBuilder(null); + StringBuilder sb = new(null); bool status = UnsafeNativeMethods.EvtFormatMessage(handle, EventLogHandle.Zero, msgId, 0, null, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageId, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); @@ -672,9 +672,9 @@ public static object EvtGetChannelConfigProperty(EventLogHandle handle, UnsafeNa [System.Security.SecuritySafeCritical] public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNativeMethods.EvtChannelConfigPropertyId enumType, object val) { - UnsafeNativeMethods.EvtVariant varVal = new UnsafeNativeMethods.EvtVariant(); + UnsafeNativeMethods.EvtVariant varVal = new(); - CoTaskMemSafeHandle taskMem = new CoTaskMemSafeHandle(); + CoTaskMemSafeHandle taskMem = new(); using (taskMem) { @@ -762,7 +762,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati [System.Security.SecurityCritical] public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) { - StringBuilder sb = new StringBuilder(null); + StringBuilder sb = new(null); int channelNameNeeded; bool status = UnsafeNativeMethods.EvtNextChannelPath(handle, 0, sb, out channelNameNeeded); @@ -791,7 +791,7 @@ public static string EvtNextChannelPath(EventLogHandle handle, ref bool finish) [System.Security.SecurityCritical] public static string EvtNextPublisherId(EventLogHandle handle, ref bool finish) { - StringBuilder sb = new StringBuilder(null); + StringBuilder sb = new(null); int ProviderIdNeeded; bool status = UnsafeNativeMethods.EvtNextPublisherId(handle, 0, sb, out ProviderIdNeeded); @@ -976,7 +976,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl if (!status) ThrowEventLogException(win32Error); - List valuesList = new List(propCount); + List valuesList = new(propCount); if (propCount > 0) { pointer = buffer; @@ -1001,7 +1001,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl public static string EvtFormatMessageRenderName(EventLogHandle pmHandle, EventLogHandle eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags flag) { int bufferNeeded; - StringBuilder sb = new StringBuilder(null); + StringBuilder sb = new(null); bool status = UnsafeNativeMethods.EvtFormatMessage(pmHandle, eventHandle, 0, 0, null, flag, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); @@ -1059,7 +1059,7 @@ public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle try { - List keywordsList = new List(); + List keywordsList = new(); bool status = UnsafeNativeMethods.EvtFormatMessageBuffer(pmHandle, eventHandle, 0, 0, IntPtr.Zero, flag, 0, IntPtr.Zero, out bufferNeeded); int error = Marshal.GetLastWin32Error(); @@ -1164,7 +1164,7 @@ public static string EvtFormatMessageFormatDescription(EventLogHandle handle, Ev stringVariants[i].StringVal = values[i]; } - StringBuilder sb = new StringBuilder(null); + StringBuilder sb = new(null); bool status = UnsafeNativeMethods.EvtFormatMessage(handle, eventHandle, 0xffffffff, values.Length, stringVariants, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent, 0, sb, out bufferNeeded); int error = Marshal.GetLastWin32Error(); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 63d81615f48..5635aed2bd0 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -84,7 +84,7 @@ internal static extern int FormatMessage(int dwFlags, IntPtr lpSource, [SecurityCritical] internal static string GetMessage(int errorCode) { - StringBuilder sb = new StringBuilder(512); + StringBuilder sb = new(512); int result = UnsafeNativeMethods.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, UnsafeNativeMethods.s_NULL, errorCode, 0, sb, sb.Capacity, UnsafeNativeMethods.s_NULL); From 3b49c139e97d8f575367dc86cf38b142f35730f8 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2020 21:03:49 +0500 Subject: [PATCH 084/138] Bump Markdig.Signed from 0.22.0 to 0.22.1 (#14305) Bumps [Markdig.Signed](https://github.com/lunet-io/markdig) from 0.22.0 to 0.22.1. - [Release notes](https://github.com/lunet-io/markdig/releases) - [Changelog](https://github.com/lunet-io/markdig/blob/master/changelog.md) - [Commits](https://github.com/lunet-io/markdig/compare/0.22.0...0.22.1) Signed-off-by: dependabot-preview[bot] Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com> --- .../Microsoft.PowerShell.MarkdownRender.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj index cc89f95d6c6..9cab5ee5e08 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj +++ b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj @@ -9,7 +9,7 @@ - + From 548e93989472053d73bd41b666170d37bd23b44e Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 3 Dec 2020 02:35:29 +0500 Subject: [PATCH 085/138] Use `StringComparison.Ordinal` insted of `StringComparison.CurrentCulture` (#14298) --- src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 73707dd0efe..d12f4385eaa 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -116,7 +116,7 @@ internal static int Start(string bannerText, string helpText) { Environment.SetEnvironmentVariable("PATH", pshome); } - else if (!path.StartsWith(pshome)) + else if (!path.StartsWith(pshome, StringComparison.Ordinal)) { Environment.SetEnvironmentVariable("PATH", pshome + path); } From f91b620fdeacc2418c1d6012fe038a106a7599b6 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Thu, 3 Dec 2020 18:18:40 +0100 Subject: [PATCH 086/138] Enable nullable: System.Management.Automation.Provider.IPropertyCmdletProvider (#14176) --- .../namespaces/IPropertiesProvider.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs index 555037635ef..1f4a6c168fe 100644 --- a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs +++ b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs @@ -3,6 +3,7 @@ using System.Collections.ObjectModel; +#nullable enable namespace System.Management.Automation.Provider { #region IPropertyCmdletProvider @@ -58,7 +59,7 @@ public interface IPropertyCmdletProvider /// void GetProperty( string path, - Collection providerSpecificPickList); + Collection? providerSpecificPickList); /// /// Gives the provider an opportunity to attach additional parameters to the @@ -79,9 +80,9 @@ void GetProperty( /// /// The default implementation returns null. (no additional parameters) /// - object GetPropertyDynamicParameters( + object? GetPropertyDynamicParameters( string path, - Collection providerSpecificPickList); + Collection? providerSpecificPickList); /// /// Sets the specified properties of the item at the specified path. @@ -137,7 +138,7 @@ void SetProperty( /// /// The default implementation returns null. (no additional parameters) /// - object SetPropertyDynamicParameters( + object? SetPropertyDynamicParameters( string path, PSObject propertyValue); @@ -191,7 +192,7 @@ void ClearProperty( /// /// The default implementation returns null. (no additional parameters) /// - object ClearPropertyDynamicParameters( + object? ClearPropertyDynamicParameters( string path, Collection propertyToClear); } From 99e527bc0a36bfc8c4ee8b62cd6e0a7bf7572848 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Thu, 3 Dec 2020 18:19:24 +0100 Subject: [PATCH 087/138] Enable nullable: System.Management.Automation.Host.IHostSupportsInteractiveSession (#14170) --- src/System.Management.Automation/engine/hostifaces/MshHost.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 64d8f1170f2..7ee89d14b12 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -290,6 +290,7 @@ public virtual bool DebuggerEnabled /// This interface needs to be implemented by PSHost objects that want to support the PushRunspace /// and PopRunspace functionality. /// +#nullable enable public interface IHostSupportsInteractiveSession { /// @@ -317,6 +318,6 @@ public interface IHostSupportsInteractiveSession /// Returns the current runspace associated with this host. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] - Runspace Runspace { get; } + Runspace? Runspace { get; } } } From 280457684086ea382fbfcd82a6c1c93ed9b2900d Mon Sep 17 00:00:00 2001 From: Ilya Date: Fri, 4 Dec 2020 00:24:49 +0500 Subject: [PATCH 088/138] Avoid an exception if file system does not support reparse points (#13634) --- .../namespaces/FileSystemProvider.cs | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 4a8b846b08b..762f7461809 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -7837,8 +7837,6 @@ public static class InternalSymbolicLinkLinkCodeMethods // data is 16KB, plus there's a header. private const int MAX_REPARSE_SIZE = (16 * 1024) + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; - private const int ERROR_NOT_A_REPARSE_POINT = 4390; - private const int FSCTL_GET_REPARSE_POINT = 0x000900A8; private const int FSCTL_SET_REPARSE_POINT = 0x000900A4; @@ -8153,16 +8151,20 @@ private static string WinInternalGetLinkType(string filePath) // Get Buffer size IntPtr dangerousHandle = handle.DangerousGetHandle(); - bool result = DeviceIoControl(dangerousHandle, FSCTL_GET_REPARSE_POINT, - IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero); + bool result = DeviceIoControl( + dangerousHandle, + FSCTL_GET_REPARSE_POINT, + InBuffer: IntPtr.Zero, + nInBufferSize: 0, + outBuffer, + outBufferSize, + out bytesReturned, + lpOverlapped: IntPtr.Zero); if (!result) { - int lastError = Marshal.GetLastWin32Error(); - if (lastError == ERROR_NOT_A_REPARSE_POINT) - linkType = null; - else - throw new Win32Exception(lastError); + // It's not a reparse point or the file system doesn't support reparse points. + return IsHardLink(ref dangerousHandle) ? "HardLink" : null; } REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = Marshal.PtrToStructure(outBuffer); @@ -8182,7 +8184,7 @@ private static string WinInternalGetLinkType(string filePath) break; default: - linkType = IsHardLink(ref dangerousHandle) ? "HardLink" : null; + linkType = null; break; } @@ -8399,16 +8401,20 @@ private static string WinInternalGetTarget(SafeFileHandle handle) // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used. handle.DangerousAddRef(ref success); - bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT, - IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero); + bool result = DeviceIoControl( + handle.DangerousGetHandle(), + FSCTL_GET_REPARSE_POINT, + InBuffer: IntPtr.Zero, + nInBufferSize: 0, + outBuffer, + outBufferSize, + out bytesReturned, + lpOverlapped: IntPtr.Zero); if (!result) { - int lastError = Marshal.GetLastWin32Error(); - if (lastError == ERROR_NOT_A_REPARSE_POINT) - return null; - - throw new Win32Exception(lastError); + // It's not a reparse point or the file system doesn't support reparse points. + return null; } string targetDir = null; From 03f40a00782e4b4fbb8c723759b956cacdc2e168 Mon Sep 17 00:00:00 2001 From: Ilya Date: Fri, 4 Dec 2020 03:34:00 +0500 Subject: [PATCH 089/138] Use `OrdinalIgnoreCase` in `CommandLineParser` (#14303) --- .../host/msh/CommandLineParameterParser.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 7b75123c2a6..ad809b70982 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -602,7 +602,7 @@ internal static string GetConfigurationNameFromGroupPolicy() /// private (string switchKey, bool shouldBreak) GetSwitchKey(string[] args, ref int argIndex, ref bool noexitSeen) { - string switchKey = args[argIndex].Trim().ToLowerInvariant(); + string switchKey = args[argIndex].Trim(); if (string.IsNullOrEmpty(switchKey)) { return (switchKey: string.Empty, shouldBreak: false); @@ -648,7 +648,7 @@ private static bool MatchSwitch(string switchKey, string match, string smallestU Dbg.Assert(match.Contains(smallestUnambiguousMatch), "sUM should be a substring of match"); return (switchKey.Length >= smallestUnambiguousMatch.Length - && match.IndexOf(switchKey, StringComparison.Ordinal) == 0); + && match.StartsWith(switchKey, StringComparison.OrdinalIgnoreCase)); } #endregion @@ -1131,11 +1131,11 @@ static object ConvertToBoolIfPossible(string arg) { if (args[i].StartsWith('-') && args[i].Length > 1) { - string param = args[i].Substring(1, args[i].Length - 1).ToLower(); + string param = args[i].Substring(1, args[i].Length - 1); StringBuilder possibleParameters = new StringBuilder(); foreach (string validParameter in s_validParameters) { - if (validParameter.Contains(param)) + if (validParameter.Contains(param, StringComparison.OrdinalIgnoreCase)) { possibleParameters.Append("\n -"); possibleParameters.Append(validParameter); From d47864d4de5af28e071fc01fa6188f63c1199dde Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 3 Dec 2020 22:35:25 +0000 Subject: [PATCH 090/138] Avoid unnecessary array allocations when searching in GAC (#14291) --- .../CoreCLR/CorePsAssemblyLoadContext.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index adc57710620..7799ec35cbb 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -404,12 +404,12 @@ private static bool FindInGac(string gacRoot, AssemblyName assemblyName, out str if (Directory.Exists(tempAssemblyDirPath)) { // Enumerate all directories, sort by name and select the last. This selects the latest version. - var chosenVersionDirectory = Directory.GetDirectories(tempAssemblyDirPath).OrderBy(d => d).LastOrDefault(); + var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).OrderBy(d => d).LastOrDefault(); if (!string.IsNullOrEmpty(chosenVersionDirectory)) { // Select first or default as the directory will contain only one assembly. If nothing then default is null; - var foundAssemblyPath = Directory.GetFiles(chosenVersionDirectory, $"{assemblyName.Name}*").FirstOrDefault(); + var foundAssemblyPath = Directory.EnumerateFiles(chosenVersionDirectory, $"{assemblyName.Name}*").FirstOrDefault(); if (!string.IsNullOrEmpty(foundAssemblyPath)) { From 927d20aec222769fb41ecfa94b7fff0a08ad5e62 Mon Sep 17 00:00:00 2001 From: Ilya Date: Fri, 4 Dec 2020 11:42:35 +0500 Subject: [PATCH 091/138] Fix a broken link in Code Guidelines doc (#14314) --- docs/dev-process/coding-guidelines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev-process/coding-guidelines.md b/docs/dev-process/coding-guidelines.md index dab26aa5bf7..389981c3f7b 100644 --- a/docs/dev-process/coding-guidelines.md +++ b/docs/dev-process/coding-guidelines.md @@ -86,7 +86,7 @@ We also run the [.NET code formatter tool](https://github.com/dotnet/codeformatt * Make sure the added/updated comments are meaningful, accurate and easy to understand. -* Public members must use [doc comments](https://docs.microsoft.com/dotnet/csharp/programming-guide/xmldoc/xml-documentation-comments). +* Public members must use [doc comments](https://docs.microsoft.com/dotnet/csharp/programming-guide/xmldoc/). Internal and private members may use doc comments but it is not required. ## Performance Considerations From 75b5813f8472b931a0ebcadbf5fec69e1adb3b8f Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Fri, 4 Dec 2020 11:31:57 +0000 Subject: [PATCH 092/138] Fix RCS1188: Remove redundant auto-property initialization part 2 (#14262) https://github.com/JosefPihrt/Roslynator/blob/master/docs/analyzers/RCS1188.md --- .../commands/utility/Measure-Object.cs | 4 ++-- .../commands/utility/New-Object.cs | 6 +++--- .../commands/utility/NewTimeSpanCommand.cs | 8 ++++---- .../commands/utility/OrderObjectBase.cs | 4 ++-- .../commands/utility/Select-Object.cs | 8 ++++---- .../commands/utility/Sort-Object.cs | 4 ++-- .../WebCmdlet/Common/WebRequestPSCmdlet.Common.cs | 2 +- .../commands/utility/Write.cs | 14 +++++++------- .../commands/utility/WriteConsoleCmdlet.cs | 2 +- .../commands/utility/WriteProgressCmdlet.cs | 2 +- .../commands/utility/XmlCommands.cs | 4 ++-- 11 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 1947793b05b..e1a2bda8126 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -18,7 +18,7 @@ public abstract class MeasureInfo /// /// Property name. /// - public string Property { get; set; } = null; + public string Property { get; set; } } /// @@ -244,7 +244,7 @@ public MeasureObjectCommand() /// [ValidateNotNullOrEmpty] [Parameter(Position = 0)] - public PSPropertyExpression[] Property { get; set; } = null; + public PSPropertyExpression[] Property { get; set; } #endregion Common parameters in both sets diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index 0b52a68499d..3f02ffcfbda 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -34,7 +34,7 @@ public sealed class NewObjectCommand : PSCmdlet /// the number [Parameter(ParameterSetName = netSetName, Mandatory = true, Position = 0)] [ValidateTrustedData] - public string TypeName { get; set; } = null; + public string TypeName { get; set; } #if !UNIX private Guid _comObjectClsId = Guid.Empty; @@ -43,7 +43,7 @@ public sealed class NewObjectCommand : PSCmdlet /// [Parameter(ParameterSetName = "Com", Mandatory = true, Position = 0)] [ValidateTrustedData] - public string ComObject { get; set; } = null; + public string ComObject { get; set; } #endif /// @@ -53,7 +53,7 @@ public sealed class NewObjectCommand : PSCmdlet [Parameter(ParameterSetName = netSetName, Mandatory = false, Position = 1)] [ValidateTrustedData] [Alias("Args")] - public object[] ArgumentList { get; set; } = null; + public object[] ArgumentList { get; set; } /// /// True if we should have an error when Com objects will use an interop assembly. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs index 0e633ca5b2e..53c39250763 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs @@ -68,25 +68,25 @@ public DateTime End /// Allows the user to override the day. /// [Parameter(ParameterSetName = "Time")] - public int Days { get; set; } = 0; + public int Days { get; set; } /// /// Allows the user to override the hour. /// [Parameter(ParameterSetName = "Time")] - public int Hours { get; set; } = 0; + public int Hours { get; set; } /// /// Allows the user to override the minute. /// [Parameter(ParameterSetName = "Time")] - public int Minutes { get; set; } = 0; + public int Minutes { get; set; } /// /// Allows the user to override the second. /// [Parameter(ParameterSetName = "Time")] - public int Seconds { get; set; } = 0; + public int Seconds { get; set; } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index 172c9c98ab5..7a6bcc6bc1b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -182,9 +182,9 @@ internal sealed class OrderByProperty /// /// A logical matrix where each row is an input object and its property values specified by Properties. /// - internal List OrderMatrix { get; } = null; + internal List OrderMatrix { get; } - internal OrderByPropertyComparer Comparer { get; } = null; + internal OrderByPropertyComparer Comparer { get; } internal List MshParameterList { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index ddd527380f1..efdd82d79de 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -91,14 +91,14 @@ public sealed class SelectObjectCommand : PSCmdlet /// [Parameter(ParameterSetName = "DefaultParameter")] [Parameter(ParameterSetName = "SkipLastParameter")] - public string[] ExcludeProperty { get; set; } = null; + public string[] ExcludeProperty { get; set; } /// /// /// [Parameter(ParameterSetName = "DefaultParameter")] [Parameter(ParameterSetName = "SkipLastParameter")] - public string ExpandProperty { get; set; } = null; + public string ExpandProperty { get; set; } /// /// @@ -152,14 +152,14 @@ public int First /// [Parameter(ParameterSetName = "DefaultParameter")] [ValidateRange(0, int.MaxValue)] - public int Skip { get; set; } = 0; + public int Skip { get; set; } /// /// Skip the specified number of items from end. /// [Parameter(ParameterSetName = "SkipLastParameter")] [ValidateRange(0, int.MaxValue)] - public int SkipLast { get; set; } = 0; + public int SkipLast { get; set; } /// /// With this switch present, the cmdlet won't "short-circuit" diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs index 60b656d890c..06f5ebfffad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs @@ -53,14 +53,14 @@ public SwitchParameter Descending /// [Parameter(ParameterSetName = "Top", Mandatory = true)] [ValidateRange(1, int.MaxValue)] - public int Top { get; set; } = 0; + public int Top { get; set; } /// /// Gets or sets the number of items to return in a Bottom N sort. /// [Parameter(ParameterSetName = "Bottom", Mandatory = true)] [ValidateRange(1, int.MaxValue)] - public int Bottom { get; set; } = 0; + public int Bottom { get; set; } /// /// Moves unique entries to the front of the list. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index a5edb07190e..13f7ea6f999 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -239,7 +239,7 @@ public virtual int MaximumRedirection /// [Parameter] [ValidateRange(0, Int32.MaxValue)] - public virtual int MaximumRetryCount { get; set; } = 0; + public virtual int MaximumRetryCount { get; set; } /// /// Gets or sets the RetryIntervalSec property, which determines the number seconds between retries. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 2d1b26391a7..bf907203544 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -21,7 +21,7 @@ public sealed class WriteDebugCommand : PSCmdlet [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowEmptyString] [Alias("Msg")] - public string Message { get; set; } = null; + public string Message { get; set; } /// /// This method implements the ProcessRecord method for Write-Debug command. @@ -69,7 +69,7 @@ public sealed class WriteVerboseCommand : PSCmdlet [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowEmptyString] [Alias("Msg")] - public string Message { get; set; } = null; + public string Message { get; set; } /// /// This method implements the ProcessRecord method for Write-verbose command. @@ -117,7 +117,7 @@ public sealed class WriteWarningCommand : PSCmdlet [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowEmptyString] [Alias("Msg")] - public string Message { get; set; } = null; + public string Message { get; set; } /// /// This method implements the ProcessRecord method for Write-Warning command. @@ -215,7 +215,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// ErrorRecord.Exception -- if not specified, ErrorRecord.Exception is System.Exception. /// [Parameter(ParameterSetName = "WithException", Mandatory = true)] - public Exception Exception { get; set; } = null; + public Exception Exception { get; set; } /// /// If Exception is specified, this is ErrorRecord.ErrorDetails.Message; @@ -226,14 +226,14 @@ public class WriteOrThrowErrorCommand : PSCmdlet [AllowNull] [AllowEmptyString] [Alias("Msg")] - public string Message { get; set; } = null; + public string Message { get; set; } /// /// If Exception is specified, this is ErrorRecord.ErrorDetails.Message; /// otherwise, the Exception is System.Exception, and this is Exception.Message. /// [Parameter(ParameterSetName = "ErrorRecord", Mandatory = true)] - public ErrorRecord ErrorRecord { get; set; } = null; + public ErrorRecord ErrorRecord { get; set; } /// /// ErrorRecord.CategoryInfo.Category. @@ -254,7 +254,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// [Parameter(ParameterSetName = "NoException")] [Parameter(ParameterSetName = "WithException")] - public object TargetObject { get; set; } = null; + public object TargetObject { get; set; } /// /// ErrorRecord.ErrorDetails.RecommendedAction. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index aabd3637ec5..2d2009e56bc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -18,7 +18,7 @@ public sealed class WriteHostCommand : ConsoleColorCmdlet /// [Parameter(Position = 0, ValueFromRemainingArguments = true, ValueFromPipeline = true)] [Alias("Msg", "Message")] - public object Object { get; set; } = null; + public object Object { get; set; } /// /// False to add a newline to the end of the output string, true if not. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index ac4e1e33aff..fe8fccb6e1a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -37,7 +37,7 @@ public sealed class WriteProgressCommand : PSCmdlet /// [Parameter(Position = 2)] [ValidateRange(0, Int32.MaxValue)] - public int Id { get; set; } = 0; + public int Id { get; set; } /// /// Percentage completion of the activity, or -1 if n/a. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 1a091008f95..cfd216edc41 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -32,7 +32,7 @@ public sealed class ExportClixmlCommand : PSCmdlet, IDisposable /// [Parameter] [ValidateRange(1, int.MaxValue)] - public int Depth { get; set; } = 0; + public int Depth { get; set; } /// /// Mandatory file name to write to. @@ -388,7 +388,7 @@ public sealed class ConvertToXmlCommand : PSCmdlet, IDisposable /// [Parameter(HelpMessage = "Specifies how many levels of contained objects should be included in the XML representation")] [ValidateRange(1, int.MaxValue)] - public int Depth { get; set; } = 0; + public int Depth { get; set; } /// /// Input Object which is written to XML format. From 18b50e80eff813ad37c5de28a35cd4cd03827374 Mon Sep 17 00:00:00 2001 From: "dependabot-preview[bot]" <27856297+dependabot-preview[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2020 16:42:27 +0500 Subject: [PATCH 093/138] Bump Microsoft.NET.Test.Sdk from 16.8.0 to 16.8.3 (#14310) Bumps [Microsoft.NET.Test.Sdk](https://github.com/microsoft/vstest) from 16.8.0 to 16.8.3. - [Release notes](https://github.com/microsoft/vstest/releases) - [Commits](https://github.com/microsoft/vstest/compare/v16.8.0...v16.8.3) Signed-off-by: dependabot-preview[bot] Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com> --- test/xUnit/xUnit.tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/xUnit/xUnit.tests.csproj b/test/xUnit/xUnit.tests.csproj index 6ecf0f798aa..352da3d353d 100644 --- a/test/xUnit/xUnit.tests.csproj +++ b/test/xUnit/xUnit.tests.csproj @@ -27,7 +27,7 @@ - + From ea3036dc6d5bcbd58ee2b3b1960a3647467d0801 Mon Sep 17 00:00:00 2001 From: Ilya Date: Fri, 4 Dec 2020 22:24:42 +0500 Subject: [PATCH 094/138] Use `Environment.TickCount64` instead of `Datetime.Now` as the random seed for AppLocker test file content (#14283) --- src/System.Management.Automation/security/wldpNativeMethods.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 5d4b49270c3..61023787457 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -230,7 +230,7 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle // AppLocker fails when you try to check a policy on a file // with no content. So create a scratch file and test on that. - string dtAppLockerTestFileContents = AppLockerTestFileContents + DateTime.Now; + string dtAppLockerTestFileContents = AppLockerTestFileContents + Environment.TickCount64; IO.File.WriteAllText(testPathScript, dtAppLockerTestFileContents); IO.File.WriteAllText(testPathModule, dtAppLockerTestFileContents); } From e35668ca0a4b354a41f316c9e8f8632f15e9b3ac Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 7 Dec 2020 11:11:03 +0000 Subject: [PATCH 095/138] Avoid array allocations from GetDirectories/GetFiles. (#14330) --- .../help/UpdatableHelpCommandBase.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index d9453b58c2e..6bd8b6e84b4 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -784,7 +784,7 @@ private IEnumerable RecursiveResolvePathHelper(string path) { yield return path; - foreach (string subDirectory in Directory.GetDirectories(path)) + foreach (string subDirectory in Directory.EnumerateDirectories(path)) { foreach (string subDirectory2 in RecursiveResolvePathHelper(subDirectory)) { From 1b7aa0a5d598dfba625cd1e28285aa11261bf7b1 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Mon, 7 Dec 2020 11:24:12 -0800 Subject: [PATCH 096/138] Fix nuget packaging to scrub `NullableAttribute` (#14344) --- tools/packaging/packaging.psm1 | 1 - 1 file changed, 1 deletion(-) diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index 4a1ecd52854..ec9c24e20c1 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -2401,7 +2401,6 @@ function CleanupGeneratedSourceCode if ($assemblyName -in $patternToReplace.ApplyTo -and $line.Contains($patternToReplace.Pattern)) { $line = $line.Replace($patternToReplace.Pattern, $patternToReplace.Replacement) $lineWasProcessed = $true - break } } From 09cc338789fce0ffb5bea2c30985ee5242d42a1a Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 7 Dec 2020 12:11:54 -0800 Subject: [PATCH 097/138] Move macOS and nuget to esrp signing (#14324) --- .../azureDevOps/templates/linux.yml | 21 +++--- .../templates/mac-file-signing.yml | 42 +++++------ .../templates/mac-package-signing.yml | 38 ++++------ .../azureDevOps/templates/nuget.yml | 70 ++++++++++--------- .../templates/windows-package-signing.yml | 18 ++--- 5 files changed, 82 insertions(+), 107 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index 5263217404e..53e9b4f1924 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -21,6 +21,9 @@ jobs: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: SetVersionVariables.yml parameters: ReleaseTagVar: $(ReleaseTagVar) @@ -100,17 +103,13 @@ jobs: downloadPath: '$(System.ArtifactsDirectory)\rpm' condition: and(eq(variables['buildName'], 'RPM'),succeeded()) - - task: SFP.build-tasks.custom-build-task-2.EsrpMalwareScanning@1 - displayName: 'Malware Scanning' - inputs: - ConnectedServiceName: pwshEsrpScanning - FolderPath: $(System.ArtifactsDirectory) - Pattern: | - **\*.rpm - **\*.deb - **\*.tar.gz - UseMinimatch: true - SessionTimeout: 30 + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(System.ArtifactsDirectory) + pattern: | + **\*.rpm + **\*.deb + **\*.tar.gz - ${{ if eq(variables['buildName'], 'RPM') }}: - template: EsrpSign.yml@ComplianceRepo diff --git a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml index fddbe5f131d..46178671496 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml @@ -9,13 +9,15 @@ jobs: pool: name: Package ES Standard Build variables: - BuildConfiguration: release - BuildPlatform: any cpu + - group: ESRP steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: shouldSign.yml - template: SetVersionVariables.yml @@ -63,27 +65,14 @@ jobs: Write-Host $zipFile displayName: 'Compress macOS binary files' - - pwsh: | - $pkgFiles = "$(Build.StagingDirectory)\macos\powershell-files-$(Version)-osx-x64.zip", "$(Build.StagingDirectory)\macos\powershell-lts-$(Version)-osx-x64.zip" - tools/releaseBuild/generatePackgeSigning.ps1 -MacDeveloperFiles $pkgFiles -path "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Generate macOS binary Signing Xml' - - - pwsh: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture macOS signing xml' - # Diagnostics is not critical it passes every time it runs - continueOnError: true - - - task: PkgESCodeSign@10 - displayName: 'CodeSign $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedMacOSPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(Build.StagingDirectory)\macos + signOutputPath: $(Build.StagingDirectory)\signedMacOSPackages + certificateId: "CP-401337-Apple" + pattern: | + **\*.zip + useMinimatch: true - pwsh: | $destination = "$(System.ArtifactsDirectory)\azureMacOs" @@ -100,8 +89,11 @@ jobs: artifactName: signedMacOsBins condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(System.ArtifactsDirectory)\azureMacOs + pattern: | + **\* - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml index 05fe9114892..3e3d69dcbe5 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml @@ -9,13 +9,15 @@ jobs: pool: name: Package ES Standard Build variables: - BuildConfiguration: release - BuildPlatform: any cpu + - group: ESRP steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + - template: shouldSign.yml - template: SetVersionVariables.yml @@ -50,27 +52,14 @@ jobs: } displayName: 'Compress macOS Package' - - pwsh: | - $pkgFiles = "$(Build.StagingDirectory)\macos\powershell-$(Version)-osx-x64.zip", "$(Build.StagingDirectory)\macos\powershell-lts-$(Version)-osx-x64.zip" - tools/releaseBuild/generatePackgeSigning.ps1 -MacDeveloperFiles $pkgFiles -path "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Generate macOS Package Signing Xml' - - - pwsh: | - Get-Content "$(System.ArtifactsDirectory)\package.xml" - displayName: 'Capture macOS signing xml' - # Diagnostics is not critical it passes every time it runs - continueOnError: true - - - task: PkgESCodeSign@10 - displayName: 'CodeSign $(System.ArtifactsDirectory)\package.xml' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(System.ArtifactsDirectory)\package.xml' - outPathRoot: '$(Build.StagingDirectory)\signedMacOSPackages' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(Build.StagingDirectory)\macos + signOutputPath: $(Build.StagingDirectory)\signedMacOSPackages + certificateId: "CP-401337-Apple" + pattern: | + **\*.zip + useMinimatch: true - template: upload-final-results.yml parameters: @@ -120,9 +109,6 @@ jobs: ContainerName: '$(AzureVersion)' condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - - task: securedevelopmentteam.vss-secure-development-tools.build-task-antimalware.AntiMalware@3 - displayName: 'Run Defender Scan' - - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' inputs: diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index 0e81e337aed..a23b9c1ad67 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -12,19 +12,35 @@ jobs: timeoutInMinutes: 90 variables: - runCodesignValidationInjection: false - GenAPIToolPath: '$(System.ArtifactsDirectory)/GenAPI' - PackagePath: '$(System.ArtifactsDirectory)/UnifiedPackagePath' - winFxdPath: '$(System.ArtifactsDirectory)/winFxd' - winFxdWinDesktopPath: '$(System.ArtifactsDirectory)/winFxdWinDesktop' - linuxFxdPath: '$(System.ArtifactsDirectory)/linuxFxd' + - name: runCodesignValidationInjection + value: false + - name: build + value: ${{ parameters.buildName }} + - group: ESRP + - name: GenAPIToolPath + value: '$(System.ArtifactsDirectory)/GenAPI' + - name: PackagePath + value: '$(System.ArtifactsDirectory)/UnifiedPackagePath' + - name: winFxdPath + value: '$(System.ArtifactsDirectory)/winFxd' + - name: winFxdWinDesktopPath + value: '$(System.ArtifactsDirectory)/winFxdWinDesktop' + - name: linuxFxdPath + value: '$(System.ArtifactsDirectory)/linuxFxd' steps: - checkout: self clean: true + - checkout: ComplianceRepo + clean: true + + - template: SetVersionVariables.yml + parameters: + ReleaseTagVar: $(ReleaseTagVar) + - powershell: | - $content = Get-Content "$(Build.SourcesDirectory)/global.json" -Raw | ConvertFrom-Json + $content = Get-Content "$env:REPOROOT/global.json" -Raw | ConvertFrom-Json $vstsCommandString = "vso[task.setvariable variable=SDKVersion]$($content.sdk.version)" Write-Host "sending " + $vstsCommandString Write-Host "##$vstsCommandString" @@ -90,8 +106,8 @@ jobs: displayName: 'Install NuGet.exe' - powershell: | - Import-Module $env:BUILD_SOURCESDIRECTORY\build.psm1 - Import-Module $env:BUILD_SOURCESDIRECTORY\tools\packaging + Import-Module $env:REPOROOT\build.psm1 + Import-Module $env:REPOROOT\tools\packaging Find-Dotnet New-ILNugetPackage -PackagePath "$(PackagePath)" -PackageVersion "$(Version)" -WinFxdBinPath '$(winFxdPath)' -LinuxFxdBinPath '$(linuxFxdPath)' -GenAPIToolPath "$(GenAPIToolPath)" displayName: 'Create Nuget Package Folders' @@ -103,8 +119,8 @@ jobs: displayName: Capture fxd folders - powershell: | - Import-Module $env:BUILD_SOURCESDIRECTORY\build.psm1 - Import-Module $env:BUILD_SOURCESDIRECTORY\tools\packaging + Import-Module $env:REPOROOT\build.psm1 + Import-Module $env:REPOROOT\tools\packaging Find-Dotnet # Create unified package first New-GlobalToolNupkg -UnifiedPackage -LinuxBinPath "$(linuxFxdPath)" -WindowsBinPath "$(winFxdPath)" -WindowsDesktopBinPath "$(winFxdWinDesktopPath)" -PackageVersion "$(Version)" -DestinationPath "$(PackagePath)\globaltool" @@ -117,28 +133,14 @@ jobs: Get-ChildItem "$(PackagePath)" -Recurse displayName: Capture generated packages - - powershell: | - $packages = Get-ChildItem "$(PackagePath)\*.nupkg", "$(PackagePath)\globaltool\*.nupkg" | Select-Object -ExpandProperty FullName - - if($packages.Count -lt 1) - { - throw "No packages created" - } - - $(Build.SourcesDirectory)\tools\releaseBuild\generatePackgeSigning.ps1 -Path $(PackagePath)\NugetSigning.xml -NuPkgFiles $packages - displayName: Create signing file - - - task: PkgESCodeSign@10 - displayName: 'CodeSign Nuget Packages' - env: - SYSTEM_ACCESSTOKEN: $(System.AccessToken) - inputs: - signConfigXml: '$(PackagePath)\NugetSigning.xml' - inPathRoot: '$(PackagePath)' - outPathRoot: '$(System.ArtifactsDirectory)\signed' - binVersion: $(SigingVersion) - binVersionOverride: $(SigningVersionOverride) - condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) + - template: EsrpSign.yml@ComplianceRepo + parameters: + buildOutputPath: $(PackagePath) + signOutputPath: $(System.ArtifactsDirectory)\signed + certificateId: "CP-401405" + pattern: | + **\*.nupkg + useMinimatch: true - pwsh: | if (-not (Test-Path '$(System.ArtifactsDirectory)\signed\')) { $null = New-Item -ItemType Directory -Path '$(System.ArtifactsDirectory)\signed\' } @@ -148,7 +150,7 @@ jobs: condition: eq(variables['SHOULD_SIGN'], 'false') - powershell: | - Import-Module $(Build.SourcesDirectory)\build.psm1 -Force + Import-Module "${env:REPOROOT}\build.psm1" -Force Get-ChildItem -Recurse "$(System.ArtifactsDirectory)\signed\*.nupkg" -Verbose | ForEach-Object { Start-NativeExecution -sb { nuget.exe verify -All $_.FullName } } displayName: Verify all packages are signed condition: eq(variables['SHOULD_SIGN'], 'true') diff --git a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml index 3803226958a..81c1a2228d9 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml @@ -93,17 +93,13 @@ jobs: msi: no msix: no - - task: SFP.build-tasks.custom-build-task-2.EsrpMalwareScanning@1 - displayName: 'Malware Scanning' - inputs: - ConnectedServiceName: pwshEsrpScanning - FolderPath: '$(Build.StagingDirectory)' - Pattern: | - **\*.msix - **\*.msi - **\*.zip - UseMinimatch: true - SessionTimeout: 30 + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(Build.StagingDirectory) + pattern: | + **\*.msix + **\*.msi + **\*.zip - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' From 86ca45681dbfd3feadb9e5a6eb782e35b87b5993 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Mon, 7 Dec 2020 23:20:58 +0000 Subject: [PATCH 098/138] Avoid array allocations from GetDirectories/GetFiles. (#14328) --- .../engine/CommandCompletion/CompletionCompleters.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index f5c276466be..853b79e7843 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -6096,7 +6096,7 @@ internal static List CompleteHelpTopics(CompletionContext cont foreach (var dir in searchPaths) { - foreach (var file in Directory.GetFiles(dir)) + foreach (var file in Directory.EnumerateFiles(dir)) { if (wildcardPattern.IsMatch(Path.GetFileName(file))) { From 909ca89be9a84bcdd365b9526f6e474d00134186 Mon Sep 17 00:00:00 2001 From: Kyle H Date: Mon, 7 Dec 2020 19:31:55 -0600 Subject: [PATCH 099/138] The -Stream parameter now works with directories (#13941) --- .../namespaces/FileSystemProvider.cs | 112 ++++++++++++------ .../Add-Content.Tests.ps1 | 24 ++++ .../Clear-Content.Tests.ps1 | 64 ++++++---- .../Get-Content.Tests.ps1 | 38 +++--- .../Get-Item.Tests.ps1 | 26 +++- .../Remove-Item.Tests.ps1 | 33 +++++- .../Set-Content.Tests.ps1 | 33 ++++++ 7 files changed, 252 insertions(+), 78 deletions(-) diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 762f7461809..db619e3d15e 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -1311,35 +1311,36 @@ protected override void GetItem(string path) // If we want to retrieve the file streams, retrieve them. if (retrieveStreams) { - if (!isContainer) + foreach (string desiredStream in dynamicParameters.Stream) { - foreach (string desiredStream in dynamicParameters.Stream) - { - // See that it matches the name specified - WildcardPattern p = WildcardPattern.Get(desiredStream, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - bool foundStream = false; + // See that it matches the name specified + WildcardPattern p = WildcardPattern.Get(desiredStream, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); + bool foundStream = false; - foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(result.FullName)) + foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(result.FullName)) + { + if (!p.IsMatch(stream.Stream)) { - if (!p.IsMatch(stream.Stream)) { continue; } - - string outputPath = result.FullName + ":" + stream.Stream; - WriteItemObject(stream, outputPath, isContainer); - foundStream = true; + continue; } - if ((!WildcardPattern.ContainsWildcardCharacters(desiredStream)) && (!foundStream)) - { - string errorMessage = StringUtil.Format( - FileSystemProviderStrings.AlternateDataStreamNotFound, desiredStream, result.FullName); - Exception e = new FileNotFoundException(errorMessage, result.FullName); - - WriteError(new ErrorRecord( - e, - "AlternateDataStreamNotFound", - ErrorCategory.ObjectNotFound, - path)); - } + string outputPath = result.FullName + ":" + stream.Stream; + // Alternate data streams can never be containers. + WriteItemObject(stream, outputPath, isContainer: false); + foundStream = true; + } + + if ((!WildcardPattern.ContainsWildcardCharacters(desiredStream)) && (!foundStream)) + { + string errorMessage = StringUtil.Format( + FileSystemProviderStrings.AlternateDataStreamNotFound, desiredStream, result.FullName); + Exception e = new FileNotFoundException(errorMessage, result.FullName); + + WriteError(new ErrorRecord( + e, + "AlternateDataStreamNotFound", + ErrorCategory.ObjectNotFound, + path)); } } } @@ -6663,7 +6664,14 @@ public IContentReader GetContentReader(string path) try { - if (Directory.Exists(path)) + // Get-Content will write a non-terminating error if the target is a directory. + // On Windows, the streamName must be null or empty for it to write the error. Otherwise, the + // alternate data stream is not a directory, even if it's set on a directory. + if (Directory.Exists(path) +#if !UNIX + && string.IsNullOrEmpty(streamName) +#endif + ) { string errMsg = StringUtil.Format(SessionStateStrings.GetContainerContentException, path); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "GetContainerContentException", ErrorCategory.InvalidOperation, null); @@ -6818,7 +6826,14 @@ public IContentWriter GetContentWriter(string path) try { - if (Directory.Exists(path)) + // Add-Content and Set-Content will write a non-terminating error if the target is a directory. + // On Windows, the streamName must be null or empty for it to write the error. Otherwise, the + // alternate data stream is not a directory, even if it's set on a directory. + if (Directory.Exists(path) +#if !UNIX + && string.IsNullOrEmpty(streamName) +#endif + ) { string errMsg = StringUtil.Format(SessionStateStrings.WriteContainerContentException, path); ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "WriteContainerContentException", ErrorCategory.InvalidOperation, null); @@ -6896,13 +6911,6 @@ public void ClearContent(string path) path = NormalizePath(path); - if (Directory.Exists(path)) - { - string errorMsg = StringUtil.Format(SessionStateStrings.ClearDirectoryContent, path); - WriteError(new ErrorRecord(new NotSupportedException(errorMsg), "ClearDirectoryContent", ErrorCategory.InvalidOperation, path)); - return; - } - try { #if !UNIX @@ -6954,6 +6962,26 @@ public void ClearContent(string path) clearStream = false; } +#endif + // On Windows, determine if our argument is a directory only after we determine if + // we're being asked to work with an alternate data stream, because directories can have + // alternate data streams on them that are not child items. These alternate data streams + // must be treated as data streams, even if they're attached to directories. However, + // if asked to work with a directory without a data stream specified, write a non-terminating + // error instead of clearing all child items of the directory. (On non-Windows, alternate + // data streams don't exist, so in that environment always write the error when addressing + // a directory.) + if (Directory.Exists(path) +#if !UNIX + && !clearStream +#endif + ) + { + string errorMsg = StringUtil.Format(SessionStateStrings.ClearDirectoryContent, path); + WriteError(new ErrorRecord(new NotSupportedException(errorMsg), "ClearDirectoryContent", ErrorCategory.InvalidOperation, path)); + return; + } +#if !UNIX if (clearStream) { FileStream fileStream = null; @@ -8625,7 +8653,22 @@ internal static List GetStreams(string path) SafeFindHandle handle = NativeMethods.FindFirstStreamW( path, NativeMethods.StreamInfoLevels.FindStreamInfoStandard, findStreamData, 0); - if (handle.IsInvalid) throw new Win32Exception(); + + if (handle.IsInvalid) + { + int error = Marshal.GetLastWin32Error(); + + // Directories don't normally have alternate streams, so this is not an exceptional state. + // If a directory has no alternate data streams, FindFirstStreamW returns ERROR_HANDLE_EOF. + if (error == NativeMethods.ERROR_HANDLE_EOF) + { + return alternateStreams; + } + + // An unexpected error was returned, that we don't know how to interpret. The most helpful + // thing we can do at this point is simply throw the raw Win32 exception. + throw new Win32Exception(error); + } try { @@ -8760,6 +8803,7 @@ internal static void SetZoneOfOrigin(string path, SecurityZone securityZone) internal static class NativeMethods { internal const int ERROR_HANDLE_EOF = 38; + internal const int ERROR_INVALID_PARAMETER = 87; internal enum StreamInfoLevels { FindStreamInfoStandard = 0 } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 index d4bd23a6fee..6d63206b709 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Add-Content.Tests.ps1 @@ -5,6 +5,7 @@ Describe "Add-Content cmdlet tests" -Tags "CI" { BeforeAll { $file1 = "file1.txt" Setup -File "$file1" + $streamContent = "ShouldWork" } Context "Add-Content should actually add content" { @@ -47,6 +48,29 @@ Describe "Add-Content cmdlet tests" -Tags "CI" { { Add-Content -Path . -Value "WriteContainerContentException" -ErrorAction Stop } | Should -Throw -ErrorId "WriteContainerContentException,Microsoft.PowerShell.Commands.AddContentCommand" } + Context "Add-Content should work with alternate data streams on Windows" { + BeforeAll { + if (!$isWindows) { + return + } + $ADSTestDir = "addcontentadstest" + $ADSTestFile = "addcontentads.txt" + $streamContent = "This is a test stream." + Setup -Directory "$ADSTestDir" + Setup -File "$ADSTestFile" + } + + It "Should add an alternate data stream on a directory" -Skip:(!$IsWindows) { + Add-Content -Path TestDrive:\$ADSTestDir -Stream Add-Content-Test-Stream -Value $streamContent -ErrorAction Stop + Get-Content -Path TestDrive:\$ADSTestDir -Stream Add-Content-Test-Stream | Should -BeExactly $streamContent + } + + It "Should add an alternate data stream on a file" -Skip:(!$IsWindows) { + Add-Content -Path TestDrive:\$ADSTestFile -Stream Add-Content-Test-Stream -Value $streamContent -ErrorAction Stop + Get-Content -Path TestDrive:\$ADSTestFile -Stream Add-Content-Test-Stream | Should -BeExactly $streamContent + } + } + #[BugId(BugDatabase.WindowsOutOfBandReleases, 906022)] It "should throw 'NotSupportedException' when you add-content to an unsupported provider" -Skip:($IsLinux -Or $IsMacOS) { { Add-Content -Path HKLM:\\software\\microsoft -Value "ShouldNotWorkBecausePathIsUnsupported" -ErrorAction Stop } | Should -Throw -ErrorId "NotSupported,Microsoft.PowerShell.Commands.AddContentCommand" diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 index e2ab56fc809..ff9d0c8f39c 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Clear-Content.Tests.ps1 @@ -51,6 +51,8 @@ Describe "Clear-Content cmdlet tests" -Tags "CI" { Setup -File "$file3" -Content $content2 $streamContent = "content for alternate stream" $streamName = "altStream1" + $dirName = "clearcontent" + Setup -Directory "$dirName" } Context "Clear-Content should actually clear content" { @@ -75,32 +77,50 @@ Describe "Clear-Content cmdlet tests" -Tags "CI" { $cci.SupportsShouldProcess | Should -BeTrue } - It "Alternate streams should be cleared with clear-content" -Skip:(!$IsWindows) { - # make sure that the content is correct - # this is here rather than BeforeAll because only windows can write to an alternate stream - Set-Content -Path "TestDrive:/$file3" -Stream $streamName -Value $streamContent - Get-Content -Path "TestDrive:/$file3" | Should -BeExactly $content2 - Get-Content -Path "TestDrive:/$file3" -Stream $streamName | Should -BeExactly $streamContent - Clear-Content -Path "TestDrive:/$file3" -Stream $streamName - Get-Content -Path "TestDrive:/$file3" | Should -BeExactly $content2 - Get-Content -Path "TestDrive:/$file3" -Stream $streamName | Should -BeNullOrEmpty - } + Context "Clear-Content should work with alternate data streams on Windows" { + It "Alternate streams should be cleared with Clear-Content on a file" -Skip:(!$IsWindows) { + + Set-Content -Path "TestDrive:/$file3" -Stream $streamName -Value $streamContent + Get-Content -Path "TestDrive:/$file3" -Stream $streamName | Should -BeExactly $streamContent + + Clear-Content -Path "TestDrive:/$file3" -Stream $streamName -ErrorAction Stop + + $result = Get-Item -Path "TestDrive:/$file3" -Stream $streamName + $result | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData + $result.length | Should -Be 0 + } - It "the '-Stream' dynamic parameter is visible to get-command in the filesystem" -Skip:(!$IsWindows) { - try { - Push-Location -Path TestDrive: - (Get-Command Clear-Content -Stream foo).parameters.keys -eq "stream" | Should -Be "stream" + It "Alternate streams should be cleared with Clear-Content on a directory" -Skip:(!$IsWindows) { + Set-Content -Path "TestDrive:/$dirName" -Stream $streamName -Value $streamContent + + Get-Content -Path "TestDrive:/$dirName" -Stream $streamName | Should -BeExactly $streamContent + Clear-Content -Path "TestDrive:/$dirName" -Stream $streamName -ErrorAction Stop + + $result = Get-Item -Path "TestDrive:/$dirName" -Stream $streamName + $result | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData + $result.length | Should -Be 0 } - finally { - Pop-Location + + It "the '-Stream' dynamic parameter is visible to get-command in the filesystem" -Skip:(!$IsWindows) { + try { + Push-Location -Path TestDrive: + (Get-Command Clear-Content -Stream foo).parameters.keys -eq "Stream" | Should -BeExactly "Stream" + } + finally { + Pop-Location + } } - } - It "the '-Stream' dynamic parameter should not be visible to get-command in the function provider" { - Push-Location -Path function: - { Get-Command Clear-Content -Stream $streamName } | - Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" - Pop-Location + It "the '-Stream' dynamic parameter should not be visible to get-command in the function provider" -Skip:(!$IsWindows) { + try { + Push-Location -Path function: + { Get-Command Clear-Content -Stream $streamName } | + Should -Throw -ErrorId "NamedParameterNotFound,Microsoft.PowerShell.Commands.GetCommandCommand" + } + finally { + Pop-Location + } + } } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 index 6c50cee5aa8..5fdc904580d 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Content.Tests.ps1 @@ -221,25 +221,27 @@ Describe "Get-Content" -Tags "CI" { $expected = 'He', 'o,', '', 'Wor', "d${nl}He", 'o2,', '', 'Wor', "d2${nl}" for ($i = 0; $i -lt $result.Length ; $i++) { $result[$i] | Should -BeExactly $expected[$i]} } + + Context "Alternate Data Stream support on Windows" { + It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { + Set-Content "${testPath}:Stream" -Value "Foo" + { Test-Path "${testPath}:Stream" | Should -Throw -ErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } + Get-Content "${testPath}:Stream" | Should -BeExactly "Foo" + Get-Content $testPath | Should -BeExactly $testString + } - It "Should support NTFS streams using colon syntax" -Skip:(!$IsWindows) { - Set-Content "${testPath}:Stream" -Value "Foo" - { Test-Path "${testPath}:Stream" | Should -Throw -ErrorId "ItemExistsNotSupportedError,Microsoft.PowerShell.Commands,TestPathCommand" } - Get-Content "${testPath}:Stream" | Should -BeExactly "Foo" - Get-Content $testPath | Should -BeExactly $testString - } - - It "Should support NTFS streams using -Stream" -Skip:(!$IsWindows) { - Set-Content -Path $testPath -Stream hello -Value World - Get-Content -Path $testPath | Should -BeExactly $testString - Get-Content -Path $testPath -Stream hello | Should -BeExactly "World" - $item = Get-Item -Path $testPath -Stream hello - $item | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData - $item.Stream | Should -BeExactly "hello" - Clear-Content -Path $testPath -Stream hello - Get-Content -Path $testPath -Stream hello | Should -BeNullOrEmpty - Remove-Item -Path $testPath -Stream hello - { Get-Content -Path $testPath -Stream hello | Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" } + It "Should support NTFS streams using -Stream" -Skip:(!$IsWindows) { + Set-Content -Path $testPath -Stream hello -Value World + Get-Content -Path $testPath | Should -BeExactly $testString + Get-Content -Path $testPath -Stream hello | Should -BeExactly "World" + $item = Get-Item -Path $testPath -Stream hello + $item | Should -BeOfType System.Management.Automation.Internal.AlternateStreamData + $item.Stream | Should -BeExactly "hello" + Clear-Content -Path $testPath -Stream hello + Get-Content -Path $testPath -Stream hello | Should -BeNullOrEmpty + Remove-Item -Path $testPath -Stream hello + { Get-Content -Path $testPath -Stream hello -ErrorAction stop} | Should -Throw -ErrorId "GetContentReaderFileNotFoundError,Microsoft.PowerShell.Commands.GetContentCommand" + } } It "Should support colons in filename on Linux/Mac" -Skip:($IsWindows) { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 index 86b831ba8d0..c04412e91b4 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Get-Item.Tests.ps1 @@ -112,16 +112,38 @@ Describe "Get-Item" -Tags "CI" { return } $altStreamPath = "$TESTDRIVE/altStream.txt" + $altStreamDirectory = "$TESTDRIVE/altstreamdir" + $noAltStreamDirectory = "$TESTDRIVE/noaltstreamdir" $stringData = "test data" $streamName = "test" - $item = New-Item -type file $altStreamPath + $absentStreamName = "noExist" + $null = New-Item -type file $altStreamPath Set-Content -Path $altStreamPath -Stream $streamName -Value $stringData + $null = New-Item -type directory $altStreamDirectory + Set-Content -Path $altStreamDirectory -Stream $streamName -Value $stringData + $null = New-Item -type directory $noAltStreamDirectory } - It "Should find an alternate stream if present" -Skip:$skipNotWindows { + It "Should find an alternate stream on a file if present" -Skip:$skipNotWindows { $result = Get-Item $altStreamPath -Stream $streamName $result.Length | Should -Be ($stringData.Length + [Environment]::NewLine.Length) $result.Stream | Should -Be $streamName } + It "Should error if it cannot find alternate stream on an existing file" -Skip:$skipNotWindows { + { Get-Item $altStreamPath -Stream $absentStreamName -ErrorAction Stop } | Should -Throw -ErrorId "AlternateDataStreamNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + } + It "Should find an alternate stream on a directory if present, and it should not be a container" -Skip:$skipNotWindows { + $result = Get-Item $altStreamDirectory -Stream $streamName + $result.Length | Should -Be ($stringData.Length + [Environment]::NewLine.Length ) + $result.Stream | Should -Be $streamName + $result.PSIsContainer | Should -BeExactly $false + } + It "Should not find an alternate stream on a directory if not present" -Skip:$skipNotWindows { + { Get-Item $noAltStreamDirectory -Stream $absentStreamName -ErrorAction Stop } | Should -Throw -ErrorId "AlternateDataStreamNotFound,Microsoft.PowerShell.Commands.GetItemCommand" + } + It "Should find zero alt streams and not fail on a directory with a wildcard stream name if no alt streams are present" -Skip:$skipNotWindows { + $result = Get-Item $noAltStreamDirectory -Stream * -ErrorAction Stop + $result | Should -BeExactly $null + } } Context "Registry Provider" { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 index 769a8a34003..3e8ccb8fa91 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Remove-Item.Tests.ps1 @@ -7,9 +7,7 @@ Describe "Remove-Item" -Tags "CI" { Context "File removal Tests" { BeforeEach { New-Item -Name $testfile -Path $testpath -ItemType "file" -Value "lorem ipsum" -Force - Test-Path $testfilepath | Should -BeTrue - } It "Should be able to be called on a regular file without error using the Path parameter" { @@ -138,4 +136,35 @@ Describe "Remove-Item" -Tags "CI" { Test-Path $testdirectory | Should -BeFalse } } + + Context "Alternate Data Streams should be supported on Windows" { + BeforeAll { + if (!$IsWindows) { + return + } + $fileName = "ADStest.txt" + $streamName = "teststream" + $dirName = "ADStestdir" + $fileContent =" This is file content." + $streamContent = "datastream content here" + $streamfile = Join-Path -Path $testpath -ChildPath $fileName + $streamdir = Join-Path -Path $testpath -ChildPath $dirName + + $null = New-Item -Path $streamfile -ItemType "File" -force + Add-Content -Path $streamfile -Value $fileContent + Add-Content -Path $streamfile -Stream $streamName -Value $streamContent + $null = New-Item -Path $streamdir -ItemType "Directory" -Force + Add-Content -Path $streamdir -Stream $streamName -Value $streamContent + } + It "Should completely remove a datastream from a file" -Skip:(!$IsWindows) { + Get-Item -Path $streamfile -Stream $streamName | Should -Not -BeNullOrEmpty + Remove-Item -Path $streamfile -Stream $streamName + Get-Item -Path $streamfile -Stream $streamName -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + It "Should completely remove a datastream from a directory" -Skip:(!$IsWindows) { + Get-Item -Path $streamdir -Stream $streamName | Should -Not -BeNullOrEmpty + Remove-Item -Path $streamdir -Stream $streamName + Get-Item -Path $streamdir -Stream $streamname -ErrorAction SilentlyContinue | Should -BeNullOrEmpty + } + } } diff --git a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 index 6e8f8bde083..fefd73412df 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Management/Set-Content.Tests.ps1 @@ -72,6 +72,39 @@ Describe "Set-Content cmdlet tests" -Tags "CI" { $result[1] | Should -BeExactly "world" } } + Context "Set-Content should work with alternate data streams on Windows" { + BeforeAll { + if ( -Not $IsWindows ) + { + return + } + $altStreamPath = "$TESTDRIVE/altStream.txt" + $altStreamPath2 = "$TESTDRIVE/altStream2.txt" + $altStreamDirectory = "$TESTDRIVE/altstreamdir" + $altStreamDirectory2 = "$TESTDRIVE/altstream2dir" + $stringData = "test data" + $streamName = "test" + $absentStreamName = "noExist" + $item = New-Item -type file $altStreamPath + $altstreamdiritem = New-Item -type directory $altStreamDirectory + } + It "Should create a new data stream on a file" -Skip:(-Not $IsWindows) { + Set-Content -Path $altStreamPath -Stream $streamName -Value $stringData + Get-Content -Path $altStreamPath -Stream $streamName | Should -BeExactly $stringData + } + It "Should create a new data stream on a file using colon syntax" -Skip:(-Not $IsWindows) { + Set-Content -Path ${altStreamPath2}:${streamName} -Value $stringData + Get-Content -Path ${altStreamPath2} -Stream $streamName | Should -BeExactly $stringData + } + It "Should create a new data stream on a directory" -Skip:(-Not $IsWindows) { + Set-Content -Path $altStreamDirectory -Stream $streamName -Value $stringData + Get-Content -Path $altStreamDirectory -Stream $streamName | Should -BeExactly $stringData + } + It "Should create a new data stream on a directory using colon syntax" -Skip:(-Not $IsWindows) { + Set-Content -Path ${altStreamDirectory2}:${streamName} -Value $stringData + Get-Content -Path ${altStreamDirectory2} -Stream ${streamName} | Should -BeExactly $stringData + } + } } Describe "Set-Content should work for PSDrive with UNC path as root" -Tags @('CI', 'RequireAdminOnWindows') { From 7b59040ffb7a32e8c39b12022fe956bed1e6b081 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Tue, 8 Dec 2020 12:42:20 -0800 Subject: [PATCH 100/138] Fix example nuget.config (#14349) --- docs/host-powershell/sample/NuGet.config | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/host-powershell/sample/NuGet.config b/docs/host-powershell/sample/NuGet.config index 58f8d2c9b6d..b3ce3cb82a5 100644 --- a/docs/host-powershell/sample/NuGet.config +++ b/docs/host-powershell/sample/NuGet.config @@ -1,8 +1,10 @@ + - - + + + From dd4e5c7ba818427169640a28ebf352589a325964 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Tue, 8 Dec 2020 21:59:10 +0000 Subject: [PATCH 101/138] Refactor multiply operation for better performance in 2 Commands.Utility functions (#14148) --- .../commands/utility/Measure-Object.cs | 9 +++++---- .../commands/utility/ObjectCommandComparer.cs | 18 +++++++++--------- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index e1a2bda8126..4bc6a3b42e0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -623,7 +623,6 @@ private static object Compare(object objValue, object statMinOrMaxValue, bool is { object currentValue = objValue; object statValue = statMinOrMaxValue; - int factor = isMin ? 1 : -1; double temp; currentValue = ((objValue != null) && LanguagePrimitives.TryConvertTo(objValue, out temp)) ? temp : currentValue; @@ -635,13 +634,15 @@ private static object Compare(object objValue, object statMinOrMaxValue, bool is statValue = PSObject.AsPSObject(statValue).ToString(); } - if ((statValue == null) || - ((LanguagePrimitives.Compare(statValue, currentValue, false, CultureInfo.CurrentCulture) * factor) > 0)) + if (statValue == null) { return objValue; } - return statMinOrMaxValue; + int comparisonResult = LanguagePrimitives.Compare(statValue, currentValue, ignoreCase: false, CultureInfo.CurrentCulture); + return (isMin ? comparisonResult : -comparisonResult) > 0 + ? objValue + : statMinOrMaxValue; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index 6bf54039260..39986943c99 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -210,19 +210,19 @@ public int Compare(object first, object second) second = secondMsh.BaseObject; } - if (LanguagePrimitives.TryCompare(first, second, !_caseSensitive, _cultureInfo, out int result)) + if (!LanguagePrimitives.TryCompare(first, second, !_caseSensitive, _cultureInfo, out int result)) { - return result * (_ascendingOrder ? 1 : -1); - } + // Note that this will occur if the objects do not support + // IComparable. We fall back to comparing as strings. - // Note that this will occur if the objects do not support - // IComparable. We fall back to comparing as strings. + // being here means the first object doesn't support ICompare + string firstString = PSObject.AsPSObject(first).ToString(); + string secondString = PSObject.AsPSObject(second).ToString(); - // being here means the first object doesn't support ICompare - string firstString = PSObject.AsPSObject(first).ToString(); - string secondString = PSObject.AsPSObject(second).ToString(); + result = _cultureInfo.CompareInfo.Compare(firstString, secondString, _caseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase); + } - return _cultureInfo.CompareInfo.Compare(firstString, secondString, _caseSensitive ? CompareOptions.None : CompareOptions.IgnoreCase) * (_ascendingOrder ? 1 : -1); + return _ascendingOrder ? result : -result; } private readonly CultureInfo _cultureInfo = null; From b007952f74b05370496c6e6cdf46af2df92220e7 Mon Sep 17 00:00:00 2001 From: krishnayalavarthi Date: Tue, 8 Dec 2020 14:45:38 -0800 Subject: [PATCH 102/138] Restrict New-Object in NoLanguage mode under lock down #14139 (#14140) --- .../commands/utility/New-Object.cs | 21 +++++++++++++++++-- .../resources/NewObjectStrings.resx | 3 +++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index 3f02ffcfbda..54e323dfac8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -10,9 +10,7 @@ using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Language; -#if !UNIX using System.Management.Automation.Security; -#endif using System.Reflection; using System.Runtime.InteropServices; #if !UNIX @@ -199,6 +197,25 @@ protected override void BeginProcessing() } } + switch (Context.LanguageMode) + { + case PSLanguageMode.NoLanguage: + case PSLanguageMode.RestrictedLanguage: + if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce + && !CoreTypes.Contains(type)) + { + ThrowTerminatingError( + new ErrorRecord( + new PSNotSupportedException( + string.Format(NewObjectStrings.CannotCreateTypeLanguageMode, Context.LanguageMode.ToString())), + nameof(NewObjectStrings.CannotCreateTypeLanguageMode), + ErrorCategory.PermissionDenied, + targetObject: null)); + } + + break; + } + // WinRT does not support creating instances of attribute & delegate WinRT types. if (WinRTHelper.IsWinRTType(type) && ((typeof(System.Attribute)).IsAssignableFrom(type) || (typeof(System.Delegate)).IsAssignableFrom(type))) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx index 63b4271c382..07c2a6d8c9e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx @@ -144,6 +144,9 @@ Cannot create type. Only core types are supported in this language mode. + + Cannot create type. Only core types are supported in {0} language mode on a policy locked down machine. + {0} Please note that Single-Threaded Apartment is not supported in PowerShell. From bb78d4b5c0aa9237df47c512d4059248078f5bbd Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 9 Dec 2020 03:52:00 +0000 Subject: [PATCH 103/138] Fix IDE0090: Simplify new expression part 6 (#14338) https://docs.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0090 --- .../CoreCLR/CorePsAssemblyLoadContext.cs | 11 ++- .../CoreCLR/CorePsPlatform.cs | 38 ++++----- .../DscSupport/CimDSCParser.cs | 46 ++++++----- .../cimSupport/cmdletization/EnumWriter.cs | 6 +- .../cmdletization/MethodInvocationInfo.cs | 2 +- .../cimSupport/cmdletization/ScriptWriter.cs | 80 +++++++++---------- .../cim/WildcardPatternToCimQueryParser.cs | 2 +- .../other/ciminstancetypeadapter.cs | 8 +- 8 files changed, 97 insertions(+), 96 deletions(-) diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 7799ec35cbb..5bd9be5c62b 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -105,7 +105,7 @@ private PowerShellAssemblyLoadContext(string basePaths) #region Fields - private static readonly object s_syncObj = new object(); + private static readonly object s_syncObj = new(); private readonly string[] _probingPaths; private readonly string[] _extensions = new string[] { ".ni.dll", ".dll" }; // CoreCLR type catalog dictionary @@ -114,9 +114,8 @@ private PowerShellAssemblyLoadContext(string basePaths) private readonly Dictionary _coreClrTypeCatalog; private readonly Lazy> _availableDotNetAssemblyNames; - private readonly HashSet _denyListedAssemblies = new HashSet(StringComparer.OrdinalIgnoreCase){ - "System.Windows.Forms" - }; + private readonly HashSet _denyListedAssemblies = + new(StringComparer.OrdinalIgnoreCase) { "System.Windows.Forms" }; #if !UNIX private string _winDir; @@ -140,7 +139,7 @@ private PowerShellAssemblyLoadContext(string basePaths) /// Therefore, there is no need to use the full assembly name as the key. Short assembly name is sufficient. /// private static readonly ConcurrentDictionary s_assemblyCache = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + new(StringComparer.OrdinalIgnoreCase); #endregion Fields @@ -509,7 +508,7 @@ private static Assembly GetTrustedPlatformAssembly(string tpaStrongName) // it back from the cache of default context. // - If the requested TPA is not loaded yet, then 'Assembly.Load' will make the // default context to load it - AssemblyName assemblyName = new AssemblyName(tpaStrongName); + AssemblyName assemblyName = new(tpaStrongName); Assembly asmLoaded = Assembly.Load(assemblyName); return asmLoaded; } diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 981d6bfb088..b5e657d497f 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -155,20 +155,20 @@ public static bool IsWindowsDesktop #endif // format files - internal static readonly List FormatFileNames = new List - { - "Certificate.format.ps1xml", - "Diagnostics.format.ps1xml", - "DotNetTypes.format.ps1xml", - "Event.format.ps1xml", - "FileSystem.format.ps1xml", - "Help.format.ps1xml", - "HelpV3.format.ps1xml", - "PowerShellCore.format.ps1xml", - "PowerShellTrace.format.ps1xml", - "Registry.format.ps1xml", - "WSMan.format.ps1xml" - }; + internal static readonly List FormatFileNames = new() + { + "Certificate.format.ps1xml", + "Diagnostics.format.ps1xml", + "DotNetTypes.format.ps1xml", + "Event.format.ps1xml", + "FileSystem.format.ps1xml", + "Help.format.ps1xml", + "HelpV3.format.ps1xml", + "PowerShellCore.format.ps1xml", + "PowerShellTrace.format.ps1xml", + "Registry.format.ps1xml", + "WSMan.format.ps1xml" + }; /// /// Some common environment variables used in PS have different @@ -566,8 +566,8 @@ internal static int NonWindowsGetProcessParentPid(int pid) /// Unix specific implementations of required functionality. internal static class Unix { - private static Dictionary usernameCache = new Dictionary(); - private static Dictionary groupnameCache = new Dictionary(); + private static Dictionary usernameCache = new(); + private static Dictionary groupnameCache = new(); /// The type of a Unix file system item. public enum ItemType @@ -699,7 +699,7 @@ public class CommonStat private const char CanExecute = 'x'; // helper for getting unix mode - private Dictionary modeMap = new Dictionary() + private Dictionary modeMap = new() { { StatMask.OwnerRead, CanRead }, { StatMask.OwnerWrite, CanWrite }, @@ -726,7 +726,7 @@ public class CommonStat }; // The item type and the character representation for the first element in the stat string - private Dictionary itemTypeTable = new Dictionary() + private Dictionary itemTypeTable = new() { { ItemType.BlockDevice, 'b' }, { ItemType.CharacterDevice, 'c' }, @@ -860,7 +860,7 @@ public static bool IsHardLink(FileSystemInfo fs) /// A managed common stat class instance. private static CommonStat CopyStatStruct(NativeMethods.CommonStatStruct css) { - CommonStat cs = new CommonStat(); + CommonStat cs = new(); cs.Inode = css.Inode; cs.Mode = css.Mode; cs.UserId = css.UserId; diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index b3f91da547f..78f778b944b 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -544,19 +544,19 @@ public static class DscClassCache // Create a list of classes which are not actual DSC resources similar to what we do inside PSDesiredStateConfiguration.psm1 private static readonly string[] s_hiddenResourceList = - { - "MSFT_BaseConfigurationProviderRegistration", - "MSFT_CimConfigurationProviderRegistration", - "MSFT_PSConfigurationProviderRegistration", - }; + { + "MSFT_BaseConfigurationProviderRegistration", + "MSFT_CimConfigurationProviderRegistration", + "MSFT_PSConfigurationProviderRegistration", + }; // Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1) - private static readonly HashSet s_hiddenResourceCache = new HashSet(s_hiddenResourceList, - StringComparer.OrdinalIgnoreCase); + private static readonly HashSet s_hiddenResourceCache = + new(s_hiddenResourceList, StringComparer.OrdinalIgnoreCase); // a collection to hold current importing script based resource file // this prevent circular importing case when the script resource existing in the same module with resources it import-dscresource - private static readonly HashSet s_currentImportingScriptFiles = new HashSet(StringComparer.OrdinalIgnoreCase); + private static readonly HashSet s_currentImportingScriptFiles = new(StringComparer.OrdinalIgnoreCase); /// /// DSC class cache for this runspace. @@ -638,18 +638,20 @@ private static HashSet ScriptKeywordFileCache /// /// Default ModuleName and ModuleVersion to use. /// - private static readonly Tuple s_defaultModuleInfoForResource = new Tuple("PSDesiredStateConfiguration", new Version("1.1")); + private static readonly Tuple s_defaultModuleInfoForResource = + new("PSDesiredStateConfiguration", new Version("1.1")); /// /// Default ModuleName and ModuleVersion to use for meta configuration resources. /// - internal static readonly Tuple DefaultModuleInfoForMetaConfigResource = new Tuple("PSDesiredStateConfigurationEngine", new Version("2.0")); + internal static readonly Tuple DefaultModuleInfoForMetaConfigResource = + new("PSDesiredStateConfigurationEngine", new Version("2.0")); /// /// A set of dynamic keywords that can be used in both configuration and meta configuration. /// internal static readonly HashSet SystemResourceNames = - new HashSet(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" }; + new(StringComparer.OrdinalIgnoreCase) { "Node", "OMI_ConfigurationDocument" }; /// /// When this property is set to true, DSC Cache will cache multiple versions of a resource. @@ -784,7 +786,7 @@ public static void Initialize(Collection errors, List moduleP // Load Regular and DSC PS modules bool importInBoxResourcesImplicitly = false; - List modulePaths = new List(); + List modulePaths = new(); if (modulePathList == null || modulePathList.Count == 0) { modulePaths.Add(Path.Combine(configSystemPath, inboxModulePath)); @@ -1131,7 +1133,7 @@ private static List GetCachedClasses() /// List of cached cim classes. public static List GetCachedClassesForModule(PSModuleInfo module) { - List cachedClasses = new List(); + List cachedClasses = new(); var moduleQualifiedName = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", module.Name, module.Version.ToString()); foreach (var dscClassCacheEntry in ClassCache) { @@ -1151,7 +1153,7 @@ private static List GetCachedClasses() /// public static List GetFileDefiningClass(string className) { - List files = new List(); + List files = new(); foreach (var pair in ByFileClassCache) { var file = pair.Key; @@ -1298,7 +1300,7 @@ private static string GetFriendlyName(CimClass cimClass) /// public static Collection GetCachedKeywords() { - Collection keywords = new Collection(); + Collection keywords = new(); foreach (KeyValuePair cachedClass in ClassCache) { @@ -1909,7 +1911,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement // This function performs semantic checks for all DSC Resources keywords. private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatementAst kwAst) { - HashSet mandatoryPropertiesNames = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet mandatoryPropertiesNames = new(StringComparer.OrdinalIgnoreCase); foreach (var pair in kwAst.Keyword.Properties) { if (pair.Value.Mandatory) @@ -2361,7 +2363,7 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s ProcessMembers(sb, embeddedInstanceTypes, typeAst, className); - Queue bases = new Queue(); + Queue bases = new(); foreach (var b in typeAst.BaseTypes) { bases.Enqueue(b); @@ -2459,7 +2461,7 @@ public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, strin } IEnumerable resourceDefinitions; - List moduleFiles = new List(); + List moduleFiles = new(); if (moduleInfo.RootModule != null) { moduleFiles.Add(moduleInfo.Path); @@ -2593,7 +2595,7 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume { if (errorList != null && extent != null) { - List errorMessages = new List(); + List errorMessages = new(); foreach (var error in errors) { errorMessages.Add(error.ToString()); @@ -2698,7 +2700,7 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m return result; } - private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new Dictionary() + private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new() { { typeof(sbyte), "sint8" }, { typeof(byte) , "uint8"}, @@ -2946,7 +2948,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable if (validateSet != null) { bool valueMapComma = false; - StringBuilder sbValues = new StringBuilder(", Values{"); + StringBuilder sbValues = new(", Values{"); sb.AppendFormat(CultureInfo.InvariantCulture, "{0}ValueMap{{", needComma ? ", " : string.Empty); needComma = true; @@ -3662,7 +3664,7 @@ public static string GetDSCResourceUsageString(DynamicKeyword keyword) private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, bool isOptionalProperty) { string cimTypeName = prop.TypeConstraint; - StringBuilder formattedTypeString = new StringBuilder(); + StringBuilder formattedTypeString = new(); if (string.Equals(cimTypeName, "MSFT_Credential", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index 23c7a09c4f2..66649420101 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -17,14 +17,14 @@ internal static class EnumWriter private static ModuleBuilder CreateModuleBuilder() { - AssemblyName aName = new AssemblyName(namespacePrefix); + AssemblyName aName = new(namespacePrefix); AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); return mb; } - private static Lazy s_moduleBuilder = new Lazy(CreateModuleBuilder, isThreadSafe: true); - private static object s_moduleBuilderUsageLock = new object(); + private static Lazy s_moduleBuilder = new(CreateModuleBuilder, isThreadSafe: true); + private static object s_moduleBuilderUsageLock = new(); internal static string GetEnumFullName(EnumMetadataEnum enumMetadata) { diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index da44abe1fae..1640dec33b9 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -54,7 +54,7 @@ public MethodInvocationInfo(string name, IEnumerable parameters internal IEnumerable GetArgumentsOfType() where T : class { - List result = new List(); + List result = new(); foreach (var methodParameter in this.Parameters) { if ((methodParameter.Bindings & MethodParameterBindings.In) != MethodParameterBindings.In) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index e72f9606e12..3197361faea 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -237,7 +237,7 @@ private string GetCmdletName(CommonCmdletMetadata cmdletMetadata) private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) { // Generate the script for the Alias and Obsolete Attribute if any is declared in CDXML - StringBuilder attributes = new StringBuilder(150); + StringBuilder attributes = new(150); if (cmdletMetadata.Aliases != null) { attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); @@ -257,12 +257,12 @@ private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) private Dictionary GetCommonParameters() { - Dictionary commonParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary commonParameters = new(StringComparer.OrdinalIgnoreCase); - InternalParameterMetadata internalParameterMetadata = new InternalParameterMetadata(_objectModelWrapper, false); + InternalParameterMetadata internalParameterMetadata = new(_objectModelWrapper, false); foreach (CompiledCommandParameter compiledCommandParameter in internalParameterMetadata.BindableParameters.Values) { - ParameterMetadata parameterMetadata = new ParameterMetadata(compiledCommandParameter); + ParameterMetadata parameterMetadata = new(compiledCommandParameter); foreach (ParameterSetMetadata psetMetadata in parameterMetadata.ParameterSets.Values) { if (psetMetadata.ValueFromPipeline) @@ -335,7 +335,7 @@ private Dictionary GetCommonParameters() private static List GetCommonParameterSets(Dictionary commonParameters) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); foreach (ParameterMetadata parameter in commonParameters.Values) { foreach (string parameterSetName in parameter.ParameterSets.Keys) @@ -352,7 +352,7 @@ private static List GetCommonParameterSets(Dictionary result = new List(parameterSetNames.Keys); + List result = new(parameterSetNames.Keys); result.Sort(StringComparer.Ordinal); // to have a deterministic order of parameter sets (also means that Ordinal instead of OrdinalIgnoreCase is ok) return result; } @@ -365,7 +365,7 @@ private string GetMethodParameterSet(StaticMethodMetadata staticMethod) private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); foreach (StaticMethodMetadata method in staticCmdlet.Method) { @@ -386,7 +386,7 @@ private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) return new List(parameterSetNames.Keys); } - private Dictionary _staticMethodMetadataToUniqueId = new Dictionary(); + private Dictionary _staticMethodMetadataToUniqueId = new(); private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) { @@ -404,7 +404,7 @@ private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) private List GetMethodParameterSets(InstanceCmdletMetadata instanceCmdlet) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); InstanceMethodMetadata method = instanceCmdlet.Method; string parameterSetName = GetMethodParameterSet(method); @@ -436,7 +436,7 @@ private GetCmdletParameters GetGetCmdletParameters(InstanceCmdletMetadata instan private List GetQueryParameterSets(InstanceCmdletMetadata instanceCmdlet) { - Dictionary parameterSetNames = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameterSetNames = new(StringComparer.OrdinalIgnoreCase); var parameters = new List(); bool anyQueryParameters = false; @@ -555,7 +555,7 @@ private ParameterMetadata GetParameter( parameterName = objectModelParameterName; } - ParameterMetadata parameterMetadata = new ParameterMetadata(parameterName); + ParameterMetadata parameterMetadata = new(parameterName); parameterMetadata.ParameterType = GetDotNetType(parameterTypeMetadata); if (typeof(PSCredential).Equals(parameterMetadata.ParameterType)) { @@ -645,7 +645,7 @@ private ParameterMetadata GetParameter( if (parameterCmdletization.ValidateSet != null) { - List allowedValues = new List(); + List allowedValues = new(); foreach (string allowedValue in parameterCmdletization.ValidateSet) { allowedValues.Add(allowedValue); @@ -803,9 +803,9 @@ private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata) confirmImpact = (System.Management.Automation.ConfirmImpact)(int)cmdletMetadata.ConfirmImpact; } - Dictionary parameters = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary parameters = new(StringComparer.OrdinalIgnoreCase); - CommandMetadata commandMetadata = new CommandMetadata( + CommandMetadata commandMetadata = new( name: this.GetCmdletName(cmdletMetadata), commandType: CommandTypes.Cmdlet, isProxyForCmdlet: true, @@ -829,7 +829,7 @@ private static string EscapeModuleNameForHelpComment(string name) { Dbg.Assert(name != null, "Caller should verify name != null"); - StringBuilder result = new StringBuilder(name.Length); + StringBuilder result = new(name.Length); foreach (char c in name) { if (("\"'`$#".IndexOf(c) == (-1)) && @@ -850,10 +850,10 @@ private static List> GetCombinations(params IEnumerable[] x if (x.Length == 1) { - List> result = new List>(); + List> result = new(); foreach (string s in x[0]) { - List subresult = new List(); + List subresult = new(); subresult.Add(s); result.Add(subresult); } @@ -866,12 +866,12 @@ private static List> GetCombinations(params IEnumerable[] x Array.Copy(x, 0, smallX, 0, smallX.Length); List> smallResult = GetCombinations(smallX); - List> result = new List>(); + List> result = new(); foreach (List smallSubresult in smallResult) { foreach (string s in x[x.Length - 1]) { - List newsubresult = new List(smallSubresult); + List newsubresult = new(smallSubresult); newsubresult.Add(s); result.Add(newsubresult); } @@ -941,7 +941,7 @@ private static void MultiplyParameterSets( foreach (ParameterMetadata parameter in parameters.Values) { - List> oldParameterSets = new List>(parameter.ParameterSets); + List> oldParameterSets = new(parameter.ParameterSets); parameter.ParameterSets.Clear(); foreach (KeyValuePair oldParameterSet in oldParameterSets) @@ -964,7 +964,7 @@ private static IEnumerable MultiplyParameterSets( string parameterSetNameTemplate, // {0} is the original parameter set, other ones are taken from the otherParameterSets array params IEnumerable[] otherParameterSets) { - List result = new List(); + List result = new(); List> combinations = GetCombinations(otherParameterSets); foreach (List combination in combinations) @@ -1139,8 +1139,8 @@ private void GenerateMethodParametersProcessing( out string outputTypeAttributeDeclaration) { methodParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - StringBuilder outputTypeAttributeDeclarationBuilder = new StringBuilder(); - StringWriter output = new StringWriter(CultureInfo.InvariantCulture); + StringBuilder outputTypeAttributeDeclarationBuilder = new(); + StringWriter output = new(CultureInfo.InvariantCulture); output.WriteLine(" $__cmdletization_methodParameters = [System.Collections.Generic.List[Microsoft.PowerShell.Cmdletization.MethodParameter]]::new()"); output.WriteLine(); @@ -1170,8 +1170,8 @@ string parameterSetName in output.WriteLine(") -contains $_ } {"); } - List typesOfOutParameters = new List(); - List etsTypesOfOutParameters = new List(); + List typesOfOutParameters = new(); + List etsTypesOfOutParameters = new(); if (method.Parameters != null) { foreach (StaticMethodParameterMetadata methodParameter in method.Parameters) @@ -1303,7 +1303,7 @@ private void GenerateMethodParametersProcessing( { methodParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); outputTypeAttributeDeclaration = string.Empty; - StringWriter output = new StringWriter(CultureInfo.InvariantCulture); + StringWriter output = new(CultureInfo.InvariantCulture); output.WriteLine(" $__cmdletization_methodParameters = [System.Collections.Generic.List[Microsoft.PowerShell.Cmdletization.MethodParameter]]::new()"); output.WriteLine(" switch -exact ($PSCmdlet.ParameterSetName) { "); @@ -1320,8 +1320,8 @@ private void GenerateMethodParametersProcessing( output.WriteLine(") -contains $_ } {"); - List typesOfOutParameters = new List(); - List etsTypesOfOutParameters = new List(); + List typesOfOutParameters = new(); + List etsTypesOfOutParameters = new(); if (method.Parameters != null) { foreach (InstanceMethodParameterMetadata methodParameter in method.Parameters) @@ -1615,7 +1615,7 @@ private void GenerateQueryParametersProcessing( out Dictionary queryParameters) { queryParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); - StringWriter output = new StringWriter(CultureInfo.InvariantCulture); + StringWriter output = new(CultureInfo.InvariantCulture); output.WriteLine(" $__cmdletization_queryBuilder = $__cmdletization_objectModelWrapper.GetQueryBuilder()"); @@ -1725,7 +1725,7 @@ private void GenerateQueryParametersProcessing( if (instanceCmdlet != null) { - ParameterMetadata inputObjectParameter = new ParameterMetadata("InputObject", _objectInstanceType.MakeArrayType()); + ParameterMetadata inputObjectParameter = new("InputObject", _objectInstanceType.MakeArrayType()); ParameterSetMetadata.ParameterFlags inputObjectFlags = ParameterSetMetadata.ParameterFlags.ValueFromPipeline; if (queryParameters.Count > 0) @@ -1761,10 +1761,10 @@ private void GenerateQueryParametersProcessing( inputObjectParameter.Attributes.Add(new ValidateNotNullAttribute()); inputObjectParameter.ParameterSets.Clear(); - ParameterSetMetadata inputObjectPSet = new ParameterSetMetadata( + ParameterSetMetadata inputObjectPSet = new( int.MinValue, // non-positional inputObjectFlags, - null); // no help message + helpMessage: null); inputObjectParameter.ParameterSets.Add(ScriptWriter.InputObjectQueryParameterSetName, inputObjectPSet); queryParameters.Add(inputObjectParameter.Name, inputObjectParameter); } @@ -1859,7 +1859,7 @@ private void GenerateQueryParametersProcessing( private string GetHelpDirectiveForExternalHelp() { - StringBuilder output = new StringBuilder(); + StringBuilder output = new(); if ((_generationOptions & GenerationOptions.HelpXml) == GenerationOptions.HelpXml) { @@ -1948,9 +1948,9 @@ private static void AddPassThruParameter(IDictionary if (!outParametersArePresent) { - ParameterMetadata passThruParameter = new ParameterMetadata("PassThru", typeof(SwitchParameter)); + ParameterMetadata passThruParameter = new("PassThru", typeof(SwitchParameter)); passThruParameter.ParameterSets.Clear(); - ParameterSetMetadata passThruPSet = new ParameterSetMetadata(int.MinValue, 0, null); + ParameterSetMetadata passThruPSet = new(int.MinValue, 0, null); passThruParameter.ParameterSets.Add(ParameterAttribute.AllParameterSets, passThruPSet); commonParameters.Add(passThruParameter.Name, passThruParameter); @@ -2017,7 +2017,7 @@ private void WriteCmdlet(TextWriter output, InstanceCmdletMetadata instanceCmdle private string GetOutputAttributeForGetCmdlet() { - StringBuilder result = new StringBuilder(); + StringBuilder result = new(); result.AppendFormat( CultureInfo.InvariantCulture, "[OutputType([{0}])]", @@ -2055,7 +2055,7 @@ private void WriteGetCmdlet(TextWriter output) { Dictionary commonParameters = this.GetCommonParameters(); List commonParameterSets = GetCommonParameterSets(commonParameters); - List methodParameterSets = new List(); + List methodParameterSets = new(); methodParameterSets.Add(string.Empty); List queryParameterSets = GetQueryParameterSets(null); @@ -2100,7 +2100,7 @@ private void WriteGetCmdlet(TextWriter output) /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); } - private static object s_enumCompilationLock = new object(); + private static object s_enumCompilationLock = new(); private static void CompileEnum(EnumMetadataEnum enumMetadata) { @@ -2176,11 +2176,11 @@ internal void PopulatePSModuleInfo(PSModuleInfo moduleInfo) moduleInfo.SetModuleType(ModuleType.Cim); moduleInfo.SetVersion(new Version(_cmdletizationMetadata.Class.Version)); - Hashtable cmdletizationData = new Hashtable(StringComparer.OrdinalIgnoreCase); + Hashtable cmdletizationData = new(StringComparer.OrdinalIgnoreCase); cmdletizationData.Add(PrivateDataKey_ClassName, _cmdletizationMetadata.Class.ClassName); cmdletizationData.Add(PrivateDataKey_ObjectModelWrapper, _objectModelWrapper); - Hashtable privateData = new Hashtable(StringComparer.OrdinalIgnoreCase); + Hashtable privateData = new(StringComparer.OrdinalIgnoreCase); privateData.Add(PrivateDataKey_CmdletsOverObjects, cmdletizationData); moduleInfo.PrivateData = privateData; } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index d4b401ade60..48a47da7289 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -20,7 +20,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// internal class WildcardPatternToCimQueryParser : WildcardPatternParser { - private readonly StringBuilder _result = new StringBuilder(); + private readonly StringBuilder _result = new(); private bool _needClientSideFiltering; protected override void AppendLiteralCharacter(char c) diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index 4220c3b62bd..f9aa9f9b73c 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -28,7 +28,7 @@ public sealed class CimInstanceAdapter : PSPropertyAdapter { private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, object baseObject, string propertyName) { - PSAdaptedProperty propertyToAdd = new PSAdaptedProperty(propertyName, property); + PSAdaptedProperty propertyToAdd = new(propertyName, property); propertyToAdd.baseObject = baseObject; // propertyToAdd.adapter = this; return propertyToAdd; @@ -50,7 +50,7 @@ private static PSAdaptedProperty GetCimPropertyAdapter(CimProperty property, obj private static PSAdaptedProperty GetPSComputerNameAdapter(CimInstance cimInstance) { - PSAdaptedProperty psComputerNameProperty = new PSAdaptedProperty(RemotingConstants.ComputerNameNoteProperty, cimInstance); + PSAdaptedProperty psComputerNameProperty = new(RemotingConstants.ComputerNameNoteProperty, cimInstance); psComputerNameProperty.baseObject = cimInstance; // psComputerNameProperty.adapter = this; return psComputerNameProperty; @@ -73,7 +73,7 @@ public override System.Collections.ObjectModel.Collection Get throw new PSInvalidOperationException(msg); } - Collection result = new Collection(); + Collection result = new(); if (cimInstance.CimInstanceProperties != null) { @@ -260,7 +260,7 @@ private static void AddTypeNameHierarchy(IList typeNamesWithNamespace, I private static List GetInheritanceChain(CimInstance cimInstance) { - List inheritanceChain = new List(); + List inheritanceChain = new(); CimClass cimClass = cimInstance.CimClass; Dbg.Assert(cimClass != null, "CimInstance should always have ClassDecl"); while (cimClass != null) From aecada3e67a8f919cb71a140ff1595e321413b88 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 9 Dec 2020 19:04:23 +0000 Subject: [PATCH 104/138] Enable CA1822: Mark private members as static (#13897) --- .globalconfig | 3 ++- src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs | 2 +- src/TypeCatalogGen/TypeCatalogGen.cs | 2 +- test/tools/WebListener/Controllers/LinkController.cs | 2 +- test/tools/WebListener/Controllers/ResponseController.cs | 2 +- test/tools/WebListener/Controllers/ResumeController.cs | 2 +- test/xUnit/csharp/test_FileSystemProvider.cs | 4 ++-- test/xUnit/csharp/test_PSConfiguration.cs | 4 ++-- 8 files changed, 11 insertions(+), 10 deletions(-) diff --git a/.globalconfig b/.globalconfig index 1deb8dd7fbe..f0cc41c388e 100644 --- a/.globalconfig +++ b/.globalconfig @@ -280,7 +280,8 @@ dotnet_diagnostic.CA1820.severity = none dotnet_diagnostic.CA1821.severity = warning # CA1822: Mark members as static -dotnet_diagnostic.CA1822.severity = suggestion +dotnet_diagnostic.CA1822.severity = warning +dotnet_code_quality.ca1822.api_surface = private # CA1823: Avoid unused private fields dotnet_diagnostic.CA1823.severity = none diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs index eac9c9c6982..100565ba86e 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs @@ -33,7 +33,7 @@ protected override void Write(VT100Renderer renderer, ListBlock obj) renderer.WriteLine(); } - private void RenderNumberedList(VT100Renderer renderer, ListItemBlock block, int index) + private static void RenderNumberedList(VT100Renderer renderer, ListItemBlock block, int index) { // For a numbered list, we need to make sure the index is incremented. foreach (var line in block) diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index e05f8b63e13..993413bc59a 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -431,7 +431,7 @@ namespace System.Management.Automation {{ internal partial class PowerShellAssemblyLoadContext {{ - private Dictionary InitializeTypeCatalog() + private static Dictionary InitializeTypeCatalog() {{ return new Dictionary({0}, StringComparer.OrdinalIgnoreCase) {{"; const string SourceEnd = @" diff --git a/test/tools/WebListener/Controllers/LinkController.cs b/test/tools/WebListener/Controllers/LinkController.cs index 3aa7541f4ee..e15607d6b9b 100644 --- a/test/tools/WebListener/Controllers/LinkController.cs +++ b/test/tools/WebListener/Controllers/LinkController.cs @@ -109,7 +109,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private string GetLink(string baseUri, int maxLinks, int linkNumber, string whitespace, string type, string rel) + private static string GetLink(string baseUri, int maxLinks, int linkNumber, string whitespace, string type, string rel) { return string.Format(Constants.LinkUriTemplate, baseUri, maxLinks, linkNumber, type, whitespace, rel); } diff --git a/test/tools/WebListener/Controllers/ResponseController.cs b/test/tools/WebListener/Controllers/ResponseController.cs index 70e4659b3a4..6347abc98e6 100644 --- a/test/tools/WebListener/Controllers/ResponseController.cs +++ b/test/tools/WebListener/Controllers/ResponseController.cs @@ -99,7 +99,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private List GetSingleOrArray(JToken token) + private static List GetSingleOrArray(JToken token) { if (token.HasValues) { diff --git a/test/tools/WebListener/Controllers/ResumeController.cs b/test/tools/WebListener/Controllers/ResumeController.cs index 623744ab7d8..8aec71e416f 100644 --- a/test/tools/WebListener/Controllers/ResumeController.cs +++ b/test/tools/WebListener/Controllers/ResumeController.cs @@ -91,7 +91,7 @@ public IActionResult Error() return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } - private RangeItemHeaderValue GetRange(string rangeHeader) + private static RangeItemHeaderValue GetRange(string rangeHeader) { return RangeHeaderValue.Parse(rangeHeader).Ranges.FirstOrDefault(); } diff --git a/test/xUnit/csharp/test_FileSystemProvider.cs b/test/xUnit/csharp/test_FileSystemProvider.cs index 23702755e77..b2a017b4b95 100644 --- a/test/xUnit/csharp/test_FileSystemProvider.cs +++ b/test/xUnit/csharp/test_FileSystemProvider.cs @@ -53,7 +53,7 @@ protected virtual void Dispose(bool disposing) } } - private ExecutionContext GetExecutionContext() + private static ExecutionContext GetExecutionContext() { CultureInfo currentCulture = CultureInfo.CurrentCulture; PSHost hostInterface = new DefaultHost(currentCulture, currentCulture); @@ -63,7 +63,7 @@ private ExecutionContext GetExecutionContext() return executionContext; } - private ProviderInfo GetProvider() + private static ProviderInfo GetProvider() { ExecutionContext executionContext = GetExecutionContext(); SessionStateInternal sessionState = new SessionStateInternal(executionContext); diff --git a/test/xUnit/csharp/test_PSConfiguration.cs b/test/xUnit/csharp/test_PSConfiguration.cs index 99e8560b0c8..54e69da68f0 100644 --- a/test/xUnit/csharp/test_PSConfiguration.cs +++ b/test/xUnit/csharp/test_PSConfiguration.cs @@ -366,7 +366,7 @@ public void SetupConfigFile4() CreateEmptyFile(currentUserConfigFile); } - private void CreateEmptyFile(string fileName) + private static void CreateEmptyFile(string fileName) { File.Create(fileName).Dispose(); } @@ -382,7 +382,7 @@ public void SetupConfigFile5() CreateBrokenConfigFile(currentUserConfigFile); } - private void CreateBrokenConfigFile(string fileName) + private static void CreateBrokenConfigFile(string fileName) { File.WriteAllText(fileName, "[abbra"); } From 95ce0643c855f154e12d9b71a2aa9f77f087e63e Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Wed, 9 Dec 2020 11:07:07 -0800 Subject: [PATCH 105/138] Add `-SkipLimitCheck` switch to `Import-PowerShellDataFile` (#13672) --- .../utility/ImportPowerShellDataFile.cs | 9 +++++++- .../Microsoft.PowerShell.Utility.psd1 | 4 ++++ .../Microsoft.PowerShell.Utility.psd1 | 4 ++++ .../engine/parser/SafeValues.cs | 6 ++++-- .../engine/parser/ast.cs | 15 ++++++++++++- .../PowerShellData.tests.ps1 | 21 +++++++++++++++++++ 6 files changed, 55 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 9195e49052b..53dc461dfb2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -39,6 +39,13 @@ public string[] LiteralPath set { _isLiteralPath = true; Path = value; } } + /// + /// Gets or sets switch that determines if built-in limits are applied to the data. + /// + [Experimental("Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck", ExperimentAction.Show)] + [Parameter] + public SwitchParameter SkipLimitCheck { get; set; } + /// /// For each path, resolve it, parse it and write all hashtables to the output stream. /// @@ -61,7 +68,7 @@ protected override void ProcessRecord() var data = ast.Find(a => a is HashtableAst, false); if (data != null) { - WriteObject(data.SafeGetValue()); + WriteObject(data.SafeGetValue(SkipLimitCheck)); } else { diff --git a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 1ef5f3328e0..b883acdd0d6 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -38,6 +38,10 @@ PrivateData = @{ Name = 'Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace' Description = 'Enables -BreakAll parameter on Debug-Runspace and Debug-Job cmdlets to allow users to decide if they want PowerShell to break immediately in the current location when they attach a debugger. Enables -Runspace parameter on *-PSBreakpoint cmdlets to support management of breakpoints in another runspace.' } + @{ + Name = 'Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck' + Description = 'Enable -SkipLimitCheck switch for Import-PowerShellDataFile to not enforce built-in hashtable limits' + } ) } } diff --git a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 3b401f039e9..5ea504197fa 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -37,6 +37,10 @@ PrivateData = @{ Name = 'Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace' Description = 'Enables -BreakAll parameter on Debug-Runspace and Debug-Job cmdlets to allow users to decide if they want PowerShell to break immediately in the current location when they attach a debugger. Enables -Runspace parameter on *-PSBreakpoint cmdlets to support management of breakpoints in another runspace.' } + @{ + Name = 'Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck' + Description = 'Enable -NoLimit switch for Import-PowerShellDataFile to not enforce built-in hashtable limits' + } ) } } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index d7ef5b4cae6..a727ae1d287 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -362,7 +362,8 @@ internal enum SafeValueContext { Default, GetPowerShell, - ModuleAnalysis + ModuleAnalysis, + SkipHashtableSizeCheck, } // future proofing @@ -371,7 +372,8 @@ private GetSafeValueVisitor() { } public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueContext safeValueContext) { t_context = context; - if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) + + if (safeValueContext == SafeValueContext.SkipHashtableSizeCheck || IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) { return ast.Accept(new GetSafeValueVisitor()); } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index b9404afa738..e99fd1001c6 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -198,6 +198,19 @@ public override string ToString() /// If is deemed unsafe /// public object SafeGetValue() + { + return SafeGetValue(skipHashtableSizeCheck: false); + } + + /// + /// Constructs the resultant object from the AST and returns it if it is safe. + /// + /// Set to skip hashtable limit validation. + /// The object represented by the AST as a safe object. + /// + /// If is deemed unsafe. + /// + public object SafeGetValue(bool skipHashtableSizeCheck) { try { @@ -207,7 +220,7 @@ public object SafeGetValue() context = System.Management.Automation.Runspaces.Runspace.DefaultRunspace.ExecutionContext; } - return GetSafeValueVisitor.GetSafeValue(this, context, GetSafeValueVisitor.SafeValueContext.Default); + return GetSafeValueVisitor.GetSafeValue(this, context, skipHashtableSizeCheck ? GetSafeValueVisitor.SafeValueContext.SkipHashtableSizeCheck : GetSafeValueVisitor.SafeValueContext.Default); } catch { diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 index 6d13be5005b..222bbf7e900 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/PowerShellData.tests.ps1 @@ -1,6 +1,19 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "CI" { + BeforeAll { + $largePsd1Path = Join-Path -Path $TestDrive -ChildPath 'large.psd1' + $largePsd1Builder = [System.Text.StringBuilder]::new('@{') + 1..501 | ForEach-Object { + $largePsd1Builder.Append("key$_ = $_;") + } + $largePsd1Builder.Append('}') + Set-Content -Path $largePsd1Path -Value $largePsd1Builder.ToString() + + if ((Get-ExperimentalFeature Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck).Enabled -ne $true) { + $skipTest = $true + } + } It "Validates error on a missing path" { { Import-PowerShellDataFile -Path /SomeMissingDirectory -ErrorAction Stop } | @@ -32,4 +45,12 @@ Describe "Tests for the Import-PowerShellDataFile cmdlet" -Tags "CI" { $result.Hello | Should -BeExactly "World" } + It 'Fails if psd1 file has more than 500 keys' { + { Import-PowerShellDataFile $largePsd1Path } | Should -Throw -ErrorId 'System.InvalidOperationException,Microsoft.PowerShell.Commands.ImportPowerShellDataFileCommand' + } + + It 'Succeeds if -NoLimit is used and has more than 500 keys' -Skip:$skipTest { + $result = Import-PowerShellDataFile $largePsd1Path -SkipLimitCheck + $result.Keys.Count | Should -Be 501 + } } From 817e6b044ba35fc9227a004b6bc3139f81278464 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Wed, 9 Dec 2020 20:13:26 +0100 Subject: [PATCH 106/138] Enable nullable: System.Management.Automation.IArgumentCompleter (#14182) --- .../engine/CommandCompletion/ExtensibleCompletion.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 665dee5c8c8..777fc6c16f4 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -58,6 +58,7 @@ public ArgumentCompleterAttribute(ScriptBlock scriptBlock) /// /// A type specified by the must implement this interface. /// +#nullable enable public interface IArgumentCompleter { /// @@ -82,6 +83,7 @@ IEnumerable CompleteArgument( CommandAst commandAst, IDictionary fakeBoundParameters); } +#nullable restore /// /// From 41ab20cce30f4791f071c402e67bee635e7dcb8d Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 9 Dec 2020 19:36:48 +0000 Subject: [PATCH 107/138] Mark applicable structs as readonly and use in-modifier (#13919) --- .../NewWinEventCommand.cs | 4 +- .../commands/management/ContentCommandBase.cs | 2 +- .../commands/management/GetContentCommand.cs | 2 +- .../WindowsTaskbarJumpList/ComInterfaces.cs | 6 +- .../WindowsTaskbarJumpList/PropertyKey.cs | 2 +- .../WindowsTaskbarJumpList/TaskbarJumpList.cs | 2 +- .../DotNetCode/Eventing/EventDescriptor.cs | 2 +- .../DotNetCode/Eventing/EventProvider.cs | 20 +-- .../Eventing/UnsafeNativeMethods.cs | 6 +- .../security/CertificateProvider.cs | 4 +- .../CommandCompletion/CommandCompletion.cs | 4 +- .../engine/CommandInfo.cs | 4 +- .../engine/LanguagePrimitives.cs | 2 +- .../engine/MshCmdlet.cs | 2 +- .../engine/interpreter/BranchLabel.cs | 2 +- .../engine/interpreter/InstructionList.cs | 4 +- .../engine/interpreter/LightCompiler.cs | 2 +- .../engine/interpreter/LocalVariables.cs | 2 +- .../engine/interpreter/Utilities.cs | 2 +- .../engine/regex.cs | 2 +- .../security/nativeMethods.cs | 16 +- .../utils/PowerShellETWTracer.cs | 2 +- .../utils/tracing/EtwActivity.cs | 6 +- .../utils/tracing/EtwEventCorrelator.cs | 2 +- .../utils/tracing/PSEtwLogProvider.cs | 4 +- .../utils/tracing/TracingGen.cs | 164 +++++++++--------- 26 files changed, 135 insertions(+), 135 deletions(-) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index b710537322d..5fceca05b47 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -327,11 +327,11 @@ protected override void ProcessRecord() } } - provider.WriteEvent(ref ed, _payload); + provider.WriteEvent(in ed, _payload); } else { - provider.WriteEvent(ref ed); + provider.WriteEvent(in ed); } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index e7cc4097066..b591e05f7de 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -336,7 +336,7 @@ public PSObject AttachNotes(PSObject content) /// A struct to hold the path information and the content readers/writers /// for an item. /// - internal struct ContentHolder + internal readonly struct ContentHolder { internal ContentHolder( PathInfo pathInfo, diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index c64f1e6b954..f01645544bb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -277,7 +277,7 @@ protected override void ProcessRecord() /// true if no error occured /// false if there was an error /// - private bool ScanForwardsForTail(ContentHolder holder, CmdletProviderContext currentContext) + private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext currentContext) { var fsReader = holder.Reader as FileSystemContentReaderWriter; Dbg.Diagnostics.Assert(fsReader != null, "Tail is only supported for FileSystemContentReaderWriter"); diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs index b6aa740c72b..f5903ded5bc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs @@ -18,7 +18,7 @@ internal static class ComInterfaces /// string fields at all, nothing is lost. /// [StructLayout(LayoutKind.Sequential)] - internal struct StartUpInfo + internal readonly struct StartUpInfo { public readonly UInt32 cb; private readonly IntPtr lpReserved; @@ -141,7 +141,7 @@ internal interface IPropertyStore /// /// [PreserveSig] - HResult GetValue([In] ref PropertyKey key, [Out] PropVariant pv); + HResult GetValue([In] in PropertyKey key, [Out] PropVariant pv); /// /// Sets the value of a property in the store. @@ -150,7 +150,7 @@ internal interface IPropertyStore /// /// [PreserveSig] - HResult SetValue([In] ref PropertyKey key, [In] PropVariant pv); + HResult SetValue([In] in PropertyKey key, [In] PropVariant pv); /// /// Commits the changes. diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs index 6e12fcb0f63..ecd1918492b 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell /// Defines a unique key for a Shell Property. /// [StructLayout(LayoutKind.Sequential, Pack = 4)] - internal struct PropertyKey : IEquatable + internal readonly struct PropertyKey : IEquatable { #region Public Properties /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 6ac50fa0e3e..90c6c811bb1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -97,7 +97,7 @@ private static void CreateElevatedEntry(string title) flags |= 0x00002000; // SLDF_RUNAS_USER shellLinkDataList.SetFlags(flags); var PKEY_TITLE = new PropertyKey(new Guid("{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"), 2); - hResult = nativePropertyStore.SetValue(ref PKEY_TITLE, new PropVariant(title)); + hResult = nativePropertyStore.SetValue(in PKEY_TITLE, new PropVariant(title)); if (hResult < 0) { pCustDestList.AbortList(); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs index f2329ae2fd6..723832979f8 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs @@ -8,7 +8,7 @@ namespace System.Diagnostics.Eventing { [StructLayout(LayoutKind.Explicit, Size = 16)] - public struct EventDescriptor + public readonly struct EventDescriptor { [FieldOffset(0)] private readonly ushort _id; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index cd87c0898fd..d4e566890f0 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -488,9 +488,9 @@ public bool WriteMessageEvent(string eventMessage) /// /// /// - public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] eventPayload) + public bool WriteEvent(in EventDescriptor eventDescriptor, params object[] eventPayload) { - return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload); + return WriteTransferEvent(in eventDescriptor, Guid.Empty, eventPayload); } /// @@ -504,7 +504,7 @@ public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] even /// [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) + public bool WriteEvent(in EventDescriptor eventDescriptor, string data) { uint status = 0; @@ -534,7 +534,7 @@ public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) userData.DataPointer = (ulong)pdata; status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, - ref eventDescriptor, + in eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, 1, @@ -565,7 +565,7 @@ public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) /// pointer do the event data /// [System.Security.SecurityCritical] - protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, IntPtr data) + protected bool WriteEvent(in EventDescriptor eventDescriptor, int dataCount, IntPtr data) { uint status = 0; @@ -575,7 +575,7 @@ protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, In status = UnsafeNativeMethods.EventWriteTransfer( _regHandle, - ref eventDescriptor, + in eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, (uint)dataCount, @@ -602,7 +602,7 @@ protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, In /// /// [System.Security.SecurityCritical] - public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload) + public bool WriteTransferEvent(in EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload) { uint status = 0; @@ -719,7 +719,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related } status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, - ref eventDescriptor, + in eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, (relatedActivityId == Guid.Empty) ? null : &relatedActivityId, (uint)argCount, @@ -737,7 +737,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related } [System.Security.SecurityCritical] - protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data) + protected bool WriteTransferEvent(in EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data) { uint status = 0; @@ -747,7 +747,7 @@ protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid rela { status = UnsafeNativeMethods.EventWriteTransfer( _regHandle, - ref eventDescriptor, + in eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, &relatedActivityId, (uint)dataCount, diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 5635aed2bd0..38a3f4a60c7 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -132,7 +132,7 @@ [In][Out] ref long registrationHandle // Control (Is Enabled) APIs [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] - internal static extern int EventEnabled([In] long registrationHandle, [In] ref System.Diagnostics.Eventing.EventDescriptor eventDescriptor); + internal static extern int EventEnabled([In] long registrationHandle, [In] in System.Diagnostics.Eventing.EventDescriptor eventDescriptor); [DllImport(EventProviderDllName, ExactSpelling = true, EntryPoint = "EventProviderEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] @@ -143,7 +143,7 @@ [In][Out] ref long registrationHandle [SecurityCritical] internal static extern unsafe uint EventWrite( [In] long registrationHandle, - [In] ref EventDescriptor eventDescriptor, + [In] in EventDescriptor eventDescriptor, [In] uint userDataCount, [In] void* userData ); @@ -162,7 +162,7 @@ [In] void* userData [SecurityCritical] internal static extern unsafe uint EventWriteTransfer( [In] long registrationHandle, - [In] ref EventDescriptor eventDescriptor, + [In] in EventDescriptor eventDescriptor, [In] Guid* activityId, [In] Guid* relatedActivityId, [In] uint userDataCount, diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index 26b1668c6fb..79e3eac1971 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -123,7 +123,7 @@ public int ExpiringInDays /// The structure contains punycode name and unicode name. /// [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - public struct DnsNameRepresentation + public readonly struct DnsNameRepresentation { /// /// Punycode version of DNS name. @@ -3064,7 +3064,7 @@ public X509StoreLocation(StoreLocation location) /// The structure contains friendly name and EKU oid. /// [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - public struct EnhancedKeyUsageRepresentation + public readonly struct EnhancedKeyUsageRepresentation { /// /// Localized friendly name of EKU. diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 837fe71f66c..4d89d87e51c 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -740,7 +740,7 @@ private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSp return false; } - private struct CommandAndName + private readonly struct CommandAndName { internal readonly PSObject Command; internal readonly PSSnapinQualifiedName CommandName; @@ -1067,7 +1067,7 @@ private static bool PSv2ShouldFullyQualifyPathsPath(PowerShellExecutionHelper he return isAbsolute; } - private struct PathItemAndConvertedPath + private readonly struct PathItemAndConvertedPath { internal readonly string Path; internal readonly PSObject Item; diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index a091f7c462d..56e17ef0f5f 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -904,7 +904,7 @@ public override string ToString() } [DebuggerDisplay("{PSTypeName} {Name}")] - internal struct PSMemberNameAndType + internal readonly struct PSMemberNameAndType { public readonly string Name; @@ -960,7 +960,7 @@ private PSSyntheticTypeName(string typeName, Type type, IList member.Name.Equals(nameof(PSTypeName), StringComparison.OrdinalIgnoreCase); + private static bool IsPSTypeName(in PSMemberNameAndType member) => member.Name.Equals(nameof(PSTypeName), StringComparison.OrdinalIgnoreCase); private static string GetMemberTypeProjection(string typename, IList members) { diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 4f4e946b0ac..d27940128e7 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -5104,7 +5104,7 @@ private static IConversionData FigureLanguageConversion(Type fromType, Type toTy return null; } - private struct SignatureComparator + private readonly struct SignatureComparator { private enum TypeMatchingContext { diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index 8c572f91826..a2a7023b2d0 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -68,7 +68,7 @@ public interface IDynamicParameters /// Type used to define a parameter on a cmdlet script of function that /// can only be used as a switch. /// - public struct SwitchParameter + public readonly struct SwitchParameter { private readonly bool _isPresent; /// diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index 919a7b06106..08af974416c 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Interpreter { - internal struct RuntimeLabel + internal readonly struct RuntimeLabel { public readonly int Index; public readonly int StackDepth; diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index a29434d0d4a..972c3f8635c 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -24,7 +24,7 @@ namespace System.Management.Automation.Interpreter { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [DebuggerTypeProxy(typeof(InstructionArray.DebugView))] - internal struct InstructionArray + internal readonly struct InstructionArray { internal readonly int MaxStackDepth; internal readonly int MaxContinuationDepth; @@ -156,7 +156,7 @@ internal static InstructionView[] GetInstructionViews(IList instruc } [DebuggerDisplay("{GetValue(),nq}", Name = "{GetName(),nq}", Type = "{GetDisplayType(), nq}")] - internal struct InstructionView + internal readonly struct InstructionView { private readonly int _index; private readonly int _stackDepth; diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 0fc928d444b..85f97ee7d40 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -243,7 +243,7 @@ public override string ToString() // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [Serializable] - internal struct InterpretedFrameInfo + internal readonly struct InterpretedFrameInfo { public readonly string MethodName; diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index e093877ce34..aaee75d0234 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -78,7 +78,7 @@ public override string ToString() } } - internal struct LocalDefinition + internal readonly struct LocalDefinition { private readonly int _index; private readonly ParameterExpression _parameter; diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 35c7756ee66..3d4307f1d3a 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -668,7 +668,7 @@ public TValue this[TKey key] } } - private struct KeyInfo + private readonly struct KeyInfo { internal readonly TValue Value; internal readonly LinkedListNode List; diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index b5fc4d42dad..3f827dc08f8 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -1264,7 +1264,7 @@ protected override void EndBracketExpression() } } - private struct CharacterNormalizer + private readonly struct CharacterNormalizer { private readonly CultureInfo _cultureInfo; private readonly bool _caseInsensitive; diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index 24d5f9f68dc..37e29c1f7cb 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -1955,18 +1955,18 @@ internal struct SIP_INDIRECT_DATA } [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATCDF + internal readonly struct CRYPTCATCDF { - private DWORD _cbStruct; - private IntPtr _hFile; - private DWORD _dwCurFilePos; - private DWORD _dwLastMemberOffset; - private BOOL _fEOF; + private readonly DWORD _cbStruct; + private readonly IntPtr _hFile; + private readonly DWORD _dwCurFilePos; + private readonly DWORD _dwLastMemberOffset; + private readonly BOOL _fEOF; [MarshalAs(UnmanagedType.LPWStr)] - private string _pwszResultDir; + private readonly string _pwszResultDir; - private IntPtr _hCATStore; + private readonly IntPtr _hCATStore; } [StructLayout(LayoutKind.Sequential)] diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index e7172cfd666..9c5e2046c87 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -866,7 +866,7 @@ private bool Trace(PowerShellTraceEvent traceEvent, PowerShellTraceLevel level, } } - return _provider.WriteEvent(ref ed, args); + return _provider.WriteEvent(in ed, args); } /// diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 54e1034b1ac..b50f68e699d 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -255,7 +255,7 @@ public void Callback(IAsyncResult asyncResult) private static readonly Dictionary providers = new Dictionary(); private static readonly object syncLock = new object(); - private static EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); + private static readonly EventDescriptor _WriteTransferEvent = new EventDescriptor(0x1f05, 0x1, 0x11, 0x5, 0x14, 0x0, (long)0x4000000000000000); private EventProvider currentProvider; @@ -328,7 +328,7 @@ public void CorrelateWithActivity(Guid parentActivityId) if (parentActivityId != Guid.Empty) { EventDescriptor transferEvent = TransferEvent; - provider.WriteTransferEvent(ref transferEvent, parentActivityId, activityId, parentActivityId); + provider.WriteTransferEvent(in transferEvent, parentActivityId, activityId, parentActivityId); } } @@ -473,7 +473,7 @@ protected void WriteEvent(EventDescriptor ed, params object[] payload) } } - bool success = provider.WriteEvent(ref ed, payload); + bool success = provider.WriteEvent(in ed, payload); if (EventWritten != null) { EventWritten.Invoke(this, new EtwEventArgs(ed, success, payload)); diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index ce2d05395cf..28d4cfe13ee 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -98,7 +98,7 @@ public IEtwActivityReverter StartActivity(Guid relatedActivityId) if (relatedActivityId != Guid.Empty) { var tempTransferEvent = _transferEvent; - _transferProvider.WriteTransferEvent(ref tempTransferEvent, relatedActivityId); + _transferProvider.WriteTransferEvent(in tempTransferEvent, relatedActivityId); } return retActivity; diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index b511a037294..03b6c9a558b 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -284,7 +284,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev EventDescriptor desc = new EventDescriptor((int)id, (byte)PSEventVersion.One, (byte)channel, (byte)level, (byte)opcode, (int)task, longKeyword); - etwProvider.WriteEvent(ref desc, args); + etwProvider.WriteEvent(in desc, args); } /// @@ -292,7 +292,7 @@ internal void WriteEvent(PSEventId id, PSChannel channel, PSOpcode opcode, PSLev /// internal void WriteTransferEvent(Guid parentActivityId) { - etwProvider.WriteTransferEvent(ref _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); + etwProvider.WriteTransferEvent(in _xferEventDescriptor, parentActivityId, EtwActivity.GetActivityId(), parentActivityId); } /// diff --git a/src/System.Management.Automation/utils/tracing/TracingGen.cs b/src/System.Management.Automation/utils/tracing/TracingGen.cs index ea369e4513a..d6d5f5070bb 100644 --- a/src/System.Management.Automation/utils/tracing/TracingGen.cs +++ b/src/System.Management.Automation/utils/tracing/TracingGen.cs @@ -38,88 +38,88 @@ public sealed partial class Tracer : System.Management.Automation.Tracing.EtwAct public const long KeywordAll = 0xFFFFFFFF; private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a"); - private static EventDescriptor WriteTransferEventEvent; - private static EventDescriptor DebugMessageEvent; - private static EventDescriptor M3PAbortingWorkflowExecutionEvent; - private static EventDescriptor M3PActivityExecutionFinishedEvent; - private static EventDescriptor M3PActivityExecutionQueuedEvent; - private static EventDescriptor M3PActivityExecutionStartedEvent; - private static EventDescriptor M3PBeginContainerParentJobExecutionEvent; - private static EventDescriptor M3PBeginCreateNewJobEvent; - private static EventDescriptor M3PBeginJobLogicEvent; - private static EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobEventHandlerEvent; - private static EventDescriptor M3PBeginProxyJobExecutionEvent; - private static EventDescriptor M3PBeginRunGarbageCollectionEvent; - private static EventDescriptor M3PBeginStartWorkflowApplicationEvent; - private static EventDescriptor M3PBeginWorkflowExecutionEvent; - private static EventDescriptor M3PCancellingWorkflowExecutionEvent; - private static EventDescriptor M3PChildWorkflowJobAdditionEvent; - private static EventDescriptor M3PEndContainerParentJobExecutionEvent; - private static EventDescriptor M3PEndCreateNewJobEvent; - private static EventDescriptor M3PEndJobLogicEvent; - private static EventDescriptor M3PEndpointDisabledEvent; - private static EventDescriptor M3PEndpointEnabledEvent; - private static EventDescriptor M3PEndpointModifiedEvent; - private static EventDescriptor M3PEndpointRegisteredEvent; - private static EventDescriptor M3PEndpointUnregisteredEvent; - private static EventDescriptor M3PEndProxyChildJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobEventHandlerEvent; - private static EventDescriptor M3PEndProxyJobExecutionEvent; - private static EventDescriptor M3PEndRunGarbageCollectionEvent; - private static EventDescriptor M3PEndStartWorkflowApplicationEvent; - private static EventDescriptor M3PEndWorkflowExecutionEvent; - private static EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PForcedWorkflowShutdownErrorEvent; - private static EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; - private static EventDescriptor M3PForcedWorkflowShutdownStartedEvent; - private static EventDescriptor M3PImportedWorkflowFromXamlEvent; - private static EventDescriptor M3PImportingWorkflowFromXamlEvent; - private static EventDescriptor M3PJobCreationCompleteEvent; - private static EventDescriptor M3PJobErrorEvent; - private static EventDescriptor M3PJobRemovedEvent; - private static EventDescriptor M3PJobRemoveErrorEvent; - private static EventDescriptor M3PJobStateChangedEvent; - private static EventDescriptor M3PLoadingWorkflowForExecutionEvent; - private static EventDescriptor M3POutOfProcessRunspaceStartedEvent; - private static EventDescriptor M3PParameterSplattingWasPerformedEvent; - private static EventDescriptor M3PParentJobCreatedEvent; - private static EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; - private static EventDescriptor M3PPersistingWorkflowEvent; - private static EventDescriptor M3PProxyJobRemoteJobAssociationEvent; - private static EventDescriptor M3PRemoveJobStartedEvent; - private static EventDescriptor M3PRunspaceAvailabilityChangedEvent; - private static EventDescriptor M3PRunspaceStateChangedEvent; - private static EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; - private static EventDescriptor M3PUnloadingWorkflowEvent; - private static EventDescriptor M3PWorkflowActivityExecutionFailedEvent; - private static EventDescriptor M3PWorkflowActivityValidatedEvent; - private static EventDescriptor M3PWorkflowActivityValidationFailedEvent; - private static EventDescriptor M3PWorkflowCleanupPerformedEvent; - private static EventDescriptor M3PWorkflowDeletedFromDiskEvent; - private static EventDescriptor M3PWorkflowEngineStartedEvent; - private static EventDescriptor M3PWorkflowExecutionAbortedEvent; - private static EventDescriptor M3PWorkflowExecutionCancelledEvent; - private static EventDescriptor M3PWorkflowExecutionErrorEvent; - private static EventDescriptor M3PWorkflowExecutionFinishedEvent; - private static EventDescriptor M3PWorkflowExecutionStartedEvent; - private static EventDescriptor M3PWorkflowJobCreatedEvent; - private static EventDescriptor M3PWorkflowLoadedForExecutionEvent; - private static EventDescriptor M3PWorkflowLoadedFromDiskEvent; - private static EventDescriptor M3PWorkflowManagerCheckpointEvent; - private static EventDescriptor M3PWorkflowPersistedEvent; - private static EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; - private static EventDescriptor M3PWorkflowPluginRestartedEvent; - private static EventDescriptor M3PWorkflowPluginStartedEvent; - private static EventDescriptor M3PWorkflowQuotaViolatedEvent; - private static EventDescriptor M3PWorkflowResumedEvent; - private static EventDescriptor M3PWorkflowResumingEvent; - private static EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; - private static EventDescriptor M3PWorkflowStateChangedEvent; - private static EventDescriptor M3PWorkflowUnloadedEvent; - private static EventDescriptor M3PWorkflowValidationErrorEvent; - private static EventDescriptor M3PWorkflowValidationFinishedEvent; - private static EventDescriptor M3PWorkflowValidationStartedEvent; + private static readonly EventDescriptor WriteTransferEventEvent; + private static readonly EventDescriptor DebugMessageEvent; + private static readonly EventDescriptor M3PAbortingWorkflowExecutionEvent; + private static readonly EventDescriptor M3PActivityExecutionFinishedEvent; + private static readonly EventDescriptor M3PActivityExecutionQueuedEvent; + private static readonly EventDescriptor M3PActivityExecutionStartedEvent; + private static readonly EventDescriptor M3PBeginContainerParentJobExecutionEvent; + private static readonly EventDescriptor M3PBeginCreateNewJobEvent; + private static readonly EventDescriptor M3PBeginJobLogicEvent; + private static readonly EventDescriptor M3PBeginProxyChildJobEventHandlerEvent; + private static readonly EventDescriptor M3PBeginProxyJobEventHandlerEvent; + private static readonly EventDescriptor M3PBeginProxyJobExecutionEvent; + private static readonly EventDescriptor M3PBeginRunGarbageCollectionEvent; + private static readonly EventDescriptor M3PBeginStartWorkflowApplicationEvent; + private static readonly EventDescriptor M3PBeginWorkflowExecutionEvent; + private static readonly EventDescriptor M3PCancellingWorkflowExecutionEvent; + private static readonly EventDescriptor M3PChildWorkflowJobAdditionEvent; + private static readonly EventDescriptor M3PEndContainerParentJobExecutionEvent; + private static readonly EventDescriptor M3PEndCreateNewJobEvent; + private static readonly EventDescriptor M3PEndJobLogicEvent; + private static readonly EventDescriptor M3PEndpointDisabledEvent; + private static readonly EventDescriptor M3PEndpointEnabledEvent; + private static readonly EventDescriptor M3PEndpointModifiedEvent; + private static readonly EventDescriptor M3PEndpointRegisteredEvent; + private static readonly EventDescriptor M3PEndpointUnregisteredEvent; + private static readonly EventDescriptor M3PEndProxyChildJobEventHandlerEvent; + private static readonly EventDescriptor M3PEndProxyJobEventHandlerEvent; + private static readonly EventDescriptor M3PEndProxyJobExecutionEvent; + private static readonly EventDescriptor M3PEndRunGarbageCollectionEvent; + private static readonly EventDescriptor M3PEndStartWorkflowApplicationEvent; + private static readonly EventDescriptor M3PEndWorkflowExecutionEvent; + private static readonly EventDescriptor M3PErrorImportingWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownErrorEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownFinishedEvent; + private static readonly EventDescriptor M3PForcedWorkflowShutdownStartedEvent; + private static readonly EventDescriptor M3PImportedWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PImportingWorkflowFromXamlEvent; + private static readonly EventDescriptor M3PJobCreationCompleteEvent; + private static readonly EventDescriptor M3PJobErrorEvent; + private static readonly EventDescriptor M3PJobRemovedEvent; + private static readonly EventDescriptor M3PJobRemoveErrorEvent; + private static readonly EventDescriptor M3PJobStateChangedEvent; + private static readonly EventDescriptor M3PLoadingWorkflowForExecutionEvent; + private static readonly EventDescriptor M3POutOfProcessRunspaceStartedEvent; + private static readonly EventDescriptor M3PParameterSplattingWasPerformedEvent; + private static readonly EventDescriptor M3PParentJobCreatedEvent; + private static readonly EventDescriptor M3PPersistenceStoreMaxSizeReachedEvent; + private static readonly EventDescriptor M3PPersistingWorkflowEvent; + private static readonly EventDescriptor M3PProxyJobRemoteJobAssociationEvent; + private static readonly EventDescriptor M3PRemoveJobStartedEvent; + private static readonly EventDescriptor M3PRunspaceAvailabilityChangedEvent; + private static readonly EventDescriptor M3PRunspaceStateChangedEvent; + private static readonly EventDescriptor M3PTrackingGuidContainerParentJobCorrelationEvent; + private static readonly EventDescriptor M3PUnloadingWorkflowEvent; + private static readonly EventDescriptor M3PWorkflowActivityExecutionFailedEvent; + private static readonly EventDescriptor M3PWorkflowActivityValidatedEvent; + private static readonly EventDescriptor M3PWorkflowActivityValidationFailedEvent; + private static readonly EventDescriptor M3PWorkflowCleanupPerformedEvent; + private static readonly EventDescriptor M3PWorkflowDeletedFromDiskEvent; + private static readonly EventDescriptor M3PWorkflowEngineStartedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionAbortedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionCancelledEvent; + private static readonly EventDescriptor M3PWorkflowExecutionErrorEvent; + private static readonly EventDescriptor M3PWorkflowExecutionFinishedEvent; + private static readonly EventDescriptor M3PWorkflowExecutionStartedEvent; + private static readonly EventDescriptor M3PWorkflowJobCreatedEvent; + private static readonly EventDescriptor M3PWorkflowLoadedForExecutionEvent; + private static readonly EventDescriptor M3PWorkflowLoadedFromDiskEvent; + private static readonly EventDescriptor M3PWorkflowManagerCheckpointEvent; + private static readonly EventDescriptor M3PWorkflowPersistedEvent; + private static readonly EventDescriptor M3PWorkflowPluginRequestedToShutdownEvent; + private static readonly EventDescriptor M3PWorkflowPluginRestartedEvent; + private static readonly EventDescriptor M3PWorkflowPluginStartedEvent; + private static readonly EventDescriptor M3PWorkflowQuotaViolatedEvent; + private static readonly EventDescriptor M3PWorkflowResumedEvent; + private static readonly EventDescriptor M3PWorkflowResumingEvent; + private static readonly EventDescriptor M3PWorkflowRunspacePoolCreatedEvent; + private static readonly EventDescriptor M3PWorkflowStateChangedEvent; + private static readonly EventDescriptor M3PWorkflowUnloadedEvent; + private static readonly EventDescriptor M3PWorkflowValidationErrorEvent; + private static readonly EventDescriptor M3PWorkflowValidationFinishedEvent; + private static readonly EventDescriptor M3PWorkflowValidationStartedEvent; /// /// Static constructor. From 971c42876924282fac59b965c4052b285b60812f Mon Sep 17 00:00:00 2001 From: Xavier Hahn Date: Wed, 9 Dec 2020 20:37:29 +0100 Subject: [PATCH 108/138] Simplify getting Encoding in `TranscriptionOption.FlushContentToDisk` (#13910) --- .../engine/Utils.cs | 85 ------------------- .../engine/hostifaces/MshHostUserInterface.cs | 36 +++----- 2 files changed, 12 insertions(+), 109 deletions(-) diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 84e1fb23936..dd464ab4e76 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1391,96 +1391,11 @@ internal static bool Succeeded(int hresult) return hresult >= 0; } - // Attempt to determine the existing encoding - internal static Encoding GetEncoding(string path) - { - if (!File.Exists(path)) - { - return ClrFacade.GetDefaultEncoding(); - } - - byte[] initialBytes = new byte[100]; - int bytesRead = 0; - - try - { - using (FileStream stream = System.IO.File.OpenRead(path)) - { - using (BinaryReader reader = new BinaryReader(stream)) - { - bytesRead = reader.Read(initialBytes, 0, 100); - } - } - } - catch (IOException) - { - return ClrFacade.GetDefaultEncoding(); - } - - // Test for four-byte preambles - string preamble = null; - Encoding foundEncoding = ClrFacade.GetDefaultEncoding(); - - if (bytesRead > 3) - { - preamble = string.Join("-", initialBytes[0], initialBytes[1], initialBytes[2], initialBytes[3]); - - if (encodingMap.TryGetValue(preamble, out foundEncoding)) - { - return foundEncoding; - } - } - - // Test for three-byte preambles - if (bytesRead > 2) - { - preamble = string.Join("-", initialBytes[0], initialBytes[1], initialBytes[2]); - if (encodingMap.TryGetValue(preamble, out foundEncoding)) - { - return foundEncoding; - } - } - - // Test for two-byte preambles - if (bytesRead > 1) - { - preamble = string.Join("-", initialBytes[0], initialBytes[1]); - if (encodingMap.TryGetValue(preamble, out foundEncoding)) - { - return foundEncoding; - } - } - - // Check for binary - string initialBytesAsAscii = System.Text.Encoding.ASCII.GetString(initialBytes, 0, bytesRead); - if (initialBytesAsAscii.IndexOfAny(nonPrintableCharacters) >= 0) - { - return Encoding.Unicode; - } - - return utf8NoBom; - } - // BigEndianUTF32 encoding is possible, but requires creation internal static readonly Encoding BigEndianUTF32Encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true); // [System.Text.Encoding]::GetEncodings() | Where-Object { $_.GetEncoding().GetPreamble() } | // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto - internal static readonly Dictionary encodingMap = - new Dictionary() - { - { "255-254", Encoding.Unicode }, - { "254-255", Encoding.BigEndianUnicode }, - { "255-254-0-0", Encoding.UTF32 }, - { "0-0-254-255", BigEndianUTF32Encoding }, - { "239-187-191", Encoding.UTF8 }, - }; - - internal static readonly char[] nonPrintableCharacters = { - (char) 0, (char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7, (char) 8, - (char) 11, (char) 12, (char) 14, (char) 15, (char) 16, (char) 17, (char) 18, (char) 19, (char) 20, - (char) 21, (char) 22, (char) 23, (char) 24, (char) 25, (char) 26, (char) 28, (char) 29, (char) 30, - (char) 31, (char) 127, (char) 129, (char) 141, (char) 143, (char) 144, (char) 157 }; internal static readonly UTF8Encoding utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 811eaf1c3f6..4996ed2493a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1071,22 +1071,7 @@ internal TranscriptionOption() /// /// The path that this transcript is being logged to. /// - internal string Path - { - get - { - return _path; - } - - set - { - _path = value; - // Get the encoding from the file, or default (UTF8-NoBom) - Encoding = Utils.GetEncoding(value); - } - } - - private string _path; + internal string Path { get; set; } /// /// Any output to log for this transcript. @@ -1104,12 +1089,6 @@ internal string Path /// internal bool IncludeInvocationHeader { get; set; } - /// - /// The encoding of this transcript, so that appending to it - /// can be done correctly. - /// - internal Encoding Encoding { get; private set; } - /// /// Logs buffered content to disk. We use this instead of File.AppendAllLines /// so that we don't need to pay seek penalties all the time, and so that we @@ -1117,6 +1096,13 @@ internal string Path /// internal void FlushContentToDisk() { + static Encoding GetPathEncoding(string path) + { + using StreamReader reader = new StreamReader(path, Utils.utf8NoBom, detectEncodingFromByteOrderMarks: true); + _ = reader.Read(); + return reader.CurrentEncoding; + } + lock (OutputBeingLogged) { if (!_disposed) @@ -1125,11 +1111,13 @@ internal void FlushContentToDisk() { try { + var currentEncoding = GetPathEncoding(this.Path); + // Try to first open the file with permissions that will allow us to read from it // later. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read), - this.Encoding); + currentEncoding); _contentWriter.BaseStream.Seek(0, SeekOrigin.End); } catch (IOException) @@ -1138,7 +1126,7 @@ internal void FlushContentToDisk() // file permissions. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), - this.Encoding); + Utils.utf8NoBom); } _contentWriter.AutoFlush = true; From ba49eb225f821224fefd9b4559d23c35badcca5e Mon Sep 17 00:00:00 2001 From: Ilya Date: Thu, 10 Dec 2020 00:46:27 +0500 Subject: [PATCH 109/138] Optimize IEnumerable variant of replace operator (#14221) --- .../engine/lang/parserutils.cs | 77 +++++++++++++------ .../Operators/ReplaceOperator.Tests.ps1 | 18 +++++ 2 files changed, 70 insertions(+), 25 deletions(-) diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 217e348bfde..52c64400ccd 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -965,6 +965,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e } } + var replacer = ReplaceOperatorImpl.Create(context, rr, substitute); IEnumerator list = LanguagePrimitives.GetEnumerator(lval); if (list == null) { @@ -978,7 +979,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e lvalString = lval?.ToString() ?? string.Empty; } - return ReplaceOperatorImpl(context, lvalString, rr, substitute); + return replacer.Replace(lvalString); } else { @@ -986,45 +987,55 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e while (ParserOps.MoveNext(context, errorPosition, list)) { string lvalString = PSObject.ToStringParser(context, ParserOps.Current(errorPosition, list)); - resultList.Add(ReplaceOperatorImpl(context, lvalString, rr, substitute)); + resultList.Add(replacer.Replace(lvalString)); } return resultList.ToArray(); } } - /// - /// ReplaceOperator implementation. - /// Abstracts away conversion of the optional substitute parameter to either a string or a MatchEvaluator delegate - /// and finally returns the result of the final Regex.Replace operation. - /// - /// The execution context in which to evaluate the expression. - /// The input string. - /// A Regex instance. - /// The substitute value. - /// The result of the regex.Replace operation. - private static object ReplaceOperatorImpl(ExecutionContext context, string input, Regex regex, object substitute) + private struct ReplaceOperatorImpl { - switch (substitute) + public static ReplaceOperatorImpl Create(ExecutionContext context, Regex regex, object substitute) + { + return new ReplaceOperatorImpl(context, regex, substitute); + } + + private readonly Regex _regex; + private readonly string _cachedReplacementString; + private readonly MatchEvaluator _cachedMatchEvaluator; + + private ReplaceOperatorImpl( + ExecutionContext context, + Regex regex, + object substitute) { - case string replacementString: - return regex.Replace(input, replacementString); + _regex = regex; + _cachedReplacementString = null; + _cachedMatchEvaluator = null; + + switch (substitute) + { + case string replacement: + _cachedReplacementString = replacement; + break; - case ScriptBlock sb: - MatchEvaluator me = GetMatchEvaluator(context, sb); - return regex.Replace(input, me); + case ScriptBlock sb: + _cachedMatchEvaluator = GetMatchEvaluator(context, sb); + break; - case object val when LanguagePrimitives.TryConvertTo(val, out MatchEvaluator matchEvaluator): - return regex.Replace(input, matchEvaluator); + case object val when LanguagePrimitives.TryConvertTo(val, out _cachedMatchEvaluator): + break; - default: - string replacement = PSObject.ToStringParser(context, substitute); - return regex.Replace(input, replacement); + default: + _cachedReplacementString = PSObject.ToStringParser(context, substitute); + break; + } } // Local helper function to avoid creating an instance of the generated delegate helper class // every time 'ReplaceOperatorImpl' is invoked. - static MatchEvaluator GetMatchEvaluator(ExecutionContext context, ScriptBlock sb) + private static MatchEvaluator GetMatchEvaluator(ExecutionContext context, ScriptBlock sb) { return match => { @@ -1039,6 +1050,22 @@ static MatchEvaluator GetMatchEvaluator(ExecutionContext context, ScriptBlock sb return PSObject.ToStringParser(context, result); }; } + + /// + /// ReplaceOperator implementation. + /// Abstracts away conversion of the optional substitute parameter to either a string or a MatchEvaluator delegate + /// and finally returns the result of the final Regex.Replace operation. + /// + public object Replace(string input) + { + if (_cachedReplacementString is not null) + { + return _regex.Replace(input, _cachedReplacementString); + } + + Dbg.Assert(_cachedMatchEvaluator is not null, "_cachedMatchEvaluator should be not null when code reach here."); + return _regex.Replace(input, _cachedMatchEvaluator); + } } /// diff --git a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 index 59d7039898a..b72779f59c4 100644 --- a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 @@ -11,6 +11,12 @@ Describe "Replace Operator" -Tags CI { $res | Should -BeExactly "image.jpg" } + It "Replace operator can convert an substitution object to string" { + $substitution = Get-Process -Id $pid + $res = "!3!" -replace "3",$substitution + $res | Should -BeExactly "!System.Diagnostics.Process (pwsh)!" + } + It "Replace operator can be case-insensitive and case-sensitive" { $res = "book" -replace "B","C" $res | Should -BeExactly "Cook" @@ -29,6 +35,18 @@ Describe "Replace Operator" -Tags CI { $res = "PowerPoint" -replace "Point" $res | Should -BeExactly "Power" } + + It "Replace operator can take an enumerable as first argument, a mandatory pattern, and an optional substitution" { + $res = "PowerPoint1","PowerPoint2" -replace "Point","Shell" + $res.Count | Should -Be 2 + $res[0] | Should -BeExactly "PowerShell1" + $res[1] | Should -BeExactly "PowerShell2" + + $res = "PowerPoint1","PowerPoint2" -replace "Point" + $res.Count | Should -Be 2 + $res[0] | Should -BeExactly "Power1" + $res[1] | Should -BeExactly "Power2" + } } Context "Replace operator substitutions" { From cb13c304671913df8811cf59c21501bae4d81c73 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Wed, 9 Dec 2020 20:57:43 +0100 Subject: [PATCH 110/138] Enable nullable: System.Management.Automation.Provider.IContentWriter (#14152) --- src/System.Management.Automation/namespaces/IContentWriter.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/System.Management.Automation/namespaces/IContentWriter.cs b/src/System.Management.Automation/namespaces/IContentWriter.cs index eee05cacf13..621808af80c 100644 --- a/src/System.Management.Automation/namespaces/IContentWriter.cs +++ b/src/System.Management.Automation/namespaces/IContentWriter.cs @@ -4,6 +4,7 @@ using System.Collections; using System.IO; +#nullable enable namespace System.Management.Automation.Provider { #region IContentWriter From f74acaa768ea542f0fdb874533e35d796c3f14cb Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Wed, 9 Dec 2020 19:59:08 +0000 Subject: [PATCH 111/138] Replace GetFiles in TestModuleManifestCommand (#14317) --- .../engine/Modules/TestModuleManifestCommand.cs | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index b31ec151af5..265287a010f 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -420,23 +420,13 @@ private static bool IsValidGacAssembly(string assemblyName) try { - var allFiles = Directory.GetFiles(gacPath, assemblyFile, SearchOption.AllDirectories); - - if (allFiles.Length == 0) - { - var allNgenFiles = Directory.GetFiles(gacPath, ngenAssemblyFile, SearchOption.AllDirectories); - if (allNgenFiles.Length == 0) - { - return false; - } - } + return Directory.EnumerateFiles(gacPath, assemblyFile, SearchOption.AllDirectories).Any() + || Directory.EnumerateFiles(gacPath, ngenAssemblyFile, SearchOption.AllDirectories).Any(); } catch { return false; } - - return true; #endif } } From 600b658990db10b5b625ee62b62022bf686ff329 Mon Sep 17 00:00:00 2001 From: Aditya Patwardhan Date: Wed, 9 Dec 2020 12:29:45 -0800 Subject: [PATCH 112/138] Use `Microsoft.PowerShell.MarkdownRender` package from `nuget.org` (#14090) --- PowerShell.sln | 4 +- assets/files.wxs | 4 - ...crosoft.PowerShell.Commands.Utility.csproj | 2 +- .../CodeInlineRenderer.cs | 18 - .../EmphasisInlineRenderer.cs | 18 - .../FencedCodeBlockRenderer.cs | 41 -- .../HeaderBlockRenderer.cs | 55 -- .../LeafInlineRenderer.cs | 28 - .../LineBreakRenderer.cs | 27 - .../LinkInlineRenderer.cs | 28 - .../ListBlockRenderer.cs | 48 -- .../ListItemBlockRenderer.cs | 80 --- .../MarkdownConverter.cs | 90 ---- ...Microsoft.PowerShell.MarkdownRender.csproj | 15 - .../ParagraphBlockRenderer.cs | 22 - .../QuoteBlockRenderer.cs | 25 - .../VT100EscapeSequences.cs | 478 ------------------ .../VT100ObjectRenderer.cs | 16 - .../VT100Renderer.cs | 42 -- tools/packaging/packaging.psm1 | 13 +- .../templates/windows-packaging.yml | 7 +- tools/releaseBuild/signing.xml | 1 - 22 files changed, 9 insertions(+), 1053 deletions(-) delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs delete mode 100644 src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs diff --git a/PowerShell.sln b/PowerShell.sln index b164361d7d2..224d27ab3fc 100644 --- a/PowerShell.sln +++ b/PowerShell.sln @@ -1,5 +1,5 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 +# Visual Studio Version 16 # https://github.com/dotnet/project-system/blob/master/docs/opening-with-new-project-system.md#project-type-guids VisualStudioVersion = 15.0.26730.12 MinimumVisualStudioVersion = 10.0.40219.1 @@ -29,8 +29,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.WSMan.Runtime", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "powershell-unix", "src\powershell-unix\powershell-unix.csproj", "{73EA0BE6-C0C5-4B56-A5AA-DADA4C01D690}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.PowerShell.MarkdownRender", "src\Microsoft.PowerShell.MarkdownRender\Microsoft.PowerShell.MarkdownRender.csproj", "{43D4F8DA-A7DE-494B-81B0-BDE3CFD7B1F1}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "xUnit.tests", "test\xUnit\xUnit.tests.csproj", "{08704934-9764-48CE-86DB-BCF0A1CF7899}" EndProject # Configuration mapping comment diff --git a/assets/files.wxs b/assets/files.wxs index 418a32db376..199e964fe17 100644 --- a/assets/files.wxs +++ b/assets/files.wxs @@ -1163,9 +1163,6 @@ - - - @@ -3451,7 +3448,6 @@ - diff --git a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 3ce6232894f..b6f1bbaf636 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs deleted file mode 100644 index f3dc651bd4c..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax.Inlines; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for inline code elements. - /// - internal class CodeInlineRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, CodeInline obj) - { - renderer.Write(renderer.EscapeSequences.FormatCode(obj.Content, isInline: true)); - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs deleted file mode 100644 index 95a2bd1c7e8..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax.Inlines; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for bold and italics elements. - /// - internal class EmphasisInlineRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, EmphasisInline obj) - { - renderer.Write(renderer.EscapeSequences.FormatEmphasis(obj.FirstChild.ToString(), isBold: obj.DelimiterCount == 2)); - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs deleted file mode 100644 index d878ae922d7..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using Markdig.Helpers; -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for code blocks with language type. - /// - internal class FencedCodeBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, FencedCodeBlock obj) - { - if (obj?.Lines.Lines != null) - { - foreach (StringLine codeLine in obj.Lines.Lines) - { - if (!string.IsNullOrWhiteSpace(codeLine.ToString())) - { - // If the code block is of type YAML, then tab to right to improve readability. - // This specifically helps for parameters help content. - if (string.Equals(obj.Info, "yaml", StringComparison.OrdinalIgnoreCase)) - { - renderer.Write("\t").WriteLine(codeLine.ToString()); - } - else - { - renderer.WriteLine(renderer.EscapeSequences.FormatCode(codeLine.ToString(), isInline: false)); - } - } - } - - // Add a blank line after the code block for better readability. - renderer.WriteLine(); - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs deleted file mode 100644 index 454000acc54..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for headings. - /// - internal class HeaderBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, HeadingBlock obj) - { - string headerText = obj?.Inline?.FirstChild?.ToString(); - - if (!string.IsNullOrEmpty(headerText)) - { - // Format header and then add blank line to improve readability. - switch (obj.Level) - { - case 1: - renderer.WriteLine(renderer.EscapeSequences.FormatHeader1(headerText)); - renderer.WriteLine(); - break; - - case 2: - renderer.WriteLine(renderer.EscapeSequences.FormatHeader2(headerText)); - renderer.WriteLine(); - break; - - case 3: - renderer.WriteLine(renderer.EscapeSequences.FormatHeader3(headerText)); - renderer.WriteLine(); - break; - - case 4: - renderer.WriteLine(renderer.EscapeSequences.FormatHeader4(headerText)); - renderer.WriteLine(); - break; - - case 5: - renderer.WriteLine(renderer.EscapeSequences.FormatHeader5(headerText)); - renderer.WriteLine(); - break; - - case 6: - renderer.WriteLine(renderer.EscapeSequences.FormatHeader6(headerText)); - renderer.WriteLine(); - break; - } - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs deleted file mode 100644 index d1af0348794..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax.Inlines; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for leaf elements like plain text in paragraphs. - /// - internal class LeafInlineRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, LeafInline obj) - { - // If the next sibling is null, then this is the last line in the paragraph. - // Add new line character at the end. - // Else just write without newline at the end. - if (obj.NextSibling == null) - { - renderer.WriteLine(obj.ToString()); - } - else - { - renderer.Write(obj.ToString()); - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs deleted file mode 100644 index 11f1cf08ecc..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax.Inlines; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for line breaks. - /// - internal class LineBreakRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, LineBreakInline obj) - { - // If it is a hard line break add new line at the end. - // Else, add a space for after the last character to improve readability. - if (obj.IsHard) - { - renderer.WriteLine(); - } - else - { - renderer.Write(" "); - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs deleted file mode 100644 index e4b11f13317..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax.Inlines; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for links. - /// - internal class LinkInlineRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, LinkInline obj) - { - string text = obj.FirstChild?.ToString(); - - // Format link as image or link. - if (obj.IsImage) - { - renderer.Write(renderer.EscapeSequences.FormatImage(text)); - } - else - { - renderer.Write(renderer.EscapeSequences.FormatLink(text, obj.Url)); - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs deleted file mode 100644 index 100565ba86e..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for list blocks. - /// - internal class ListBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, ListBlock obj) - { - // start index of a numbered block. - int index = 1; - - foreach (var item in obj) - { - if (item is ListItemBlock listItem) - { - if (obj.IsOrdered) - { - RenderNumberedList(renderer, listItem, index++); - } - else - { - renderer.Write(listItem); - } - } - } - - renderer.WriteLine(); - } - - private static void RenderNumberedList(VT100Renderer renderer, ListItemBlock block, int index) - { - // For a numbered list, we need to make sure the index is incremented. - foreach (var line in block) - { - if (line is ParagraphBlock paragraphBlock) - { - renderer.Write(index.ToString()).Write(". ").Write(paragraphBlock.Inline); - } - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs deleted file mode 100644 index 6eb356b3dba..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Threading; -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for items in a list block. - /// - internal class ListItemBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, ListItemBlock obj) - { - if (obj.Parent is ListBlock parent) - { - if (!parent.IsOrdered) - { - foreach (var line in obj) - { - RenderWithIndent(renderer, line, parent.BulletType, 0); - } - } - } - } - - private void RenderWithIndent(VT100Renderer renderer, MarkdownObject block, char listBullet, int indentLevel) - { - // Indent left by 2 for each level on list. - string indent = Padding(indentLevel * 2); - - if (block is ParagraphBlock paragraphBlock) - { - renderer.Write(indent).Write(listBullet).Write(" ").Write(paragraphBlock.Inline); - } - else - { - // If there is a sublist, the block is a ListBlock instead of ParagraphBlock. - if (block is ListBlock subList) - { - foreach (var subListItem in subList) - { - if (subListItem is ListItemBlock subListItemBlock) - { - foreach (var line in subListItemBlock) - { - // Increment indent level for sub list. - RenderWithIndent(renderer, line, listBullet, indentLevel + 1); - } - } - } - } - } - } - - // Typical padding is at most a screen's width, any more than that and we won't bother caching. - private const int IndentCacheMax = 120; - - private static readonly string[] IndentCache = new string[IndentCacheMax]; - - internal static string Padding(int countOfSpaces) - { - if (countOfSpaces >= IndentCacheMax) - { - return new string(' ', countOfSpaces); - } - - var result = IndentCache[countOfSpaces]; - - if (result == null) - { - Interlocked.CompareExchange(ref IndentCache[countOfSpaces], new string(' ', countOfSpaces), comparand: null); - result = IndentCache[countOfSpaces]; - } - - return result; - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs b/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs deleted file mode 100644 index bb4a3e8a84f..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.IO; - -using Markdig; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Type of conversion from Markdown. - /// - [Flags] - public enum MarkdownConversionType - { - /// - /// Convert to HTML. - /// - HTML = 1, - - /// - /// Convert to VT100 encoded string. - /// - VT100 = 2 - } - - /// - /// Object representing the conversion from Markdown. - /// - public class MarkdownInfo - { - /// - /// Gets the Html content after conversion. - /// - public string Html { get; internal set; } - - /// - /// Gets the VT100 encoded string after conversion. - /// - public string VT100EncodedString { get; internal set; } - - /// - /// Gets the AST of the Markdown string. - /// - public Markdig.Syntax.MarkdownDocument Tokens { get; internal set; } - } - - /// - /// Class to convert a Markdown string to VT100, HTML or AST. - /// - public sealed class MarkdownConverter - { - /// - /// Convert from Markdown string to VT100 encoded string or HTML. Returns MarkdownInfo object. - /// - /// String with Markdown content to be converted. - /// Specifies type of conversion, either VT100 or HTML. - /// Specifies the rendering options for VT100 rendering. - /// MarkdownInfo object with the converted output. - public static MarkdownInfo Convert(string markdownString, MarkdownConversionType conversionType, PSMarkdownOptionInfo optionInfo) - { - var renderInfo = new MarkdownInfo(); - var writer = new StringWriter(); - MarkdownPipeline pipeline = null; - - if (conversionType.HasFlag(MarkdownConversionType.HTML)) - { - pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build(); - var renderer = new Markdig.Renderers.HtmlRenderer(writer); - renderInfo.Html = Markdig.Markdown.Convert(markdownString, renderer, pipeline).ToString(); - } - - if (conversionType.HasFlag(MarkdownConversionType.VT100)) - { - pipeline = new MarkdownPipelineBuilder().Build(); - - // Use the VT100 renderer. - var renderer = new VT100Renderer(writer, optionInfo); - renderInfo.VT100EncodedString = Markdig.Markdown.Convert(markdownString, renderer, pipeline).ToString(); - } - - // Always have AST available. - var parsed = Markdig.Markdown.Parse(markdownString, pipeline); - renderInfo.Tokens = parsed; - - return renderInfo; - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj deleted file mode 100644 index 9cab5ee5e08..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - - PowerShell's Markdown Rendering project - Microsoft.PowerShell.MarkdownRender - - - - - - - - - diff --git a/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs deleted file mode 100644 index 3b854cb2189..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for paragraphs. - /// - internal class ParagraphBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, ParagraphBlock obj) - { - // Call the renderer for children, leaf inline or line breaks. - renderer.WriteChildren(obj.Inline); - - // Add new line at the end of the paragraph. - renderer.WriteLine(); - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs deleted file mode 100644 index 7e0bda6bda8..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Renderer for adding VT100 escape sequences for quote blocks. - /// - internal class QuoteBlockRenderer : VT100ObjectRenderer - { - protected override void Write(VT100Renderer renderer, QuoteBlock obj) - { - // Iterate through each item and add the quote character before the content. - foreach (var item in obj) - { - renderer.Write(obj.QuoteChar).Write(" ").Write(item); - } - - // Add blank line after the quote block. - renderer.WriteLine(); - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs deleted file mode 100644 index 311522ac0aa..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs +++ /dev/null @@ -1,478 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Management.Automation; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Enum to name all the properties of PSMarkdownOptionInfo. - /// - public enum MarkdownOptionInfoProperty - { - /// - /// Property name Header1. - /// - Header1, - - /// - /// Property name Header2. - /// - Header2, - - /// - /// Property name Header3. - /// - Header3, - - /// - /// Property name Header4. - /// - Header4, - - /// - /// Property name Header5. - /// - Header5, - - /// - /// Property name Header6. - /// - Header6, - - /// - /// Property name Code. - /// - Code, - - /// - /// Property name Link. - /// - Link, - - /// - /// Property name Image. - /// - Image, - - /// - /// Property name EmphasisBold. - /// - EmphasisBold, - - /// - /// Property name EmphasisItalics. - /// - EmphasisItalics - } - - /// - /// Class to represent color preference options for various Markdown elements. - /// - public sealed class PSMarkdownOptionInfo - { - private const char Esc = (char)0x1b; - private const string EndSequence = "[0m"; - - /// - /// Gets or sets current VT100 escape sequence for header 1. - /// - public string Header1 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 2. - /// - public string Header2 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 3. - /// - public string Header3 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 4. - /// - public string Header4 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 5. - /// - public string Header5 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for header 6. - /// - public string Header6 { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for code inline and code blocks. - /// - public string Code { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for links. - /// - public string Link { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for images. - /// - public string Image { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for bold text. - /// - public string EmphasisBold { get; set; } - - /// - /// Gets or sets current VT100 escape sequence for italics text. - /// - public string EmphasisItalics { get; set; } - - /// - /// Gets or sets a value indicating whether VT100 escape sequences should be added. Default it true. - /// - public bool EnableVT100Encoding { get; set; } - - /// - /// Get the property as an rendered escape sequence. - /// This is used by formatting system for displaying. - /// - /// Name of the property to get as escape sequence. - /// Specified property name as escape sequence. - public string AsEscapeSequence(MarkdownOptionInfoProperty propertyName) - { - switch (propertyName) - { - case MarkdownOptionInfoProperty.Header1: - return string.Concat(Esc, Header1, Header1, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header2: - return string.Concat(Esc, Header2, Header2, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header3: - return string.Concat(Esc, Header3, Header3, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header4: - return string.Concat(Esc, Header4, Header4, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header5: - return string.Concat(Esc, Header5, Header5, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Header6: - return string.Concat(Esc, Header6, Header6, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Code: - return string.Concat(Esc, Code, Code, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Link: - return string.Concat(Esc, Link, Link, Esc, EndSequence); - - case MarkdownOptionInfoProperty.Image: - return string.Concat(Esc, Image, Image, Esc, EndSequence); - - case MarkdownOptionInfoProperty.EmphasisBold: - return string.Concat(Esc, EmphasisBold, EmphasisBold, Esc, EndSequence); - - case MarkdownOptionInfoProperty.EmphasisItalics: - return string.Concat(Esc, EmphasisItalics, EmphasisItalics, Esc, EndSequence); - - default: - break; - } - - return null; - } - - /// - /// Initializes a new instance of the class and sets dark as the default theme. - /// - public PSMarkdownOptionInfo() - { - SetDarkTheme(); - EnableVT100Encoding = true; - } - - private const string Header1Dark = "[7m"; - private const string Header2Dark = "[4;93m"; - private const string Header3Dark = "[4;94m"; - private const string Header4Dark = "[4;95m"; - private const string Header5Dark = "[4;96m"; - private const string Header6Dark = "[4;97m"; - private const string CodeDark = "[48;2;155;155;155;38;2;30;30;30m"; - private const string CodeMacOS = "[107;95m"; - private const string LinkDark = "[4;38;5;117m"; - private const string ImageDark = "[33m"; - private const string EmphasisBoldDark = "[1m"; - private const string EmphasisItalicsDark = "[36m"; - - private const string Header1Light = "[7m"; - private const string Header2Light = "[4;33m"; - private const string Header3Light = "[4;34m"; - private const string Header4Light = "[4;35m"; - private const string Header5Light = "[4;36m"; - private const string Header6Light = "[4;30m"; - private const string CodeLight = "[48;2;155;155;155;38;2;30;30;30m"; - private const string LinkLight = "[4;38;5;117m"; - private const string ImageLight = "[33m"; - private const string EmphasisBoldLight = "[1m"; - private const string EmphasisItalicsLight = "[36m"; - - /// - /// Set all preference for dark theme. - /// - public void SetDarkTheme() - { - Header1 = Header1Dark; - Header2 = Header2Dark; - Header3 = Header3Dark; - Header4 = Header4Dark; - Header5 = Header5Dark; - Header6 = Header6Dark; - Link = LinkDark; - Image = ImageDark; - EmphasisBold = EmphasisBoldDark; - EmphasisItalics = EmphasisItalicsDark; - SetCodeColor(isDarkTheme: true); - } - - /// - /// Set all preference for light theme. - /// - public void SetLightTheme() - { - Header1 = Header1Light; - Header2 = Header2Light; - Header3 = Header3Light; - Header4 = Header4Light; - Header5 = Header5Light; - Header6 = Header6Light; - Link = LinkLight; - Image = ImageLight; - EmphasisBold = EmphasisBoldLight; - EmphasisItalics = EmphasisItalicsLight; - SetCodeColor(isDarkTheme: false); - } - - private void SetCodeColor(bool isDarkTheme) - { - // MacOS terminal app does not support extended colors for VT100, so we special case for it. - Code = Platform.IsMacOS ? CodeMacOS : isDarkTheme ? CodeDark : CodeLight; - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - public class VT100EscapeSequences - { - private const char Esc = (char)0x1B; - - private readonly string endSequence = Esc + "[0m"; - - // For code blocks, [500@ make sure that the whole line has background color. - private const string LongBackgroundCodeBlock = "[500@"; - - private readonly PSMarkdownOptionInfo options; - - /// - /// Initializes a new instance of the class. - /// - /// PSMarkdownOptionInfo object to initialize with. - public VT100EscapeSequences(PSMarkdownOptionInfo optionInfo) - { - if (optionInfo == null) - { - throw new ArgumentNullException(nameof(optionInfo)); - } - - options = optionInfo; - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 1 string. - public string FormatHeader1(string headerText) - { - return FormatHeader(headerText, options.Header1); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 2 string. - public string FormatHeader2(string headerText) - { - return FormatHeader(headerText, options.Header2); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 3 string. - public string FormatHeader3(string headerText) - { - return FormatHeader(headerText, options.Header3); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 4 string. - public string FormatHeader4(string headerText) - { - return FormatHeader(headerText, options.Header4); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 5 string. - public string FormatHeader5(string headerText) - { - return FormatHeader(headerText, options.Header5); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the header to format. - /// Formatted Header 6 string. - public string FormatHeader6(string headerText) - { - return FormatHeader(headerText, options.Header6); - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the code block to format. - /// True if it is a inline code block, false otherwise. - /// Formatted code block string. - public string FormatCode(string codeText, bool isInline) - { - bool isVT100Enabled = options.EnableVT100Encoding; - - if (isInline) - { - if (isVT100Enabled) - { - return string.Concat(Esc, options.Code, codeText, endSequence); - } - else - { - return codeText; - } - } - else - { - if (isVT100Enabled) - { - return string.Concat(Esc, options.Code, codeText, Esc, LongBackgroundCodeBlock, endSequence); - } - else - { - return codeText; - } - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the link to format. - /// URL of the link. - /// True url should be hidden, false otherwise. Default is true. - /// Formatted link string. - public string FormatLink(string linkText, string url, bool hideUrl = true) - { - bool isVT100Enabled = options.EnableVT100Encoding; - - if (hideUrl) - { - if (isVT100Enabled) - { - return string.Concat(Esc, options.Link, "\"", linkText, "\"", endSequence); - } - else - { - return string.Concat("\"", linkText, "\""); - } - } - else - { - if (isVT100Enabled) - { - return string.Concat("\"", linkText, "\" (", Esc, options.Link, url, endSequence, ")"); - } - else - { - return string.Concat("\"", linkText, "\" (", url, ")"); - } - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text to format as emphasis. - /// True if it is to be formatted as bold, false to format it as italics. - /// Formatted emphasis string. - public string FormatEmphasis(string emphasisText, bool isBold) - { - var sequence = isBold ? options.EmphasisBold : options.EmphasisItalics; - - if (options.EnableVT100Encoding) - { - return string.Concat(Esc, sequence, emphasisText, endSequence); - } - else - { - return emphasisText; - } - } - - /// - /// Class to represent default VT100 escape sequences. - /// - /// Text of the image to format. - /// Formatted image string. - public string FormatImage(string altText) - { - var text = altText; - - if (string.IsNullOrEmpty(altText)) - { - text = "Image"; - } - - if (options.EnableVT100Encoding) - { - return string.Concat(Esc, options.Image, "[", text, "]", endSequence); - } - else - { - return string.Concat("[", text, "]"); - } - } - - private string FormatHeader(string headerText, string headerEscapeSequence) - { - if (options.EnableVT100Encoding) - { - return string.Concat(Esc, headerEscapeSequence, headerText, endSequence); - } - else - { - return headerText; - } - } - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs deleted file mode 100644 index 916999ecf77..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using Markdig.Renderers; -using Markdig.Syntax; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Implement the MarkdownObjectRenderer with VT100Renderer. - /// - /// The element type of the renderer. - public abstract class VT100ObjectRenderer : MarkdownObjectRenderer where T : MarkdownObject - { - } -} diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs deleted file mode 100644 index 1f5da6270dc..00000000000 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.IO; -using Markdig.Renderers; - -namespace Microsoft.PowerShell.MarkdownRender -{ - /// - /// Initializes an instance of the VT100 renderer. - /// - public sealed class VT100Renderer : TextRendererBase - { - /// - /// Initializes a new instance of the class. - /// - /// TextWriter to write to. - /// PSMarkdownOptionInfo object with options. - public VT100Renderer(TextWriter writer, PSMarkdownOptionInfo optionInfo) : base(writer) - { - EscapeSequences = new VT100EscapeSequences(optionInfo); - - // Add the various element renderers. - ObjectRenderers.Add(new HeaderBlockRenderer()); - ObjectRenderers.Add(new LineBreakRenderer()); - ObjectRenderers.Add(new CodeInlineRenderer()); - ObjectRenderers.Add(new FencedCodeBlockRenderer()); - ObjectRenderers.Add(new EmphasisInlineRenderer()); - ObjectRenderers.Add(new ParagraphBlockRenderer()); - ObjectRenderers.Add(new LeafInlineRenderer()); - ObjectRenderers.Add(new LinkInlineRenderer()); - ObjectRenderers.Add(new ListBlockRenderer()); - ObjectRenderers.Add(new ListItemBlockRenderer()); - ObjectRenderers.Add(new QuoteBlockRenderer()); - } - - /// - /// Gets the current escape sequences. - /// - public VT100EscapeSequences EscapeSequences { get; } - } -} diff --git a/tools/packaging/packaging.psm1 b/tools/packaging/packaging.psm1 index ec9c24e20c1..aaaee8688d0 100644 --- a/tools/packaging/packaging.psm1 +++ b/tools/packaging/packaging.psm1 @@ -1825,8 +1825,7 @@ function New-ILNugetPackage "Microsoft.PowerShell.SDK.dll", "Microsoft.WSMan.Management.dll", "Microsoft.WSMan.Runtime.dll", - "System.Management.Automation.dll", - "Microsoft.PowerShell.MarkdownRender.dll") + "System.Management.Automation.dll") $linuxExceptionList = @( "Microsoft.Management.Infrastructure.CimCmdlets.dll", @@ -1934,7 +1933,6 @@ function New-ILNugetPackage 'Microsoft.PowerShell.Commands.Utility' { $deps.Add([tuple]::Create([tuple]::Create('id', 'System.Management.Automation'), [tuple]::Create('version', $PackageVersion))) > $null - $deps.Add([tuple]::Create([tuple]::Create('id', 'Microsoft.PowerShell.MarkdownRender'), [tuple]::Create('version', $PackageVersion))) > $null foreach($packageInfo in (Get-ProjectPackageInformation -ProjectName $fileBaseName)) { @@ -1996,14 +1994,6 @@ function New-ILNugetPackage $deps.Add([tuple]::Create([tuple]::Create('id', $packageInfo.Name), [tuple]::Create('version', $packageInfo.Version))) > $null } } - - 'Microsoft.PowerShell.MarkdownRender' { - $deps.Add([tuple]::Create([tuple]::Create('id', 'System.Management.Automation'), [tuple]::Create('version', $PackageVersion))) > $null - foreach($packageInfo in (Get-ProjectPackageInformation -ProjectName $fileBaseName)) - { - $deps.Add([tuple]::Create([tuple]::Create('id', $packageInfo.Name), [tuple]::Create('version', $packageInfo.Version))) > $null - } - } } New-NuSpec -PackageId $fileBaseName -PackageVersion $PackageVersion -Dependency $deps -FilePath (Join-Path $filePackageFolder.FullName "$fileBaseName.nuspec") @@ -2321,7 +2311,6 @@ function CleanupGeneratedSourceCode '[Microsoft.PowerShell.Commands.AddMemberCommand' '[System.Management.Automation.ArgumentCompleterAttribute(typeof(Microsoft.PowerShell.Commands.Utility.JoinItemCompleter))]' '[System.Management.Automation.ArgumentCompleterAttribute(typeof(System.Management.Automation.PropertyNameCompleter))]' - '[System.Management.Automation.OutputTypeAttribute(typeof(Microsoft.PowerShell.MarkdownRender' '[Microsoft.PowerShell.Commands.ArgumentToTypeNameTransformationAttribute]' '[System.Management.Automation.Internal.ArchitectureSensitiveAttribute]' '[Microsoft.PowerShell.Commands.SelectStringCommand.FileinfoToStringAttribute]' diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index a89a397f343..b9d577e989c 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -124,13 +124,18 @@ jobs: "$($fullSymbolsFolder)\System.Management.Automation.dll" = "" } + $itemsToExclude = @{ + # This package is retrieved from https://www.github.com/powershell/MarkdownRender + "$($fullSymbolsFolder)\Microsoft.PowerShell.MarkdownRender.dll" + } + if ("$env:Architecture" -notlike 'fxdependent*') { $itemsToCopy += @{"$($fullSymbolsFolder)\pwsh.exe" = ""} } Write-Verbose -verbose "recusively copying $($itemsToCopyWithRecurse | out-string) to $filesToSignDirectory" - Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose + Copy-Item -Path $itemsToCopyWithRecurse -Destination $filesToSignDirectory -Recurse -verbose -exclude $itemsToExclude foreach($pattern in $itemsToCopy.Keys) { $destinationFolder = Join-Path $filesToSignDirectory -ChildPath $itemsToCopy.$pattern diff --git a/tools/releaseBuild/signing.xml b/tools/releaseBuild/signing.xml index 017dc425e0a..11f63fe69cc 100644 --- a/tools/releaseBuild/signing.xml +++ b/tools/releaseBuild/signing.xml @@ -8,7 +8,6 @@ - From 06b660cb5a77be2ad24eb3950675830a1f13b9cd Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Wed, 9 Dec 2020 21:33:17 +0100 Subject: [PATCH 113/138] Enable nullable: System.Management.Automation.IModuleAssemblyInitializer (#14158) --- .../engine/Modules/ModuleIntrinsics.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index cd354719660..94ce2664703 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1719,6 +1719,7 @@ internal enum ModuleMatchFailure /// Used by Modules/Snapins to provide a hook to the engine for startup initialization /// w.r.t compiled assembly loading. /// +#nullable enable public interface IModuleAssemblyInitializer { /// From 9724293fef5e28225e9c1674358ad9333ad3a345 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Wed, 9 Dec 2020 21:33:29 +0100 Subject: [PATCH 114/138] Enable nullable: System.Management.Automation.Language.IAstPostVisitHandler (#14164) --- .../engine/parser/PreOrderVisitor.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index 0bf5368fddb..33b2fadec64 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -254,6 +254,7 @@ public abstract class AstVisitor2 : AstVisitor /// Implement this interface when you implement or when /// you want to do something after possibly visiting the children of the ast. /// +#nullable enable public interface IAstPostVisitHandler { /// From 3905cb0beb87e3359a74f6619dc8e516457abb11 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Dec 2020 13:09:21 -0800 Subject: [PATCH 115/138] Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353) --- .../security/wldpNativeMethods.cs | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 61023787457..0eb53dbcb3a 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -78,28 +78,31 @@ public static SystemEnforcementMode GetSystemLockdownPolicy() /// An EnforcementMode that describes policy. public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle handle) { - // Check the WLDP API - SystemEnforcementMode lockdownPolicy = GetWldpPolicy(path, handle); - if (lockdownPolicy == SystemEnforcementMode.Enforce) + // Check the WLDP File policy via API + var wldpFilePolicy = GetWldpPolicy(path, handle); + if (wldpFilePolicy == SystemEnforcementMode.Enforce) { - return lockdownPolicy; + return wldpFilePolicy; + } + + // Check the AppLocker File policy via API + // This needs to be checked before WLDP audit policy + // So, that we don't end up in Audit mode, + // when we should be enforce mode. + var appLockerFilePolicy = GetAppLockerPolicy(path, handle); + if (appLockerFilePolicy == SystemEnforcementMode.Enforce) + { + return appLockerFilePolicy; } // At this point, LockdownPolicy = Audit or Allowed. // If there was a WLDP policy, but WLDP didn't block it, // then it was explicitly allowed. Therefore, return the result for the file. SystemEnforcementMode systemWldpPolicy = s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); - if ((systemWldpPolicy == SystemEnforcementMode.Enforce) || - (systemWldpPolicy == SystemEnforcementMode.Audit)) - { - return lockdownPolicy; - } - - // Check the AppLocker API - lockdownPolicy = GetAppLockerPolicy(path, handle); - if (lockdownPolicy == SystemEnforcementMode.Enforce) + if ((systemWldpPolicy == SystemEnforcementMode.Audit) || + (systemWldpPolicy == SystemEnforcementMode.Enforce)) { - return lockdownPolicy; + return wldpFilePolicy; } // If there was a system-wide AppLocker policy, but AppLocker didn't block it, @@ -107,7 +110,7 @@ public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle ha if (s_cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) == SaferPolicy.Disallowed) { - return lockdownPolicy; + return appLockerFilePolicy; } // If it's not set to 'Enforce' by the platform, allow debug overrides From f6fa26258089b812e3e05633e18b83519ac51904 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Wed, 9 Dec 2020 14:51:43 -0800 Subject: [PATCH 116/138] Fix issue with unsigned build (#14367) --- tools/releaseBuild/azureDevOps/templates/linux.yml | 1 + .../azureDevOps/templates/mac-file-signing.yml | 12 +++++++----- .../azureDevOps/templates/mac-package-signing.yml | 1 + tools/releaseBuild/azureDevOps/templates/nuget.yml | 1 + .../templates/windows-package-signing.yml | 1 + .../azureDevOps/templates/windows-packaging.yml | 2 ++ tools/releaseBuild/setReleaseTag.ps1 | 2 +- 7 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index 53e9b4f1924..f8cfd397a3d 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -120,6 +120,7 @@ jobs: pattern: | **\*.rpm useMinimatch: true + shouldSign: $(SHOULD_SIGN) # requires windows - task: AzureFileCopy@4 diff --git a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml index 46178671496..0332ec560d0 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-file-signing.yml @@ -73,6 +73,7 @@ jobs: pattern: | **\*.zip useMinimatch: true + shouldSign: $(SHOULD_SIGN) - pwsh: | $destination = "$(System.ArtifactsDirectory)\azureMacOs" @@ -89,11 +90,12 @@ jobs: artifactName: signedMacOsBins condition: and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')) - - template: EsrpScan.yml@ComplianceRepo - parameters: - scanPath: $(System.ArtifactsDirectory)\azureMacOs - pattern: | - **\* + - ${{ if eq(variables['SHOULD_SIGN'], 'true') }}: + - template: EsrpScan.yml@ComplianceRepo + parameters: + scanPath: $(System.ArtifactsDirectory)\azureMacOs + pattern: | + **\* - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 displayName: 'Component Detection' diff --git a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml index 3e3d69dcbe5..8d13693ca5a 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac-package-signing.yml @@ -60,6 +60,7 @@ jobs: pattern: | **\*.zip useMinimatch: true + shouldSign: $(SHOULD_SIGN) - template: upload-final-results.yml parameters: diff --git a/tools/releaseBuild/azureDevOps/templates/nuget.yml b/tools/releaseBuild/azureDevOps/templates/nuget.yml index a23b9c1ad67..b2702f162ee 100644 --- a/tools/releaseBuild/azureDevOps/templates/nuget.yml +++ b/tools/releaseBuild/azureDevOps/templates/nuget.yml @@ -141,6 +141,7 @@ jobs: pattern: | **\*.nupkg useMinimatch: true + shouldSign: $(SHOULD_SIGN) - pwsh: | if (-not (Test-Path '$(System.ArtifactsDirectory)\signed\')) { $null = New-Item -ItemType Directory -Path '$(System.ArtifactsDirectory)\signed\' } diff --git a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml index 81c1a2228d9..070a0840991 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-package-signing.yml @@ -49,6 +49,7 @@ jobs: **\*.msi **\*.msix useMinimatch: true + shouldSign: $(SHOULD_SIGN) - powershell: | new-item -itemtype Directory -path '$(Build.StagingDirectory)\signedPackages' diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index b9d577e989c..9aa5cc80a09 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -158,6 +158,7 @@ jobs: **\*.ps1 **\*.exe useMinimatch: true + shouldSign: $(SHOULD_SIGN) - pwsh: | Import-Module $(PowerShellRoot)/build.psm1 -Force @@ -193,6 +194,7 @@ jobs: pattern: | **\*.dll useMinimatch: true + shouldSign: $(SHOULD_SIGN) - powershell: | Get-ChildItem '$(System.ArtifactsDirectory)\thirdPartySigned\*' diff --git a/tools/releaseBuild/setReleaseTag.ps1 b/tools/releaseBuild/setReleaseTag.ps1 index 1927eb7ae60..121425d963b 100644 --- a/tools/releaseBuild/setReleaseTag.ps1 +++ b/tools/releaseBuild/setReleaseTag.ps1 @@ -79,7 +79,7 @@ if($ReleaseTag -eq 'fromBranch' -or !$ReleaseTag) New-BuildInfoJson -ReleaseTag $releaseTag } } - elseif($branchOnly -eq 'master' -or $branchOnly -like '*dailytest*') + elseif(($branchOnly -eq 'master' -and $env:BUILD_REASON -ne 'Manual') -or $branchOnly -like '*dailytest*') { $isDaily = $true Write-Verbose "daily build" -Verbose From a8213b54b3f061e3828b0f32c512814022002b71 Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 10 Dec 2020 19:36:48 +0000 Subject: [PATCH 117/138] Remove redundant local assignment in AclCommands (#14358) --- .../security/AclCommands.cs | 68 +++++++------------ 1 file changed, 25 insertions(+), 43 deletions(-) diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index b673b2c22d7..beda593b70b 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -292,20 +292,17 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) } // Get DACL - AuthorizationRuleCollection dacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; if (cos != null) { - dacl = cos.GetAccessRules(true, true, typeof(NTAccount)); + return cos.GetAccessRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); - dacl = dos.GetAccessRules(true, true, typeof(NTAccount)); + return dos.GetAccessRules(true, true, typeof(NTAccount)); } - - return dacl; } /// @@ -330,20 +327,17 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) PSTraceSource.NewArgumentException(nameof(instance)); } - AuthorizationRuleCollection sacl; CommonObjectSecurity cos = sd as CommonObjectSecurity; if (cos != null) { - sacl = cos.GetAuditRules(true, true, typeof(NTAccount)); + return cos.GetAuditRules(true, true, typeof(NTAccount)); } else { DirectoryObjectSecurity dos = sd as DirectoryObjectSecurity; Dbg.Diagnostics.Assert(dos != null, "Acl should be of type CommonObjectSecurity or DirectoryObjectSecurity"); - sacl = dos.GetAuditRules(true, true, typeof(NTAccount)); + return dos.GetAuditRules(true, true, typeof(NTAccount)); } - - return sacl; } /// @@ -360,8 +354,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) SessionState sessionState = new SessionState(); string path = sessionState.Path.GetUnresolvedProviderPathFromPSPath( GetPath(instance)); - IntPtr pOwner = IntPtr.Zero, pGroup = IntPtr.Zero; - IntPtr pDacl = IntPtr.Zero, pSacl = IntPtr.Zero, pSd = IntPtr.Zero; + IntPtr pSd = IntPtr.Zero; try { @@ -370,10 +363,10 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) path, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, - out pOwner, - out pGroup, - out pDacl, - out pSacl, + out IntPtr pOwner, + out IntPtr pGroup, + out IntPtr pDacl, + out IntPtr pSacl, out pSd); if (rs != NativeMethods.ERROR_SUCCESS) { @@ -385,8 +378,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) return null; } - NativeMethods.ACL sacl = new NativeMethods.ACL(); - sacl = Marshal.PtrToStructure(pSacl); + NativeMethods.ACL sacl = Marshal.PtrToStructure(pSacl); if (sacl.AceCount == 0) { return null; @@ -396,8 +388,7 @@ public static SecurityIdentifier GetCentralAccessPolicyId(PSObject instance) IntPtr pAce = pSacl + Marshal.SizeOf(new NativeMethods.ACL()); for (ushort aceIdx = 0; aceIdx < sacl.AceCount; aceIdx++) { - NativeMethods.ACE_HEADER ace = new NativeMethods.ACE_HEADER(); - ace = Marshal.PtrToStructure(pAce); + NativeMethods.ACE_HEADER ace = Marshal.PtrToStructure(pAce); Dbg.Diagnostics.Assert(ace.AceType == NativeMethods.SYSTEM_SCOPED_POLICY_ID_ACE_TYPE, "Unexpected ACE type: " + ace.AceType.ToString(CultureInfo.CurrentCulture)); @@ -458,12 +449,11 @@ public static string GetCentralAccessPolicyName(PSObject instance) Marshal.Copy(capIdArray, 0, pCapId, capIdSize); IntPtr[] ppCapId = new IntPtr[1]; ppCapId[0] = pCapId; - uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( ppCapId, 1, out caps, - out capCount); + out uint capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); @@ -475,8 +465,7 @@ public static string GetCentralAccessPolicyName(PSObject instance) } // Get the CAP name. - NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); - cap = Marshal.PtrToStructure(caps); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(caps); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. return Marshal.PtrToStringUni(cap.Name.Buffer, cap.Name.Length / 2); } @@ -508,12 +497,11 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) try { // Retrieve all CAPs. - uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, - out capCount); + out uint capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); @@ -528,14 +516,13 @@ public static string[] GetAllCentralAccessPolicies(PSObject instance) // Add CAP names and IDs to a string array. string[] policies = new string[capCount]; - NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { // Retrieve CAP name. Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); - cap = Marshal.PtrToStructure(capPtr); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. policies[capIdx] = "\"" + Marshal.PtrToStringUni( cap.Name.Buffer, @@ -653,7 +640,7 @@ public string[] Path } } - private PSObject _inputObject = null; + private PSObject _inputObject; /// /// InputObject Parameter @@ -695,7 +682,7 @@ public string[] LiteralPath } } - private bool _isLiteralPath = false; + private bool _isLiteralPath; /// /// Gets or sets the audit flag of the command. This flag @@ -758,7 +745,6 @@ public SwitchParameter AllCentralAccessPolicies /// protected override void ProcessRecord() { - Collection sd = null; AccessControlSections sections = AccessControlSections.Owner | AccessControlSections.Group | @@ -855,7 +841,7 @@ protected override void ProcessRecord() InvokeProvider.SecurityDescriptor.Get(rp, sections, context); - sd = context.GetAccumulatedObjects(); + Collection sd = context.GetAccumulatedObjects(); if (sd != null) { AddBrokeredProperties( @@ -921,7 +907,7 @@ public string[] Path } } - private PSObject _inputObject = null; + private PSObject _inputObject; /// /// InputObject Parameter @@ -962,7 +948,7 @@ public string[] LiteralPath } } - private bool _isLiteralPath = false; + private bool _isLiteralPath; private object _securityDescriptor; @@ -1125,12 +1111,11 @@ private IntPtr GetSaclWithCapId(string capStr) // be deallocated separately (but with the entire buffer // returned by LsaQueryCAPs). freeCapId = false; - uint capCount = 0; rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, - out capCount); + out uint capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); @@ -1144,13 +1129,12 @@ private IntPtr GetSaclWithCapId(string capStr) } // Find the supplied string among available CAP names, use the corresponding CAPID. - NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); - cap = Marshal.PtrToStructure(capPtr); + NativeMethods.CENTRAL_ACCESS_POLICY cap = Marshal.PtrToStructure(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. string capName = Marshal.PtrToStringUni( cap.Name.Buffer, @@ -1334,14 +1318,13 @@ protected override void ProcessRecord() if (methodInfo != null) { - CommonSecurityDescriptor aclCommonSD = _securityDescriptor as CommonSecurityDescriptor; string sddl; if (aclObjectSecurity != null) { sddl = aclObjectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All); } - else if (aclCommonSD != null) + else if (_securityDescriptor is CommonSecurityDescriptor aclCommonSD) { sddl = aclCommonSD.GetSddlForm(AccessControlSections.All); } @@ -1476,9 +1459,8 @@ protected override void ProcessRecord() context.PassThru = Passthru; if (_isLiteralPath) { - ProviderInfo Provider = null; - PSDriveInfo Drive = null; - string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath(p, out Provider, out Drive); + string pathStr = SessionState.Path.GetUnresolvedProviderPathFromPSPath( + p, out ProviderInfo Provider, out PSDriveInfo Drive); pathsToProcess.Add(new PathInfo(Drive, Provider, pathStr, SessionState)); context.SuppressWildcardExpansion = true; } From 16e2b62d78f63d07ab40d8e58977942387ee6ea6 Mon Sep 17 00:00:00 2001 From: "Joel Sallow (/u/ta11ow)" <32407840+vexx32@users.noreply.github.com> Date: Thu, 10 Dec 2020 15:12:34 -0500 Subject: [PATCH 118/138] Ensure -PipelineVariable is set for all output from script cmdlets (#12766) --- .../engine/MshCommandRuntime.cs | 11 ++++ .../ParameterBinding.Tests.ps1 | 56 +++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 39bc3b267d0..a1cd276fa89 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -3751,6 +3751,17 @@ internal void SetVariableListsInPipe() if (this.PipelineVariable != null) { + // _state can be null if the current script block is dynamicparam, etc. + if (_state != null) + { + // Create the pipeline variable + _state.PSVariable.Set(_pipelineVarReference); + + // Get the reference again in case we re-used one from the + // same scope. + _pipelineVarReference = _state.PSVariable.Get(this.PipelineVariable); + } + this.OutputPipe.SetPipelineVariable(_pipelineVarReference); } } diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 07d132012a0..a0fe5973c8e 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -256,6 +256,62 @@ Describe "Parameter Binding Tests" -Tags "CI" { DynamicParamTest -PipelineVariable bar | ForEach-Object { $bar } | Should -Be "hi" } + Context "PipelineVariable Behaviour" { + + BeforeAll { + function Write-PipelineVariable { + [CmdletBinding()] + [OutputType([int])] + param( + [Parameter(ValueFromPipeline)] + $a + ) + begin { 1 } + process { 2 } + end { 3 } + } + + $testScripts = @( + @{ + CmdletType = 'Script Cmdlet' + Script = { + 1..3 | + Write-PipelineVariable -PipelineVariable pipe | + Select-Object -Property @( + @{ Name = "PipelineVariableSet"; Expression = { $null -ne $pipe ? $true : $false } } + @{ Name = "PipelineVariable"; Expression = { $pipe } } + ) + } + } + @{ + CmdletType = 'Compiled Cmdlet' + Script = { + 1..3 | + Write-PipelineVariable | + ForEach-Object { $_ } -PipelineVariable pipe | + Select-Object -Property @( + @{ Name = "PipelineVariableSet"; Expression = { $null -ne $pipe ? $true : $false } } + @{ Name = "PipelineVariable"; Expression = { $pipe } } + ) + } + } + ) + } + + AfterAll { + Remove-Item -Path 'function:Write-PipelineVariable' + } + + It 'should set the pipeline variable every time for a ' -TestCases $testScripts { + param($Script, $CmdletType) + + $result = & $Script + $result.Count | Should -Be 5 + $result.PipelineVariableSet | Should -Not -Contain $false + $result.PipelineVariable | Should -Be 1, 2, 2, 2, 3 + } + } + Context "Use automatic variables as default value for parameters" { BeforeAll { ## Explicit use of 'CmdletBinding' make it a script cmdlet From 1223518a437ccc06c49357358150919db9b91eab Mon Sep 17 00:00:00 2001 From: "Joel Sallow (/u/ta11ow)" <32407840+vexx32@users.noreply.github.com> Date: Thu, 10 Dec 2020 15:34:17 -0500 Subject: [PATCH 119/138] (#12430) Improve detection of mutable value types (#12495) --- .../engine/hostifaces/History.cs | 98 +++---------------- .../engine/runtime/Binding/Binders.cs | 37 +++---- 2 files changed, 31 insertions(+), 104 deletions(-) diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index 160857a3a0a..e1100b97487 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -1433,6 +1433,7 @@ void ProcessRecord() { break; } + // Read CommandLine property if (!(GetPropertyValue(mshObject, "CommandLine") is string commandLine)) { @@ -1441,109 +1442,32 @@ void ProcessRecord() // Read ExecutionStatus property object pipelineState = GetPropertyValue(mshObject, "ExecutionStatus"); - if (pipelineState == null) - { - break; - } - - PipelineState executionStatus; - if (pipelineState is PipelineState) - { - executionStatus = (PipelineState)pipelineState; - } - else if (pipelineState is PSObject) - { - PSObject serializedPipelineState = pipelineState as PSObject; - object baseObject = serializedPipelineState.BaseObject; - if (baseObject is not int) - { - break; - } - - executionStatus = (PipelineState)baseObject; - if (executionStatus < PipelineState.NotStarted || executionStatus > PipelineState.Failed) - { - break; - } - } - else if (pipelineState is string) - { - try - { - executionStatus = (PipelineState)Enum.Parse(typeof(PipelineState), (string)pipelineState); - } - catch (ArgumentException) - { - break; - } - } - else + if (pipelineState == null || !LanguagePrimitives.TryConvertTo(pipelineState, out PipelineState executionStatus)) { break; } // Read StartExecutionTime property - DateTime startExecutionTime; object temp = GetPropertyValue(mshObject, "StartExecutionTime"); - if (temp == null) - { - break; - } - else if (temp is DateTime) - { - startExecutionTime = (DateTime)temp; - } - else if (temp is string) - { - try - { - startExecutionTime = DateTime.Parse((string)temp, System.Globalization.CultureInfo.CurrentCulture); - } - catch (FormatException) - { - break; - } - } - else + if (temp == null || !LanguagePrimitives.TryConvertTo(temp, out DateTime startExecutionTime)) { break; } // Read EndExecutionTime property - DateTime endExecutionTime; temp = GetPropertyValue(mshObject, "EndExecutionTime"); - if (temp == null) - { - break; - } - else if (temp is DateTime) - { - endExecutionTime = (DateTime)temp; - } - else if (temp is string) - { - try - { - endExecutionTime = DateTime.Parse((string)temp, System.Globalization.CultureInfo.CurrentCulture); - } - catch (FormatException) - { - break; - } - } - else + if (temp == null || !LanguagePrimitives.TryConvertTo(temp, out DateTime endExecutionTime)) { break; } - return new HistoryInfo - ( - 0, - commandLine, - executionStatus, - startExecutionTime, - endExecutionTime - ); + return new HistoryInfo( + pipelineId: 0, + commandLine, + executionStatus, + startExecutionTime, + endExecutionTime + ); } while (false); // If we are here, an error has occured. diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index b32e2e38733..83dc432ef55 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -2035,36 +2035,39 @@ private static object NullRule(CallSite site, object obj) internal static bool IsValueTypeMutable(Type type) { - if (type.IsPrimitive || type.IsEnum) + // First, check for enums/primitives and compiler-defined attributes. + if (type.IsPrimitive + || type.IsEnum + || type.IsDefined(typeof(System.Runtime.CompilerServices.IsReadOnlyAttribute), inherit: false)) { return false; } - // If there are any fields, the type is mutable. - if (type.GetFields(BindingFlags.Public | BindingFlags.Instance).Length > 0) + // If the builtin attribute is not present, check for a custom attribute from by the compiler. If the + // library targets netstandard2.0, the compiler can't be sure the attribute will be provided by the runtime, + // and defines its own attribute of the same name during compilation. To account for this, we must check the + // type by name, not by reference. + foreach (object attribute in type.GetCustomAttributes(inherit: false)) { - return true; + if (attribute.GetType().FullName.Equals( + "System.Runtime.CompilerServices.IsReadOnlyAttribute", + StringComparison.Ordinal)) + { + return false; + } } - // If there are any properties with setters, the type is mutable. - var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); - for (int index = 0; index < properties.Length; index++) + // Fallback: check all fields (public + private) to verify whether they're all readonly. + // If any field is not readonly, the value type is potentially mutable. + foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { - var property = properties[index]; - if (property.CanWrite) + if (!field.IsInitOnly) { return true; } } - // If there are any methods other than the property getters, the type might - // be mutable, so assume the type is mutable. - var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance); - if (methods.Length != properties.Length) - { - return true; - } - + // If all fields are init-only (read-only), then the value type is immutable. return false; } From 9d50a052ab16796e0ed5dcdcaebba52acc7c0260 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Thu, 10 Dec 2020 13:07:53 -0800 Subject: [PATCH 120/138] Fix syntax error in Windows packaging script (#14377) --- .../releaseBuild/azureDevOps/templates/windows-packaging.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index 9aa5cc80a09..0106977dff9 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -124,10 +124,10 @@ jobs: "$($fullSymbolsFolder)\System.Management.Automation.dll" = "" } - $itemsToExclude = @{ + $itemsToExclude = @( # This package is retrieved from https://www.github.com/powershell/MarkdownRender "$($fullSymbolsFolder)\Microsoft.PowerShell.MarkdownRender.dll" - } + ) if ("$env:Architecture" -notlike 'fxdependent*') { From 429125a8f39b490728f148c6ddbccc189907bbf9 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 06:43:23 +0100 Subject: [PATCH 121/138] Enable nullable: System.Management.Automation.Tracing.IEtwEventCorrelator (#14168) --- .../utils/tracing/EtwEventCorrelator.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index 28d4cfe13ee..a421b918eb8 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -12,6 +12,7 @@ namespace System.Management.Automation.Tracing /// An object that can be used to manage the ETW activity ID of the current thread. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Etw")] +#nullable enable public interface IEtwEventCorrelator { /// @@ -42,6 +43,7 @@ public interface IEtwEventCorrelator /// the new activity yields control of the current thread. IEtwActivityReverter StartActivity(); } +#nullable restore /// /// A simple implementation of . From 5533e0da296e704deddf7f81a185ef7dce2a48c3 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 06:46:36 +0100 Subject: [PATCH 122/138] Enable nullable: System.Management.Automation.IHasSessionStateEntryVisibility (#14169) --- src/System.Management.Automation/engine/SessionStatePublic.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index 8f010cb65d4..ce14d4948dc 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -336,6 +336,7 @@ public enum SessionStateEntryVisibility Private = 1 } +#nullable enable internal interface IHasSessionStateEntryVisibility { SessionStateEntryVisibility Visibility { get; set; } From 74d833c214830bae97a3536f9d23ccb77b6dd619 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 06:48:54 +0100 Subject: [PATCH 123/138] Enable nullable: System.Management.Automation.Interpreter.IInstructionProvider (#14173) --- .../engine/interpreter/Instruction.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/System.Management.Automation/engine/interpreter/Instruction.cs b/src/System.Management.Automation/engine/interpreter/Instruction.cs index 0a46fd88dfa..f1d8edaeb87 100644 --- a/src/System.Management.Automation/engine/interpreter/Instruction.cs +++ b/src/System.Management.Automation/engine/interpreter/Instruction.cs @@ -17,10 +17,12 @@ namespace System.Management.Automation.Interpreter { +#nullable enable internal interface IInstructionProvider { void AddInstructions(LightCompiler compiler); } +#nullable restore internal abstract class Instruction { From ab44bf4ae248823763e17f21011bee6d2ce761d3 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 06:53:25 +0100 Subject: [PATCH 124/138] Enable nullable: System.Management.Automation.IJobDebugger (#14174) --- .../engine/remoting/client/Job.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 7fcc78a1c75..b547d1f3ca9 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -379,12 +379,13 @@ internal JobIdentifier(int id, Guid instanceId) /// /// Interface to expose a job debugger. /// +#nullable enable public interface IJobDebugger { /// /// Job Debugger. /// - Debugger Debugger + Debugger? Debugger { get; } @@ -398,6 +399,7 @@ bool IsAsync set; } } +#nullable restore /// /// Represents a command running in background. A job object can internally From 9c75ba8b63aebd5e1ed641b0a0406992fc05ce4f Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 06:58:51 +0100 Subject: [PATCH 125/138] Enable nullable: System.Management.Automation.IOutputProcessingState (#14175) --- src/System.Management.Automation/engine/remoting/client/Job.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index b547d1f3ca9..8e876902c26 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -4520,9 +4520,10 @@ internal OutputProcessingStateEventArgs(bool processingOutput) } } +#nullable enable internal interface IOutputProcessingState { - event EventHandler OutputProcessingStateChanged; + event EventHandler? OutputProcessingStateChanged; } #endregion From e55f94013123a18952f2fd6cb3c73129e0888cf8 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:02:53 +0100 Subject: [PATCH 126/138] Enable nullable: System.Management.Automation.ICommandRuntime2 (#14183) --- src/System.Management.Automation/engine/ICommandRuntime.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/ICommandRuntime.cs b/src/System.Management.Automation/engine/ICommandRuntime.cs index cf5de2b20ab..6f0b3ce9d57 100644 --- a/src/System.Management.Automation/engine/ICommandRuntime.cs +++ b/src/System.Management.Automation/engine/ICommandRuntime.cs @@ -560,6 +560,7 @@ public interface ICommandRuntime /// execute an instance of a Cmdlet. ICommandRuntime2 extends the ICommandRuntime interface /// by adding support for the informational data stream. /// +#nullable enable public interface ICommandRuntime2 : ICommandRuntime { /// @@ -614,6 +615,6 @@ public interface ICommandRuntime2 : ICommandRuntime /// performed, and the Cmdlet should move on to the next target resource. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] - bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll); + bool ShouldContinue(string? query, string? caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll); } } From 25cfd2be9891dd159b635ce36b1a5bcc310e22da Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:04:57 +0100 Subject: [PATCH 127/138] Enable nullable: System.Management.Automation.Language.ISupportsAssignment (#14180) --- src/System.Management.Automation/engine/parser/ast.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index e99fd1001c6..156e0365b4a 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -29,11 +29,15 @@ namespace System.Management.Automation.Language using System.Runtime.CompilerServices; using System.Reflection.Emit; +#nullable enable + internal interface ISupportsAssignment { IAssignableValue GetAssignableValue(); } +#nullable restore + internal interface IAssignableValue { /// From 2784add414393b0ecab798055cfbac0d363c1c1e Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:09:35 +0100 Subject: [PATCH 128/138] Enable nullable: ...Automation.Remoting.Client.IWSManNativeApiFacade (#14186) --- .../engine/remoting/fanin/WSManNativeAPI.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 8bcf2c09f2c..6dd3614a62f 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -3015,6 +3015,7 @@ internal static extern void WSManPluginRegisterShutdownCallback( /// unit testing. /// Note: It is implemented as a class to avoid exposing it outside the module. /// +#nullable enable internal interface IWSManNativeApiFacade { // TODO: Expand this to cover the rest of the API once I prove that it works! @@ -3033,7 +3034,7 @@ int WSManPluginOperationComplete( int WSManPluginReceiveResult( IntPtr requestDetails, int flags, - string stream, + string? stream, IntPtr streamResult, string commandState, int exitCode); @@ -3048,6 +3049,7 @@ void WSManPluginRegisterShutdownCallback( IntPtr shutdownCallback, IntPtr shutdownContext); } +#nullable restore /// /// Concrete implementation of the PInvoke facade for use in the production code. From 55476817b4cc7e9535ecf3bfbabb651d4f095aa2 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:15:54 +0100 Subject: [PATCH 129/138] Enable nullable: System.Management.Automation.LanguagePrimitives.IConversionData (#14187) --- .../engine/LanguagePrimitives.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index d27940128e7..c397385e557 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -4349,19 +4349,21 @@ internal delegate T PSConverter(object valueToConvert, internal delegate object PSNullConverter(object nullOrAutomationNull); +#nullable enable internal interface IConversionData { object Converter { get; } ConversionRank Rank { get; } - object Invoke(object valueToConvert, + object? Invoke(object? valueToConvert, Type resultType, bool recurse, - PSObject originalValueToConvert, - IFormatProvider formatProvider, - TypeTable backupTable); + PSObject? originalValueToConvert, + IFormatProvider? formatProvider, + TypeTable? backupTable); } +#nullable restore [System.Diagnostics.DebuggerDisplay("{_converter.Method.Name}")] internal class ConversionData : IConversionData From 29131d573cf7402dcb931f0efcb3b04e69780eaf Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:22:52 +0100 Subject: [PATCH 130/138] Enable nullable: System.Management.Automation.Language.ICustomAstVisitor2 (#14192) --- .../engine/parser/AstVisitor.cs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index 45cdb438008..5c09ee78dc6 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -201,35 +201,37 @@ public interface ICustomAstVisitor } /// +#nullable enable public interface ICustomAstVisitor2 : ICustomAstVisitor { /// - object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst); + object? VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) => DefaultVisit(typeDefinitionAst); /// - object VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst); + object? VisitPropertyMember(PropertyMemberAst propertyMemberAst) => DefaultVisit(propertyMemberAst); /// - object VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst); + object? VisitFunctionMember(FunctionMemberAst functionMemberAst) => DefaultVisit(functionMemberAst); /// - object VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst); + object? VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) => DefaultVisit(baseCtorInvokeMemberExpressionAst); /// - object VisitUsingStatement(UsingStatementAst usingStatement) => DefaultVisit(usingStatement); + object? VisitUsingStatement(UsingStatementAst usingStatement) => DefaultVisit(usingStatement); /// - object VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) => DefaultVisit(configurationDefinitionAst); + object? VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) => DefaultVisit(configurationDefinitionAst); /// - object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) => DefaultVisit(dynamicKeywordAst); + object? VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) => DefaultVisit(dynamicKeywordAst); /// - object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst); + object? VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) => DefaultVisit(ternaryExpressionAst); /// - object VisitPipelineChain(PipelineChainAst statementChainAst) => DefaultVisit(statementChainAst); + object? VisitPipelineChain(PipelineChainAst statementChainAst) => DefaultVisit(statementChainAst); } +#nullable restore #if DEBUG internal class CheckAllParentsSet : AstVisitor2 From 76e471c0dd052ca979512f24d3413627e0c8dc99 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:35:00 +0100 Subject: [PATCH 131/138] Enable nullable: System.Management.Automation.Language.IScriptExtent (#14179) --- src/System.Management.Automation/engine/parser/Position.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 24ce0d118a2..5e967e432b6 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -51,12 +51,13 @@ public interface IScriptPosition /// /// Represents the a span of text in a script. /// +#nullable enable public interface IScriptExtent { /// /// The filename the extent includes, or null if the extent is not included in any file. /// - string File { get; } + string? File { get; } /// /// The starting position of the extent. @@ -103,6 +104,7 @@ public interface IScriptExtent /// int EndOffset { get; } } +#nullable restore /// /// A few utility functions for script positions. From 7944cf0873e566ad6423b1eb2527af6eab71734c Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:37:02 +0100 Subject: [PATCH 132/138] Enable nullable: System.Management.Automation.Provider.IDynamicPropertyProvider (#14167) --- .../namespaces/IDynamicPropertyProvider.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs index 6b8c69c270e..232f3f5d78b 100644 --- a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs +++ b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable namespace System.Management.Automation.Provider { #region IDynamicPropertyCmdletProvider - /// /// An interface that can be implemented on a Cmdlet provider to expose the dynamic /// manipulation of properties. @@ -61,7 +61,7 @@ void NewProperty( string path, string propertyName, string propertyTypeName, - object value); + object? value); /// /// Gives the provider an opportunity to attach additional parameters to the @@ -87,11 +87,11 @@ void NewProperty( /// /// The default implementation returns null. (no additional parameters) /// - object NewPropertyDynamicParameters( + object? NewPropertyDynamicParameters( string path, string propertyName, string propertyTypeName, - object value); + object? value); /// /// Removes a property on the item specified by the path. @@ -196,7 +196,7 @@ void RenameProperty( /// /// The default implementation returns null. (no additional parameters) /// - object RenamePropertyDynamicParameters( + object? RenamePropertyDynamicParameters( string path, string sourceProperty, string destinationProperty); @@ -262,7 +262,7 @@ void CopyProperty( /// /// The default implementation returns null. (no additional parameters) /// - object CopyPropertyDynamicParameters( + object? CopyPropertyDynamicParameters( string sourcePath, string sourceProperty, string destinationPath, @@ -328,7 +328,7 @@ void MoveProperty( /// /// The default implementation returns null. (no additional parameters) /// - object MovePropertyDynamicParameters( + object? MovePropertyDynamicParameters( string sourcePath, string sourceProperty, string destinationPath, From c4cc62658a486bd6a073a2cdc8c50309004c2b59 Mon Sep 17 00:00:00 2001 From: Staffan Gustafsson Date: Fri, 11 Dec 2020 07:45:11 +0100 Subject: [PATCH 133/138] Enable nullable: System.Management.Automation.Interpreter.IBoxableInstruction (#14165) --- .../engine/interpreter/LocalAccess.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs index 7b0711b1930..30596866c0c 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalAccess.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalAccess.cs @@ -23,10 +23,13 @@ namespace System.Management.Automation.Interpreter { + +#nullable enable internal interface IBoxableInstruction { - Instruction BoxIfIndexMatches(int index); + Instruction? BoxIfIndexMatches(int index); } +#nullable restore internal abstract class LocalAccessInstruction : Instruction { From a106d1d4b6521298804c8620c8bbcfdb392b3341 Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Fri, 11 Dec 2020 09:34:37 -0800 Subject: [PATCH 134/138] Add 'Microsoft.PowerShell.MarkdownRender' to the package reference list (#14386) --- .../Microsoft.PowerShell.Commands.Utility.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index 8890d53951a..d6aa032de2b 100644 --- a/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -15,5 +15,6 @@ + From a99ea2acd2ac4b979974719d514d6c421fdcbdee Mon Sep 17 00:00:00 2001 From: Steve Lee Date: Fri, 11 Dec 2020 10:33:57 -0800 Subject: [PATCH 135/138] Enable ANSI formatting via `$PSStyle` and support suppressing ANSI output (#13758) --- .../host/msh/ConsoleHostUserInterface.cs | 60 ++- .../PowerShellCore_format_ps1xml.cs | 144 ++++++- .../FormatAndOutput/common/ILineOutput.cs | 4 + .../FormatAndOutput/common/PSStyle.cs | 404 ++++++++++++++++++ .../FormatAndOutput/common/StringDecorated.cs | 175 ++++++++ .../out-console/ConsoleLineOutput.cs | 2 + .../ExperimentalFeature.cs | 3 + .../engine/InitialSessionState.cs | 7 + .../engine/SpecialVariables.cs | 4 + .../engine/Utils.cs | 102 +++++ .../engine/hostifaces/MshHostUserInterface.cs | 10 + .../resources/RunspaceInit.resx | 3 + .../Formatting/OutputRendering.Tests.ps1 | 85 ++++ .../engine/Formatting/PSStyle.Tests.ps1 | 114 +++++ 14 files changed, 1102 insertions(+), 15 deletions(-) create mode 100644 src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs create mode 100644 src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs create mode 100644 test/powershell/engine/Formatting/OutputRendering.Tests.ps1 create mode 100644 test/powershell/engine/Formatting/PSStyle.Tests.ps1 diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 5c319347a8b..7485306c14e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -696,6 +696,7 @@ private void WriteImpl(string value, bool newLine) } TextWriter writer = Console.IsOutputRedirected ? Console.Out : _parent.ConsoleTextWriter; + value = Utils.GetOutputString(value, isHost: true, SupportsVirtualTerminal, Console.IsOutputRedirected); if (_parent.IsRunningAsync) { @@ -1179,11 +1180,17 @@ public override void WriteDebugLine(string message) } else { - // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here... - WriteLine( - DebugForegroundColor, - DebugBackgroundColor, - StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message)); + if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Debug) + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message)); + } + else + { + WriteLine( + DebugForegroundColor, + DebugBackgroundColor, + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message)); + } } } @@ -1234,10 +1241,17 @@ public override void WriteVerboseLine(string message) } else { - WriteLine( - VerboseForegroundColor, - VerboseBackgroundColor, - StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message)); + if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Verbose) + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message)); + } + else + { + WriteLine( + VerboseForegroundColor, + VerboseBackgroundColor, + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message)); + } } } @@ -1271,10 +1285,17 @@ public override void WriteWarningLine(string message) } else { - WriteLine( - WarningForegroundColor, - WarningBackgroundColor, - StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message)); + if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Warning) + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message)); + } + else + { + WriteLine( + WarningForegroundColor, + WarningBackgroundColor, + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message)); + } } } @@ -1334,9 +1355,20 @@ public override void WriteErrorLine(string value) else { if (writer == _parent.ConsoleTextWriter) - WriteLine(ErrorForegroundColor, ErrorBackgroundColor, value); + { + if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + WriteLine(value); + } + else + { + WriteLine(ErrorForegroundColor, ErrorBackgroundColor, value); + } + } else + { Console.Error.WriteLine(value); + } } } diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index 0400d3488b5..dbb8d3a2085 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -263,6 +263,22 @@ internal static IEnumerable GetFormatData() yield return new ExtendedTypeDefinition( "Microsoft.PowerShell.Commands.ByteCollection", ViewsOf_Microsoft_PowerShell_Commands_ByteCollection()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle", + ViewsOf_System_Management_Automation_PSStyle()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+FormattingData", + ViewsOf_System_Management_Automation_PSStyleFormattingData()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+ForegroundColor", + ViewsOf_System_Management_Automation_PSStyleForegroundColor()); + + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+BackgroundColor", + ViewsOf_System_Management_Automation_PSStyleBackgroundColor()); } private static IEnumerable ViewsOf_System_RuntimeType() @@ -1317,7 +1333,7 @@ function Get-ConciseViewPositionMessage { $err.CategoryInfo.GetMessage() } elseif (! $err.ErrorDetails -or ! $err.ErrorDetails.Message) { - $err.Exception.Message + $posmsg + $newline + $err.Exception.Message + $posmsg } else { $err.ErrorDetails.Message + $posmsg } @@ -2004,5 +2020,131 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co .GroupByProperty("Label") .EndTable()); } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyle() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Reset)$($_.Reset.Replace(""""`e"""",'`e'))""", label: "Reset") + .AddItemScriptBlock(@"""$($_.BlinkOff)$($_.BlinkOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "BlinkOff") + .AddItemScriptBlock(@"""$($_.Blink)$($_.Blink.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Blink") + .AddItemScriptBlock(@"""$($_.BoldOff)$($_.BoldOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "BoldOff") + .AddItemScriptBlock(@"""$($_.Bold)$($_.Bold.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Bold") + .AddItemScriptBlock(@"""$($_.Hidden)$($_.Hidden.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Hidden") + .AddItemScriptBlock(@"""$($_.HiddenOff)$($_.HiddenOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "HiddenOff") + .AddItemScriptBlock(@"""$($_.Reverse)$($_.Reverse.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Reverse") + .AddItemScriptBlock(@"""$($_.ReverseOff)$($_.ReverseOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "ReverseOff") + .AddItemScriptBlock(@"""$($_.ItalicOff)$($_.ItalicOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "ItalicOff") + .AddItemScriptBlock(@"""$($_.Italic)$($_.Italic.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Italic") + .AddItemScriptBlock(@"""$($_.UnderlineOff)$($_.UnderlineOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "UnderlineOff") + .AddItemScriptBlock(@"""$($_.Underline)$($_.Underline.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Underline") + .AddItemProperty(@"OutputRendering") + .AddItemScriptBlock(@"""$($_.Formatting.FormatAccent)$($_.Formatting.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FormatAccent") + .AddItemScriptBlock(@"""$($_.Formatting.ErrorAccent)$($_.Formatting.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.ErrorAccent") + .AddItemScriptBlock(@"""$($_.Formatting.Error)$($_.Formatting.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Error") + .AddItemScriptBlock(@"""$($_.Formatting.Warning)$($_.Formatting.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Warning") + .AddItemScriptBlock(@"""$($_.Formatting.Verbose)$($_.Formatting.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") + .AddItemScriptBlock(@"""$($_.Formatting.Debug)$($_.Formatting.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Debug") + .AddItemScriptBlock(@"""$($_.Foreground.Black)$($_.Foreground.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Black") + .AddItemScriptBlock(@"""$($_.Foreground.White)$($_.Foreground.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.White") + .AddItemScriptBlock(@"""$($_.Foreground.DarkGray)$($_.Foreground.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.DarkGray") + .AddItemScriptBlock(@"""$($_.Foreground.LightGray)$($_.Foreground.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightGray") + .AddItemScriptBlock(@"""$($_.Foreground.Red)$($_.Foreground.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Red") + .AddItemScriptBlock(@"""$($_.Foreground.LightRed)$($_.Foreground.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightRed") + .AddItemScriptBlock(@"""$($_.Foreground.Magenta)$($_.Foreground.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Magenta") + .AddItemScriptBlock(@"""$($_.Foreground.LightMagenta)$($_.Foreground.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightMagenta") + .AddItemScriptBlock(@"""$($_.Foreground.Blue)$($_.Foreground.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Blue") + .AddItemScriptBlock(@"""$($_.Foreground.LightBlue)$($_.Foreground.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightBlue") + .AddItemScriptBlock(@"""$($_.Foreground.Cyan)$($_.Foreground.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Cyan") + .AddItemScriptBlock(@"""$($_.Foreground.LightCyan)$($_.Foreground.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightCyan") + .AddItemScriptBlock(@"""$($_.Foreground.Green)$($_.Foreground.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Green") + .AddItemScriptBlock(@"""$($_.Foreground.LightGreen)$($_.Foreground.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightGreen") + .AddItemScriptBlock(@"""$($_.Foreground.Yellow)$($_.Foreground.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Yellow") + .AddItemScriptBlock(@"""$($_.Foreground.LightYellow)$($_.Foreground.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightYellow") + .AddItemScriptBlock(@"""$($_.Background.Black)$($_.Background.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Black") + .AddItemScriptBlock(@"""$($_.Background.White)$($_.Background.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.White") + .AddItemScriptBlock(@"""$($_.Background.DarkGray)$($_.Background.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.DarkGray") + .AddItemScriptBlock(@"""$($_.Background.LightGray)$($_.Background.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightGray") + .AddItemScriptBlock(@"""$($_.Background.Red)$($_.Background.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Red") + .AddItemScriptBlock(@"""$($_.Background.LightRed)$($_.Background.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightRed") + .AddItemScriptBlock(@"""$($_.Background.Magenta)$($_.Background.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Magenta") + .AddItemScriptBlock(@"""$($_.Background.LightMagenta)$($_.Background.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightMagenta") + .AddItemScriptBlock(@"""$($_.Background.Blue)$($_.Background.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Blue") + .AddItemScriptBlock(@"""$($_.Background.LightBlue)$($_.Background.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightBlue") + .AddItemScriptBlock(@"""$($_.Background.Cyan)$($_.Background.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Cyan") + .AddItemScriptBlock(@"""$($_.Background.LightCyan)$($_.Background.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightCyan") + .AddItemScriptBlock(@"""$($_.Background.Green)$($_.Background.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Green") + .AddItemScriptBlock(@"""$($_.Background.LightGreen)$($_.Background.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightGreen") + .AddItemScriptBlock(@"""$($_.Background.Yellow)$($_.Background.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Yellow") + .AddItemScriptBlock(@"""$($_.Background.LightYellow)$($_.Background.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightYellow") + .EndEntry() + .EndList()); + } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleFormattingData() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+FormattingData", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.FormatAccent)$($_.FormatAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FormatAccent") + .AddItemScriptBlock(@"""$($_.ErrorAccent)$($_.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "ErrorAccent") + .AddItemScriptBlock(@"""$($_.Error)$($_.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Error") + .AddItemScriptBlock(@"""$($_.Warning)$($_.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Warning") + .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") + .AddItemScriptBlock(@"""$($_.Debug)$($_.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Debug") + .EndEntry() + .EndList()); + } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleForegroundColor() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+ForegroundColor", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Black)$($_.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Black") + .AddItemScriptBlock(@"""$($_.White)$($_.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "White") + .AddItemScriptBlock(@"""$($_.DarkGray)$($_.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "DarkGray") + .AddItemScriptBlock(@"""$($_.LightGray)$($_.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGray") + .AddItemScriptBlock(@"""$($_.Red)$($_.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Red") + .AddItemScriptBlock(@"""$($_.LightRed)$($_.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightRed") + .AddItemScriptBlock(@"""$($_.Magenta)$($_.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Magenta") + .AddItemScriptBlock(@"""$($_.LightMagenta)$($_.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightMagenta") + .AddItemScriptBlock(@"""$($_.Blue)$($_.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Blue") + .AddItemScriptBlock(@"""$($_.LightBlue)$($_.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightBlue") + .AddItemScriptBlock(@"""$($_.Cyan)$($_.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Cyan") + .AddItemScriptBlock(@"""$($_.LightCyan)$($_.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightCyan") + .AddItemScriptBlock(@"""$($_.Green)$($_.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Green") + .AddItemScriptBlock(@"""$($_.LightGreen)$($_.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGreen") + .AddItemScriptBlock(@"""$($_.Yellow)$($_.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Yellow") + .AddItemScriptBlock(@"""$($_.LightYellow)$($_.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightYellow") + .EndEntry() + .EndList()); + } + + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleBackgroundColor() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+ForegroundColor", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Black)$($_.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Black") + .AddItemScriptBlock(@"""$($_.White)$($_.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "White") + .AddItemScriptBlock(@"""$($_.DarkGray)$($_.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "DarkGray") + .AddItemScriptBlock(@"""$($_.LightGray)$($_.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGray") + .AddItemScriptBlock(@"""$($_.Red)$($_.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Red") + .AddItemScriptBlock(@"""$($_.LightRed)$($_.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightRed") + .AddItemScriptBlock(@"""$($_.Magenta)$($_.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Magenta") + .AddItemScriptBlock(@"""$($_.LightMagenta)$($_.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightMagenta") + .AddItemScriptBlock(@"""$($_.Blue)$($_.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Blue") + .AddItemScriptBlock(@"""$($_.LightBlue)$($_.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightBlue") + .AddItemScriptBlock(@"""$($_.Cyan)$($_.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Cyan") + .AddItemScriptBlock(@"""$($_.LightCyan)$($_.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightCyan") + .AddItemScriptBlock(@"""$($_.Green)$($_.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Green") + .AddItemScriptBlock(@"""$($_.LightGreen)$($_.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGreen") + .AddItemScriptBlock(@"""$($_.Yellow)$($_.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Yellow") + .AddItemScriptBlock(@"""$($_.LightYellow)$($_.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightYellow") + .EndEntry() + .EndList()); + } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 83e39c4dd5d..32d4565da5d 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.IO; using System.Management.Automation; +using System.Management.Automation.Internal; using System.Text; // interfaces for host interaction @@ -411,6 +412,9 @@ internal override int RowNumber internal override void WriteLine(string s) { CheckStopProcessing(); + + s = Utils.GetOutputString(s, isHost: false); + if (_suppressNewline) { _writer.Write(s); diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs new file mode 100644 index 00000000000..f27a5b89da9 --- /dev/null +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -0,0 +1,404 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace System.Management.Automation +{ + #region OutputRendering + /// + /// Defines the options for output rendering. + /// + public enum OutputRendering + { + /// Automatic by PowerShell. + Automatic = 0, + + /// Render as plaintext. + PlainText = 1, + + /// Render as ANSI. + Ansi = 2, + + /// Render ANSI only to host. + Host = 3, + } + #endregion OutputRendering + + #region PSStyle + /// + /// Contains configuration for how PowerShell renders text. + /// + public class PSStyle + { + /// + /// Contains foreground colors. + /// + public class ForegroundColor + { + /// + /// Gets the color black. + /// + public string Black { get; } = "\x1b[30m"; + + /// + /// Gets the color blue. + /// + public string Blue { get; } = "\x1b[34m"; + + /// + /// Gets the color cyan. + /// + public string Cyan { get; } = "\x1b[36m"; + + /// + /// Gets the color dark gray. + /// + public string DarkGray { get; } = "\x1b[90m"; + + /// + /// Gets the color green. + /// + public string Green { get; } = "\x1b[32m"; + + /// + /// Gets the color light blue. + /// + public string LightBlue { get; } = "\x1b[94m"; + + /// + /// Gets the color light cyan. + /// + public string LightCyan { get; } = "\x1b[96m"; + + /// + /// Gets the color light gray. + /// + public string LightGray { get; } = "\x1b[97m"; + + /// + /// Gets the color light green. + /// + public string LightGreen { get; } = "\x1b[92m"; + + /// + /// Gets the color light magenta. + /// + public string LightMagenta { get; } = "\x1b[95m"; + + /// + /// Gets the color light red. + /// + public string LightRed { get; } = "\x1b[91m"; + + /// + /// Gets the color light yellow. + /// + public string LightYellow { get; } = "\x1b[93m"; + + /// + /// Gets the color magenta. + /// + public string Magenta { get; } = "\x1b[35m"; + + /// + /// Gets the color read. + /// + public string Red { get; } = "\x1b[31m"; + + /// + /// Gets the color white. + /// + public string White { get; } = "\x1b[37m"; + + /// + /// Gets the color yellow. + /// + public string Yellow { get; } = "\x1b[33m"; + + /// + /// Set as RGB (Red, Green, Blue). + /// + /// Byte value representing red. + /// Byte value representing green. + /// Byte value representing blue. + /// String representing ANSI code for RGB value. + public string FromRgb(byte red, byte green, byte blue) + { + return $"\x1b[38;2;{red};{green};{blue}m"; + } + + /// + /// The color set as RGB as a single number. + /// + /// RGB value specified as an integer. + /// String representing ANSI code for RGB value. + public string FromRgb(int rgb) + { + byte red, green, blue; + blue = (byte)(rgb & 0xFF); + rgb >>= 8; + green = (byte)(rgb & 0xFF); + rgb >>= 8; + red = (byte)(rgb & 0xFF); + + return FromRgb(red, green, blue); + } + } + + /// + /// Contains background colors. + /// + public class BackgroundColor + { + /// + /// Gets the color black. + /// + public string Black { get; } = "\x1b[40m"; + + /// + /// Gets the color blue. + /// + public string Blue { get; } = "\x1b[44m"; + + /// + /// Gets the color cyan. + /// + public string Cyan { get; } = "\x1b[46m"; + + /// + /// Gets the color dark gray. + /// + public string DarkGray { get; } = "\x1b[100m"; + + /// + /// Gets the color green. + /// + public string Green { get; } = "\x1b[42m"; + + /// + /// Gets the color light blue. + /// + public string LightBlue { get; } = "\x1b[104m"; + + /// + /// Gets the color light cyan. + /// + public string LightCyan { get; } = "\x1b[106m"; + + /// + /// Gets the color light gray. + /// + public string LightGray { get; } = "\x1b[107m"; + + /// + /// Gets the color light green. + /// + public string LightGreen { get; } = "\x1b[102m"; + + /// + /// Gets the color light magenta. + /// + public string LightMagenta { get; } = "\x1b[105m"; + + /// + /// Gets the color light red. + /// + public string LightRed { get; } = "\x1b[101m"; + + /// + /// Gets the color light yellow. + /// + public string LightYellow { get; } = "\x1b[103m"; + + /// + /// Gets the color magenta. + /// + public string Magenta { get; } = "\x1b[45m"; + + /// + /// Gets the color read. + /// + public string Red { get; } = "\x1b[41m"; + + /// + /// Gets the color white. + /// + public string White { get; } = "\x1b[47m"; + + /// + /// Gets the color yellow. + /// + public string Yellow { get; } = "\x1b[43m"; + + /// + /// The color set as RGB (Red, Green, Blue). + /// + /// Byte value representing red. + /// Byte value representing green. + /// Byte value representing blue. + /// String representing ANSI code for RGB value. + public string FromRgb(byte red, byte green, byte blue) + { + return $"\x1b[48;2;{red};{green};{blue}m"; + } + + /// + /// The color set as RGB as a single number. + /// + /// RGB value specified as an integer. + /// String representing ANSI code for RGB value. + public string FromRgb(int rgb) + { + byte red, green, blue; + blue = (byte)(rgb & 0xFF); + rgb >>= 8; + green = (byte)(rgb & 0xFF); + rgb >>= 8; + red = (byte)(rgb & 0xFF); + + return FromRgb(red, green, blue); + } + } + + /// + /// Contains formatting styles for steams and objects. + /// + public class FormattingData + { + /// + /// Gets or sets the accent style for formatting. + /// + public string FormatAccent { get; set; } = "\x1b[32;1m"; + + /// + /// Gets or sets the accent style for errors. + /// + public string ErrorAccent { get; set; } = "\x1b[36;1m"; + + /// + /// Gets or sets the style for error messages. + /// + public string Error { get; set; } = "\x1b[31;1m"; + + /// + /// Gets or sets the style for warning messages. + /// + public string Warning { get; set; } = "\x1b[33;1m"; + + /// + /// Gets or sets the style for verbose messages. + /// + public string Verbose { get; set; } = "\x1b[33;1m"; + + /// + /// Gets or sets the style for debug messages. + /// + public string Debug { get; set; } = "\x1b[33;1m"; + } + + /// + /// Gets or sets the rendering mode for output. + /// + public OutputRendering OutputRendering { get; set; } = OutputRendering.Automatic; + + /// + /// Gets value to turn off all attributes. + /// + public string Reset { get; } = "\x1b[0m"; + + /// + /// Gets value to turn off blink. + /// + public string BlinkOff { get; } = "\x1b[5m"; + + /// + /// Gets value to turn on blink. + /// + public string Blink { get; } = "\x1b[25m"; + + /// + /// Gets value to turn off bold. + /// + public string BoldOff { get; } = "\x1b[22m"; + + /// + /// Gets value to turn on blink. + /// + public string Bold { get; } = "\x1b[1m"; + + /// + /// Gets value to turn on hidden. + /// + public string Hidden { get; } = "\x1b[8m"; + + /// + /// Gets value to turn off hidden. + /// + public string HiddenOff { get; } = "\x1b[28m"; + + /// + /// Gets value to turn on reverse. + /// + public string Reverse { get; } = "\x1b[7m"; + + /// + /// Gets value to turn off reverse. + /// + public string ReverseOff { get; } = "\x1b[27m"; + + /// + /// Gets value to turn off standout. + /// + public string ItalicOff { get; } = "\x1b[23m"; + + /// + /// Gets value to turn on standout. + /// + public string Italic { get; } = "\x1b[3m"; + + /// + /// Gets value to turn off underlined. + /// + public string UnderlineOff { get; } = "\x1b[24m"; + + /// + /// Gets value to turn on underlined. + /// + public string Underline { get; } = "\x1b[4m"; + + /// + /// Gets the formatting rendering settings. + /// + public FormattingData Formatting { get; } + + /// + /// Gets foreground colors. + /// + public ForegroundColor Foreground { get; } + + /// + /// Gets background colors. + /// + public BackgroundColor Background { get; } + + private static readonly PSStyle s_psstyle = new PSStyle(); + + private PSStyle() + { + Formatting = new FormattingData(); + Foreground = new ForegroundColor(); + Background = new BackgroundColor(); + } + + /// + /// Gets singleton instance. + /// + public static PSStyle Instance + { + get + { + return s_psstyle; + } + } + } + #endregion PSStyle +} diff --git a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs new file mode 100644 index 00000000000..3c1041f9c47 --- /dev/null +++ b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Text.RegularExpressions; + +namespace System.Management.Automation.Internal +{ + /// + /// Extensions to String type to calculate and render decorated content. + /// + public class StringDecorated + { + private readonly bool _isDecorated; + private readonly string _text; + private string? _plaintextcontent; + + private string PlainText + { + get + { + if (_plaintextcontent == null) + { + _plaintextcontent = ValueStringDecorated.AnsiRegex.Replace(_text, string.Empty); + } + + return _plaintextcontent; + } + } + + /// + /// Initializes a new instance of the class. + /// + /// The input string. + public StringDecorated(string text) + { + _text = text; + _isDecorated = text.Contains(ValueStringDecorated.ESC); + } + + /// + /// Gets a value indicating whether the string contains decoration. + /// + /// Boolean if the string contains decoration. + public bool IsDecorated => _isDecorated; + + /// + /// Gets the length of content sans escape sequences. + /// + /// Length of content sans escape sequences. + public int ContentLength => PlainText.Length; + + /// + /// Render the decorarted string using automatic output rendering. + /// + /// Rendered string based on automatic output rendering. + public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + + /// + /// Return string representation of content depending on output rendering mode. + /// + /// Specify how to render the text content. + /// Rendered string based on outputRendering. + public string ToString(OutputRendering outputRendering) + { + if (!_isDecorated) + { + return _text; + } + + if (outputRendering == OutputRendering.Automatic) + { + outputRendering = OutputRendering.Ansi; + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + outputRendering = OutputRendering.PlainText; + } + } + + if (outputRendering == OutputRendering.PlainText) + { + return PlainText; + } + else + { + return _text; + } + } + } + + internal struct ValueStringDecorated + { + internal const char ESC = '\x1b'; + private readonly bool _isDecorated; + private readonly string _text; + private string? _plaintextcontent; + + private string PlainText + { + get + { + if (_plaintextcontent == null) + { + _plaintextcontent = AnsiRegex.Replace(_text, string.Empty); + } + + return _plaintextcontent; + } + } + + // replace regex with .NET 6 API once available + internal static readonly Regex AnsiRegex = new Regex(@"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", RegexOptions.Compiled); + + /// + /// Initializes a new instance of the struct. + /// + /// The input string. + public ValueStringDecorated(string text) + { + _text = text; + _isDecorated = text.Contains(ESC); + _plaintextcontent = null; + } + + /// + /// Gets a value indicating whether the string contains decoration. + /// + /// Boolean if the string contains decoration. + public bool IsDecorated => _isDecorated; + + /// + /// Gets the length of content sans escape sequences. + /// + /// Length of content sans escape sequences. + public int ContentLength => PlainText.Length; + + /// + /// Render the decorarted string using automatic output rendering. + /// + /// Rendered string based on automatic output rendering. + public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + + /// + /// Return string representation of content depending on output rendering mode. + /// + /// Specify how to render the text content. + /// Rendered string based on outputRendering. + public string ToString(OutputRendering outputRendering) + { + if (!_isDecorated) + { + return _text; + } + + if (outputRendering == OutputRendering.Automatic) + { + outputRendering = OutputRendering.Ansi; + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + outputRendering = OutputRendering.PlainText; + } + } + + if (outputRendering == OutputRendering.PlainText) + { + return PlainText; + } + else + { + return _text; + } + } + } +} diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index decceac5108..4750b099b01 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -222,6 +222,7 @@ internal override int RowNumber internal override void WriteLine(string s) { CheckStopProcessing(); + // delegate the action to the helper, // that will properly break the string into // screen lines @@ -351,6 +352,7 @@ private void OnWrite(string s) #if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); #endif + switch (this.WriteStream) { case WriteStreamType.Error: diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 86ff0666e2c..f1be0c5acc8 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -126,6 +126,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSSubsystemPluginModel", description: "A plugin model for registering and un-registering PowerShell subsystems"), + new ExperimentalFeature( + name: "PSAnsiRendering", + description: "Enable $PSStyle variable to control ANSI rendering of strings"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 74fb6f87037..2495a4ac0fe 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -4442,6 +4442,13 @@ .ForwardHelpCategory Cmdlet new SessionStateVariableEntry(SpecialVariables.FirstToken, null, string.Empty), new SessionStateVariableEntry(SpecialVariables.StackTrace, null, string.Empty), + // Variable which controls the output rendering + new SessionStateVariableEntry( + SpecialVariables.PSStyle, + PSStyle.Instance, + RunspaceInit.PSStyleDescription, + ScopedItemOptions.None), + // Variable which controls the encoding for piping data to a NativeCommand new SessionStateVariableEntry( SpecialVariables.OutputEncoding, diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index aa241b6c942..ba757722e91 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -32,6 +32,10 @@ internal static class SpecialVariables internal static readonly VariablePath OFSVarPath = new VariablePath(OFS); + internal const string PSStyle = "PSStyle"; + + internal static readonly VariablePath PSStyleVarPath = new VariablePath(PSStyle); + internal const string OutputEncoding = "OutputEncoding"; internal static readonly VariablePath OutputEncodingVarPath = new VariablePath(OutputEncoding); diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index dd464ab4e76..6a4a863d23c 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1787,6 +1787,107 @@ private static bool TryGetCommandInfoList(PowerShell ps, HashSet command return true; } + internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTerminal) + { + var outputRendering = OutputRendering.Ansi; + + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + if (supportsVirtualTerminal != false) + { + switch (PSStyle.Instance.OutputRendering) + { + case OutputRendering.Automatic: + outputRendering = OutputRendering.Ansi; + break; + case OutputRendering.Host: + outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; + break; + default: + outputRendering = PSStyle.Instance.OutputRendering; + break; + } + } + } + + return outputRendering == OutputRendering.PlainText; + } + + internal static string GetOutputString(string s, bool isHost, bool? supportsVirtualTerminal = null, bool isOutputRedirected = false) + { + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + var sd = new ValueStringDecorated(s); + + if (sd.IsDecorated) + { + var outputRendering = OutputRendering.Ansi; + if (InternalTestHooks.BypassOutputRedirectionCheck) + { + isOutputRedirected = false; + } + + if (isOutputRedirected || ShouldOutputPlainText(isHost, supportsVirtualTerminal)) + { + outputRendering = OutputRendering.PlainText; + } + + s = sd.ToString(outputRendering); + } + } + + return s; + } + + internal enum FormatStyle + { + Reset, + FormatAccent, + ErrorAccent, + Error, + Warning, + Verbose, + Debug, + } + + internal static string GetFormatStyleString(FormatStyle formatStyle) + { + // redirected console gets plaintext output to preserve existing behavior + if (!InternalTestHooks.BypassOutputRedirectionCheck && + ((PSStyle.Instance.OutputRendering == OutputRendering.PlainText) || + (formatStyle == FormatStyle.Error && Console.IsErrorRedirected) || + (formatStyle != FormatStyle.Error && Console.IsOutputRedirected))) + { + return string.Empty; + } + + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + PSStyle psstyle = PSStyle.Instance; + switch (formatStyle) + { + case FormatStyle.Reset: + return psstyle.Reset; + case FormatStyle.FormatAccent: + return psstyle.Formatting.FormatAccent; + case FormatStyle.ErrorAccent: + return psstyle.Formatting.ErrorAccent; + case FormatStyle.Error: + return psstyle.Formatting.Error; + case FormatStyle.Warning: + return psstyle.Formatting.Warning; + case FormatStyle.Verbose: + return psstyle.Formatting.Verbose; + case FormatStyle.Debug: + return psstyle.Formatting.Debug; + default: + return string.Empty; + } + } + + return string.Empty; + } + #endregion } @@ -1970,6 +2071,7 @@ public static class InternalTestHooks internal static bool BypassAppLockerPolicyCaching; internal static bool BypassOnlineHelpRetrieval; internal static bool ForcePromptForChoiceDefaultOption; + internal static bool BypassOutputRedirectionCheck; // Stop/Restart/Rename Computer tests internal static bool TestStopComputer; diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 4996ed2493a..1e3da98da26 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -619,6 +619,16 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) } resultText = resultText.TrimEnd(); + + if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + { + var text = new ValueStringDecorated(resultText); + if (text.IsDecorated) + { + resultText = text.ToString(OutputRendering.PlainText); + } + } + foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) { if (transcript != null) diff --git a/src/System.Management.Automation/resources/RunspaceInit.resx b/src/System.Management.Automation/resources/RunspaceInit.resx index c4a485121c7..ac900465d7d 100644 --- a/src/System.Management.Automation/resources/RunspaceInit.resx +++ b/src/System.Management.Automation/resources/RunspaceInit.resx @@ -153,6 +153,9 @@ The text encoding used when piping text to a native executable file + + Configuration controlling how text is rendered. + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. diff --git a/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 new file mode 100644 index 00000000000..27dea30689e --- /dev/null +++ b/test/powershell/engine/Formatting/OutputRendering.Tests.ps1 @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'OutputRendering tests' { + BeforeAll { + $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) + $th = New-TestHost + $rs = [runspacefactory]::Createrunspace($th) + $rs.open() + $ps = [powershell]::Create() + $ps.Runspace = $rs + } + + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') + } + + BeforeEach { + if ($null -ne $PSStyle) { + $oldOutputRendering = $PSStyle.OutputRendering + } + } + + AfterEach { + if ($null -ne $PSStyle) { + $PSStyle.OutputRendering = $oldOutputRendering + } + + $ps.Commands.Clear() + } + + It 'OutputRendering works for "" to the host' -TestCases @( + @{ outputRendering = 'automatic'; ansi = $true } + @{ outputRendering = 'host' ; ansi = $true } + @{ outputRendering = 'ansi' ; ansi = $true } + @{ outputRendering = 'plaintext'; ansi = $false } + ) { + param($outputRendering, $ansi) + + $out = pwsh -noprofile -command "[System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('BypassOutputRedirectionCheck', `$true); `$PSStyle.OutputRendering = '$outputRendering'; write-host '$($PSStyle.Foreground.Green)hello'" + + if ($ansi) { + $out | Should -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + else { + $out | Should -Not -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + } + + It 'OutputRendering works for "" to the pipeline' -TestCases @( + @{ outputRendering = 'automatic'; ansi = $true } + @{ outputRendering = 'host' ; ansi = $false } + @{ outputRendering = 'ansi' ; ansi = $true } + @{ outputRendering = 'plaintext'; ansi = $false } + ) { + param($outputRendering, $ansi) + + $PSStyle.OutputRendering = $outputRendering + $out = "$($PSStyle.Foreground.Green)hello" | Out-String + + if ($ansi) { + $out | Should -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + else { + $out | Should -Not -BeLike "*`e*" -Because ($out | Format-Hex | Out-String) + } + } + + # Error isn't covered here because it has custom formatting + It 'OutputRendering is correct for ' -TestCases @( + @{ stream = 'Verbose' } + @{ stream = 'Debug' } + @{ stream = 'Warning' } + ) { + param($stream) + + if ($stream -ne 'Warning') + { + $switch = "-$stream" + } + + $out = pwsh -noprofile -command "[System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('BypassOutputRedirectionCheck', `$true); write-$stream $switch 'hello'" + $out | Should -BeExactly "$($PSStyle.Formatting.$stream)$($stream.ToUpper()): hello" + } +} diff --git a/test/powershell/engine/Formatting/PSStyle.Tests.ps1 b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 new file mode 100644 index 00000000000..5e02e2e231c --- /dev/null +++ b/test/powershell/engine/Formatting/PSStyle.Tests.ps1 @@ -0,0 +1,114 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'Tests for $PSStyle automatic variable' { + BeforeAll { + $PSDefaultParameterValues.Add('It:Skip', (-not $EnabledExperimentalFeatures.Contains('PSAnsiRendering'))) + $styleDefaults = @{ + Reset = "`e[0m" + BlinkOff = "`e[5m" + Blink = "`e[25m" + BoldOff = "`e[22m" + Bold = "`e[1m" + HiddenOff = "`e[28m" + Hidden = "`e[8m" + ReverseOff = "`e[27m" + Reverse = "`e[7m" + ItalicOff = "`e[23m" + Italic = "`e[3m" + UnderlineOff = "`e[24m" + Underline = "`e[4m" + } + + $formattingDefaults = @{ + FormatAccent = "`e[32;1m" + ErrorAccent = "`e[36;1m" + Error = "`e[31;1m" + Debug = "`e[33;1m" + Verbose = "`e[33;1m" + Warning = "`e[33;1m" + } + + $foregroundDefaults = @{ + Black = "`e[30m" + White = "`e[37m" + DarkGray = "`e[90m" + LightGray = "`e[97m" + Red = "`e[31m" + LightRed = "`e[91m" + Magenta = "`e[35m" + LightMagenta = "`e[95m" + Blue = "`e[34m" + LightBlue = "`e[94m" + Cyan = "`e[36m" + LightCyan = "`e[96m" + Green = "`e[32m" + LightGreen = "`e[92m" + Yellow = "`e[33m" + LightYellow = "`e[93m" + } + + $backgroundDefaults = @{ + Black = "`e[40m" + White = "`e[47m" + DarkGray = "`e[100m" + LightGray = "`e[107m" + Red = "`e[41m" + LightRed = "`e[101m" + Magenta = "`e[45m" + LightMagenta = "`e[105m" + Blue = "`e[44m" + LightBlue = "`e[104m" + Cyan = "`e[46m" + LightCyan = "`e[106m" + Green = "`e[42m" + LightGreen = "`e[102m" + Yellow = "`e[43m" + LightYellow = "`e[103m" + } + + function Get-TestCases($hashtable) { + $testcases = [System.Collections.Generic.List[hashtable]]::new() + foreach ($key in $hashtable.Keys) { + $testcases.Add( + @{ Key = $key; Value = $hashtable[$key] } + ) + } + + return $testcases + } + } + + AfterAll { + $PSDefaultParameterValues.Remove('It:Skip') + } + + It '$PSStyle has correct default for OutputRendering' { + $PSStyle | Should -Not -BeNullOrEmpty + $PSStyle.OutputRendering | Should -BeExactly 'Automatic' + } + + It '$PSStyle has correct defaults for style ' -TestCases (Get-TestCases $styleDefaults) { + param($key, $value) + + $PSStyle.$key | Should -BeExactly $value + } + + It '$PSStyle.Formatting has correct default for ' -TestCases (Get-TestCases $formattingDefaults) { + param($key, $value) + + $PSStyle.Formatting.$key | Should -BeExactly $value + } + + It '$PSStyle.Foreground has correct default for ' -TestCases (Get-TestCases $foregroundDefaults) { + param($key, $value) + + $PSStyle.Foreground.$key | Should -BeExactly $value + } + + It '$PSStyle.Background has correct default for ' -TestCases (Get-TestCases $backgroundDefaults) { + param($key, $value) + + $PSStyle.Background.$key | Should -BeExactly $value + } +} From e33bbd842736b1d1139ba28521d7100a4019ef7f Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 14 Dec 2020 13:59:27 -0800 Subject: [PATCH 136/138] Fix path signed RPMs are uploaded from in release build (#14424) --- tools/releaseBuild/azureDevOps/templates/linux.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index f8cfd397a3d..cc1ea114506 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -151,7 +151,7 @@ jobs: - task: AzureFileCopy@4 displayName: 'Upload to Azure - RPM - Signed' inputs: - SourcePath: '$(Build.StagingDirectory)\signedPackages\*' + SourcePath: '$(Build.StagingDirectory)\signedPackages\release\*' azureSubscription: '$(AzureFileCopySubscription)' Destination: AzureBlob storage: '$(StorageAccount)' @@ -165,7 +165,7 @@ jobs: - template: upload-final-results.yml parameters: - artifactPath: '$(Build.StagingDirectory)\signedPackages' + artifactPath: '$(Build.StagingDirectory)\signedPackages\release' condition: and(and(succeeded(), eq(variables['SHOULD_SIGN'], 'true')),eq(variables['buildName'], 'RPM')) - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 From 47ef533b2edd5f4cfae5adb9533613f142dc4315 Mon Sep 17 00:00:00 2001 From: Travis Plunk Date: Mon, 14 Dec 2020 14:16:55 -0800 Subject: [PATCH 137/138] Use one feed in each nuget.config in official builds (#14363) Co-authored-by: Robert Holt --- build.psm1 | 18 ++++++++++----- nuget.config | 6 ++--- src/Modules/PSGalleryModules.csproj | 10 ++++++++- src/Modules/nuget.config | 11 ++++++++++ test/tools/Modules/nuget.config | 10 +++++++++ .../AzArtifactFeed/PSGalleryToAzArtifacts.yml | 2 +- .../templates/insert-nuget-config-azfeed.yml | 22 +++++++++++++++---- .../azureDevOps/templates/linux.yml | 5 ++++- .../azureDevOps/templates/mac.yml | 16 +++++--------- .../templates/windows-hosted-build.yml | 6 +++-- .../templates/windows-packaging.yml | 4 ++-- 11 files changed, 80 insertions(+), 30 deletions(-) create mode 100644 src/Modules/nuget.config create mode 100644 test/tools/Modules/nuget.config diff --git a/build.psm1 b/build.psm1 index ce9ff123b1b..c6eb8624a41 100644 --- a/build.psm1 +++ b/build.psm1 @@ -337,7 +337,8 @@ function Start-PSBuild { try { # Excluded sqlite3 folder is due to this Roslyn issue: https://github.com/dotnet/roslyn/issues/23060 # Excluded src/Modules/nuget.config as this is required for release build. - git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3 --exclude src/Modules/nuget.config + # Excluded nuget.config as this is required for release build. + git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3 --exclude src/Modules/nuget.config --exclude nuget.config } finally { Pop-Location } @@ -628,7 +629,9 @@ function Restore-PSPackage [switch] $Force, - [switch] $InteractiveAuth + [switch] $InteractiveAuth, + + [switch] $PSModule ) if (-not $ProjectDirs) @@ -652,7 +655,10 @@ function Restore-PSPackage 'Microsoft.NET.Sdk' } - if ($Options.Runtime -notlike 'fxdependent*') { + if ($PSModule.IsPresent) { + $RestoreArguments = @("--verbosity") + } + elseif ($Options.Runtime -notlike 'fxdependent*') { $RestoreArguments = @("--runtime", $Options.Runtime, "/property:SDKToUse=$sdkToUse", "--verbosity") } else { $RestoreArguments = @("/property:SDKToUse=$sdkToUse", "--verbosity") @@ -2500,7 +2506,7 @@ function Copy-PSGalleryModules Find-DotNet - Restore-PSPackage -ProjectDirs (Split-Path $CsProjPath) -Force:$Force.IsPresent + Restore-PSPackage -ProjectDirs (Split-Path $CsProjPath) -Force:$Force.IsPresent -PSModule $cache = dotnet nuget locals global-packages -l if ($cache -match "global-packages: (.*)") { @@ -3282,8 +3288,10 @@ function New-NugetConfigFile - + + + <[FEEDNAME]> diff --git a/nuget.config b/nuget.config index cbb2494cecf..760e780c8ec 100644 --- a/nuget.config +++ b/nuget.config @@ -4,8 +4,8 @@ - - - + + + diff --git a/src/Modules/PSGalleryModules.csproj b/src/Modules/PSGalleryModules.csproj index 3f7b71a07a3..63807dc1e50 100644 --- a/src/Modules/PSGalleryModules.csproj +++ b/src/Modules/PSGalleryModules.csproj @@ -1,6 +1,14 @@ - + + PowerShell + Microsoft Corporation + (c) Microsoft Corporation. + + net5.0 + + true + diff --git a/src/Modules/nuget.config b/src/Modules/nuget.config new file mode 100644 index 00000000000..f5a7f806a36 --- /dev/null +++ b/src/Modules/nuget.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/test/tools/Modules/nuget.config b/test/tools/Modules/nuget.config new file mode 100644 index 00000000000..b0fc73009da --- /dev/null +++ b/test/tools/Modules/nuget.config @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml b/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml index fab28643168..221a385b8b8 100644 --- a/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml +++ b/tools/releaseBuild/azureDevOps/AzArtifactFeed/PSGalleryToAzArtifacts.yml @@ -18,7 +18,7 @@ steps: - pwsh: | Import-Module -Force "$(Build.SourcesDirectory)/tools/releaseBuild/azureDevOps/AzArtifactFeed/SyncGalleryToAzArtifacts.psm1" - SyncGalleryToAzArtifacts -AzDevOpsFeedUserName $(AzDevOpsFeedUserName) -AzDevOpsPAT $(AzDevOpsFeedPAT) -Destination $(Build.ArtifactStagingDirectory) + SyncGalleryToAzArtifacts -AzDevOpsFeedUserName $(AzDevOpsFeedUserName) -AzDevOpsPAT $(AzDevOpsFeedPAT2) -Destination $(Build.ArtifactStagingDirectory) displayName: Download packages from PSGallery that need to be updated condition: succeededOrFailed() diff --git a/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml b/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml index d768a876372..5fdb9f7d977 100644 --- a/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml +++ b/tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml @@ -1,11 +1,25 @@ +parameters: + - name: "repoRoot" + default: $(REPOROOT) + steps: -- powershell: | - Import-Module $env:REPOROOT/build.psm1 -Force - New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT) -FeedName AzDevOpsFeed -Destination $env:REPOROOT/src/Modules +- pwsh: | + Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force + New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT2) -FeedName AzDevOpsFeed -Destination '${{ parameters.repoRoot }}/src/Modules' - if(-not (Test-Path "$env:REPOROOT/src/Modules/nuget.config")) + if(-not (Test-Path "${{ parameters.repoRoot }}/src/Modules/nuget.config")) { throw "nuget.config is not created" } displayName: 'Add nuget.config for Azure DevOps feed for PSGallery modules' condition: and(succeededOrFailed(), ne(variables['AzDevOpsFeed'], '')) +- pwsh: | + Import-Module ${{ parameters.repoRoot }}/build.psm1 -Force + New-NugetConfigFile -NugetFeedUrl $(AzDevOpsPackageFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT2) -FeedName AzDevOpsFeed -Destination '${{ parameters.repoRoot }}' + + if(-not (Test-Path "${{ parameters.repoRoot }}/nuget.config")) + { + throw "nuget.config is not created" + } + displayName: 'Add nuget.config for Azure DevOps feed for packages' + condition: and(succeededOrFailed(), ne(variables['AzDevOpsPackageFeed'], '')) diff --git a/tools/releaseBuild/azureDevOps/templates/linux.yml b/tools/releaseBuild/azureDevOps/templates/linux.yml index cc1ea114506..0fac7ae4f24 100644 --- a/tools/releaseBuild/azureDevOps/templates/linux.yml +++ b/tools/releaseBuild/azureDevOps/templates/linux.yml @@ -42,7 +42,8 @@ jobs: displayName: 'Skip Alpine or fxdependent for PS v6.0.*' - template: insert-nuget-config-azfeed.yml - + parameters: + repoRoot: $(REPOROOT) - powershell: | import-module "$env:REPOROOT/build.psm1" @@ -51,7 +52,9 @@ jobs: condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) - powershell: | + $env:AzDevOpsFeedPAT2 = '$(AzDevOpsFeedPAT2)' & "$env:REPOROOT/tools/releaseBuild/vstsbuild.ps1" -ReleaseTag $(ReleaseTagVar) -Name '$(build)' + $env:AzDevOpsFeedPAT2 = $null displayName: 'Build and package' condition: and(succeeded(), ne(variables['SkipBuild'], 'true')) diff --git a/tools/releaseBuild/azureDevOps/templates/mac.yml b/tools/releaseBuild/azureDevOps/templates/mac.yml index f38e9b63573..6690f678888 100644 --- a/tools/releaseBuild/azureDevOps/templates/mac.yml +++ b/tools/releaseBuild/azureDevOps/templates/mac.yml @@ -35,20 +35,14 @@ jobs: tools/releaseBuild/macOS/PowerShellPackageVsts.ps1 -location $(PowerShellRoot) -BootStrap displayName: 'Bootstrap VM' - - pwsh: | - Import-Module $(Build.SourcesDirectory)/build.psm1 -Force - New-NugetConfigFile -NugetFeedUrl $(AzDevOpsFeed) -UserName $(AzDevOpsFeedUserName) -ClearTextPAT $(AzDevOpsFeedPAT) -FeedName AzDevOpsFeed -Destination "$(PowerShellRoot)/src/Modules" - - if(-not (Test-Path "$(PowerShellRoot)/src/Modules/nuget.config")) - { - throw "nuget.config is not created" - } - displayName: 'Add nuget.config for AzDevOps feed for PSGallery modules ' + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) - pwsh: | - $env:AZDEVOPSFEEDPAT = '$(AzDevOpsFeedPAT)' + $env:AzDevOpsFeedPAT2 = '$(AzDevOpsFeedPAT2)' $(Build.SourcesDirectory)/tools/releaseBuild/macOS/PowerShellPackageVsts.ps1 -ReleaseTag $(ReleaseTagVar) -Destination $(System.ArtifactsDirectory) -Symbols -location $(PowerShellRoot) -Build -ArtifactName macosBinResults - $env:AZDEVOPSFEEDPAT = $null + $env:AzDevOpsFeedPAT2 = $null displayName: 'Build' - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 diff --git a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml index 3413896f0b2..cc05417b17b 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-hosted-build.yml @@ -31,10 +31,12 @@ jobs: parameters: ReleaseTagVar: $(ReleaseTagVar) - - template: insert-nuget-config-azfeed.yml - - template: cloneToOfficialPath.yml + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + parameters: + repoRoot: $(PowerShellRoot) + - powershell: | $runtime = switch ($env:Architecture) diff --git a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml index 0106977dff9..81eac8e5a11 100644 --- a/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml +++ b/tools/releaseBuild/azureDevOps/templates/windows-packaging.yml @@ -60,7 +60,7 @@ jobs: - template: cloneToOfficialPath.yml - - powershell: | + - pwsh: | # cleanup previous install if((Test-Path "${env:ProgramFiles(x86)}\WiX Toolset xcopy")) { Remove-Item "${env:ProgramFiles(x86)}\WiX Toolset xcopy" -Recurse -Force @@ -68,7 +68,7 @@ jobs: $toolsDir = New-Item -ItemType Directory -Path '$(Build.ArtifactStagingDirectory)\tools' $wixUri = 'https://github.com/wixtoolset/wix3/releases/download/wix311rtm/wix311-binaries.zip' - Invoke-RestMethod -Uri $wixUri -OutFile '$(Build.ArtifactStagingDirectory)\tools\wix.zip' + Invoke-RestMethod -Uri $wixUri -OutFile '$(Build.ArtifactStagingDirectory)\tools\wix.zip' -MaximumRetryCount 5 -RetryIntervalSec 10 Import-Module '$(PowerShellRoot)/tools/releaseBuild/Images/microsoft_powershell_windowsservercore/wix.psm1' Install-WixZip -zipPath '$(Build.ArtifactStagingDirectory)\tools\wix.zip' From 88d28cb8788ded72436fec929ac73480cc5f8480 Mon Sep 17 00:00:00 2001 From: Robert Holt Date: Tue, 15 Dec 2020 21:09:53 +0000 Subject: [PATCH 138/138] Merged PR 13877: Add CHANGELOG for 7.2.0-preview.2 Add CHANGELOG for 7.2.0-preview.2 --- CHANGELOG/preview.md | 183 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index 2e89bcd37df..afc36040313 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,5 +1,188 @@ # Current preview release +## [7.2.0-preview.2] - 2020-12-15 + +### Breaking Changes + +- Improve detection of mutable value types (#12495) (Thanks @vexx32!) +- Ensure `-PipelineVariable` is set for all output from script cmdlets (#12766) (Thanks @vexx32!) + +### Experimental Features + +- `PSAnsiRendering`: Enable ANSI formatting via `$PSStyle` and support suppressing ANSI output (#13758) + +### Performance + +- Optimize `IEnumerable` variant of replace operator (#14221) (Thanks @iSazonov!) +- Refactor multiply operation for better performance in two `Microsoft.PowerShell.Commands.Utility` methods (#14148) (Thanks @xtqqczze!) +- Use `Environment.TickCount64` instead of `Datetime.Now` as the random seed for AppLocker test file content (#14283) (Thanks @iSazonov!) +- Avoid unnecessary array allocations when searching in GAC (#14291) (Thanks @xtqqczze!) +- Use `OrdinalIgnoreCase` in `CommandLineParser` (#14303) (Thanks @iSazonov!) +- Use `StringComparison.Ordinal` instead of `StringComparison.CurrentCulture` (#14298) (Thanks @iSazonov!) +- Avoid creating instances of the generated delegate helper class in `-replace` implementation (#14128) + +### General Cmdlet Updates and Fixes + +- Write better error message if config file is broken (#13496) (Thanks @iSazonov!) +- Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353) +- Add `-SkipLimitCheck` switch to `Import-PowerShellDataFile` (#13672) +- Restrict `New-Object` in NoLanguage mode under lock down (#14140) (Thanks @krishnayalavarthi!) +- The `-Stream` parameter now works with directories (#13941) (Thanks @kyanha!) +- Avoid an exception if file system does not support reparse points (#13634) (Thanks @iSazonov!) +- Enable `CA1012`: Abstract types should not have public constructors (#13940) (Thanks @xtqqczze!) +- Enable `SA1212`: Property accessors should follow order (#14051) (Thanks @xtqqczze!) + +### Code Cleanup + +
+ + + +

We thank the following contributors!

+

@xtqqczze, @matthewjdegarmo, @powercode, @Gimly

+ +
+ +
    +
  • Enable SA1007: Operator keyword should be followed by space (#14130) (Thanks @xtqqczze!)
  • +
  • Expand where alias to Where-Object in Reset-PWSHSystemPath.ps1 (#14113) (Thanks @matthewjdegarmo!)
  • +
  • Fix whitespace issues (#14092) (Thanks @xtqqczze!)
  • +
  • Add StyleCop.Analyzers package (#13963) (Thanks @xtqqczze!)
  • +
  • Enable IDE0041: UseIsNullCheck (#14041) (Thanks @xtqqczze!)
  • +
  • Enable IDE0082: ConvertTypeOfToNameOf (#14042) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary usings part 4 (#14023) (Thanks @xtqqczze!)
  • +
  • Fix PriorityAttribute name (#14094) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Interpreter.IBoxableInstruction (#14165) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Provider.IDynamicPropertyProvider (#14167) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Language.IScriptExtent (#14179) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Language.ICustomAstVisitor2 (#14192) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.LanguagePrimitives.IConversionData (#14187) (Thanks @powercode!)
  • +
  • Enable nullable: System.Automation.Remoting.Client.IWSManNativeApiFacade (#14186) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Language.ISupportsAssignment (#14180) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.ICommandRuntime2 (#14183) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IOutputProcessingState (#14175) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IJobDebugger (#14174) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Interpreter.IInstructionProvider (#14173) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IHasSessionStateEntryVisibility (#14169) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Tracing.IEtwEventCorrelator (#14168) (Thanks @powercode!)
  • +
  • Fix syntax error in Windows packaging script (#14377)
  • +
  • Remove redundant local assignment in AclCommands (#14358) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Language.IAstPostVisitHandler (#14164) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.IModuleAssemblyInitializer (#14158) (Thanks @powercode!)
  • +
  • Use Microsoft.PowerShell.MarkdownRender package from nuget.org (#14090)
  • +
  • Replace GetFiles in TestModuleManifestCommand (#14317) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Provider.IContentWriter (#14152) (Thanks @powercode!)
  • +
  • Simplify getting Encoding in TranscriptionOption.FlushContentToDisk (#13910) (Thanks @Gimly!)
  • +
  • Mark applicable structs as readonly and use in-modifier (#13919) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.IArgumentCompleter (#14182) (Thanks @powercode!)
  • +
  • Enable CA1822: Mark private members as static (#13897) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 6 (#14338) (Thanks @xtqqczze!)
  • +
  • Avoid array allocations from GetDirectories/GetFiles. (#14328) (Thanks @xtqqczze!)
  • +
  • Avoid array allocations from GetDirectories/GetFiles. (#14330) (Thanks @xtqqczze!)
  • +
  • Fix RCS1188: Remove redundant auto-property initialization part 2 (#14262) (Thanks @xtqqczze!)
  • +
  • Enable nullable: System.Management.Automation.Host.IHostSupportsInteractiveSession (#14170) (Thanks @powercode!)
  • +
  • Enable nullable: System.Management.Automation.Provider.IPropertyCmdletProvider (#14176) (Thanks @powercode!)
  • +
  • Fix IDE0090: Simplify new expression part 5 (#14301) (Thanks @xtqqczze!)
  • +
  • Enable IDE0075: SimplifyConditionalExpression (#14078) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary usings part 9 (#14288) (Thanks @xtqqczze!)
  • +
  • Fix StyleCop and MarkdownLint CI failures (#14297) (Thanks @xtqqczze!)
  • +
  • Enable SA1000: Keywords should be spaced correctly (#13973) (Thanks @xtqqczze!)
  • +
  • Fix RCS1188: Remove redundant auto-property initialization part 1 (#14261) (Thanks @xtqqczze!)
  • +
  • Mark private members as static part 10 (#14235) (Thanks @xtqqczze!)
  • +
  • Mark private members as static part 9 (#14234) (Thanks @xtqqczze!)
  • +
  • Fix SA1642 for Microsoft.Management.Infrastructure.CimCmdlets (#14239) (Thanks @xtqqczze!)
  • +
  • Use AsSpan/AsMemory slice constructor (#14265) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.6 (#14260) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.5 (#14259) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.3 (#14257) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.2 (#14256) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 2 (#14200) (Thanks @xtqqczze!)
  • +
  • Enable SA1643: Destructor summary documentation should begin with standard text (#14236) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.4 (#14258) (Thanks @xtqqczze!)
  • +
  • Use xml documentation child blocks correctly (#14249) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 4.1 (#14255) (Thanks @xtqqczze!)
  • +
  • Use consistent spacing in xml documentation tags (#14231) (Thanks @xtqqczze!)
  • +
  • Enable IDE0074: Use coalesce compound assignment (#13396) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary finalizers (#14248) (Thanks @xtqqczze!)
  • +
  • Mark local variable as const (#13217) (Thanks @xtqqczze!)
  • +
  • Fix IDE0032: UseAutoProperty part 2 (#14244) (Thanks @xtqqczze!)
  • +
  • Fix IDE0032: UseAutoProperty part 1 (#14243) (Thanks @xtqqczze!)
  • +
  • Mark private members as static part 8 (#14233) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 6 (#14229) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 5 (#14228) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 4 (#14227) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 3 (#14226) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 2 (#14225) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 1 (#14224) (Thanks @xtqqczze!)
  • +
  • Use see keyword in documentation (#14220) (Thanks @xtqqczze!)
  • +
  • Enable CA2211: Non-constant fields should not be visible (#14073) (Thanks @xtqqczze!)
  • +
  • Enable CA1816: Dispose methods should call SuppressFinalize (#14074) (Thanks @xtqqczze!)
  • +
  • Remove incorrectly implemented finalizer (#14246) (Thanks @xtqqczze!)
  • +
  • Fix CA1822: Mark members as static part 7 (#14230) (Thanks @xtqqczze!)
  • +
  • Fix SA1122: Use string.Empty for empty strings (#14218) (Thanks @xtqqczze!)
  • +
  • Fix various xml documentation issues (#14223) (Thanks @xtqqczze!)
  • +
  • Remove unnecessary usings part 8 (#14072) (Thanks @xtqqczze!)
  • +
  • Enable SA1006: Preprocessor keywords should not be preceded by space (#14052) (Thanks @xtqqczze!)
  • +
  • Fix SA1642 for Microsoft.PowerShell.Commands.Utility (#14142) (Thanks @xtqqczze!)
  • +
  • Enable CA2216: Disposable types should declare finalizer (#14089) (Thanks @xtqqczze!)
  • +
  • Wrap and name LoadBinaryModule arguments (#14193) (Thanks @xtqqczze!)
  • +
  • Wrap and name GetListOfFilesFromData arguments (#14194) (Thanks @xtqqczze!)
  • +
  • Enable SA1002: Semicolons should be spaced correctly (#14197) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 3 (#14201) (Thanks @xtqqczze!)
  • +
  • Enable SA1106: Code should not contain empty statements (#13964) (Thanks @xtqqczze!)
  • +
  • Code performance fixes follow-up (#14207) (Thanks @xtqqczze!)
  • +
  • Remove uninformative comments (#14199) (Thanks @xtqqczze!)
  • +
  • Fix IDE0090: Simplify new expression part 1 (#14027) (Thanks @xtqqczze!)
  • +
  • Enable SA1517: Code should not contain blank lines at start of file (#14131) (Thanks @xtqqczze!)
  • +
  • Enable SA1131: Use readable conditions (#14132) (Thanks @xtqqczze!)
  • +
  • Enable SA1507: Code should not contain multiple blank lines in a row (#14136) (Thanks @xtqqczze!)
  • +
  • Enable SA1516 Elements should be separated by blank line (#14137) (Thanks @xtqqczze!)
  • +
  • Enable IDE0031: Null check can be simplified (#13548) (Thanks @xtqqczze!)
  • +
  • Enable CA1065: Do not raise exceptions in unexpected locations (#14117) (Thanks @xtqqczze!)
  • +
  • Enable CA1000: Do not declare static members on generic types (#14097) (Thanks @xtqqczze!)
  • +
+ +
+ +### Tools + +- Fixing formatting in `Reset-PWSHSystemPath.ps1` (#13689) (Thanks @dgoldman-msft!) + +### Tests + +- Reinstate `Test-Connection` tests (#13324) +- Update markdown test packages with security fixes (#14145) + +### Build and Packaging Improvements + +
+ +
    +
  • Fix a typo in the Get-ChangeLog function (#14129)
  • +
  • Update README and metadata.json for 7.2.0-preview.1 release (#14104)
  • +
  • Bump NJsonSchema from 10.2.2 to 10.3.1 (#14040)
  • +
  • Move windows package signing to use ESRP (#14060)
  • +
  • Use one feed in each nuget.config in official builds (#14363)
  • +
  • Fix path signed RPMs are uploaded from in release build (#14424)
  • +
  • Add Microsoft.PowerShell.MarkdownRender to the package reference list (#14386)
  • +
  • Fix issue with unsigned build (#14367)
  • +
  • Move macOS and nuget to ESRP signing (#14324)
  • +
  • Fix nuget packaging to scrub NullableAttribute (#14344)
  • +
  • Bump Microsoft.NET.Test.Sdk from 16.8.0 to 16.8.3 (#14310)
  • +
  • Bump Markdig.Signed from 0.22.0 to 0.22.1 (#14305)
  • +
  • Bump Microsoft.ApplicationInsights from 2.15.0 to 2.16.0 (#14031)
  • +
  • Move Linux to ESRP signing (#14210)
  • +
+ +
+ +### Documentation and Help Content + +- Fix example `nuget.config` (#14349) +- Fix a broken link in Code Guidelines doc (#14314) (Thanks @iSazonov!) + +[7.2.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.2.0-preview.1...v7.2.0-preview.2 + ## [7.2.0-preview.1] - 2020-11-17 ### Engine Updates and Fixes