diff --git a/.dependabot/config.yml b/.dependabot/config.yml index 69640b335c7..ea0745fd494 100644 --- a/.dependabot/config.yml +++ b/.dependabot/config.yml @@ -8,24 +8,52 @@ update_configs: update_schedule: "live" default_labels: - "CL-BuildPackaging" + ignored_updates: + - match: + dependency_name: "System.*" + - match: + dependency_name: "Microsoft.Win32.Registry.AccessControl" + - match: + dependency_name: "Microsoft.Windows.Compatibility" - package_manager: "dotnet:nuget" directory: "/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility" update_schedule: "live" default_labels: - "CL-BuildPackaging" + ignored_updates: + - match: + dependency_name: "System.*" + - match: + dependency_name: "Microsoft.Win32.Registry.AccessControl" + - match: + dependency_name: "Microsoft.Windows.Compatibility" - package_manager: "dotnet:nuget" directory: "/tools/packaging/projects/reference/System.Management.Automation" update_schedule: "live" default_labels: - "CL-BuildPackaging" + ignored_updates: + - match: + dependency_name: "System.*" + - match: + dependency_name: "Microsoft.Win32.Registry.AccessControl" + - match: + dependency_name: "Microsoft.Windows.Compatibility" - package_manager: "dotnet:nuget" directory: "/test/tools/Modules" update_schedule: "live" default_labels: - "CL-BuildPackaging" + ignored_updates: + - match: + dependency_name: "System.*" + - match: + dependency_name: "Microsoft.Win32.Registry.AccessControl" + - match: + dependency_name: "Microsoft.Windows.Compatibility" - package_manager: "dotnet:nuget" directory: "/src/Modules" diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 97c6efee968..305de6bdda3 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -1,9 +1,9 @@ #------------------------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information. #------------------------------------------------------------------------------------------------------------- -FROM mcr.microsoft.com/dotnet/core/sdk:3.1.101 +FROM mcr.microsoft.com/dotnet/core/sdk:5.0.100-preview.2 # Avoid warnings by switching to noninteractive ENV DEBIAN_FRONTEND=noninteractive @@ -13,7 +13,7 @@ RUN apt-get update \ && apt-get -y install --no-install-recommends apt-utils 2>&1 \ # # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed - && apt-get -y install git procps lsb-release \ + && apt-get -y install --no-install-recommends git procps lsb-release \ # # Clean up && apt-get autoremove -y \ diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 3daba6f1dd2..36ae9537336 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,6 +1,6 @@ // See https://aka.ms/vscode-remote/devcontainer.json for format details. { - "name": ".NET Core 3.1, including pwsh (Debian 10)", + "name": ".NET Core 5.0, including pwsh (Debian 10)", "dockerFile": "Dockerfile", // Uncomment the next line to run commands after the container is created. @@ -8,7 +8,7 @@ "extensions": [ "ms-azure-devops.azure-pipelines", - "ms-vscode.csharp", + "ms-dotnettools.csharp", "ms-vscode.powershell", "DavidAnson.vscode-markdownlint", "vitaliymaz.vscode-svg-previewer" diff --git a/.devcontainer/fedora30/devcontainer.json b/.devcontainer/fedora30/devcontainer.json index 9a4da68c1c9..d9ef8ef5312 100644 --- a/.devcontainer/fedora30/devcontainer.json +++ b/.devcontainer/fedora30/devcontainer.json @@ -8,7 +8,7 @@ "extensions": [ "ms-azure-devops.azure-pipelines", - "ms-vscode.csharp", + "ms-dotnettools.csharp", "ms-vscode.powershell", "DavidAnson.vscode-markdownlint", "vitaliymaz.vscode-svg-previewer" diff --git a/.editorconfig b/.editorconfig index ab87f961068..a00fd02dd66 100644 --- a/.editorconfig +++ b/.editorconfig @@ -48,6 +48,9 @@ indent_size = 2 # Sort using and Import directives with System.* appearing first dotnet_sort_system_directives_first = true +# Modifier preferences +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion + # Avoid "this." and "Me." if not necessary dotnet_style_qualification_for_field = false:suggestion dotnet_style_qualification_for_property = false:suggestion diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f1e9368cdab..26e01101693 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -33,7 +33,7 @@ src/Microsoft.PowerShell.Commands.Management/ @daxian-dbw @adityapatwardhan src/Microsoft.PowerShell.Commands.Utility/ @JamesWTruher @PaulHigin # Area: Console -src/Microsoft.PowerShell.ConsoleHost/ @daxian-dbw @anmenaga +src/Microsoft.PowerShell.ConsoleHost/ @daxian-dbw @anmenaga @TylerLeonhardt # Area: Demos demos/ @joeyaiello @SteveL-MSFT @HemantMahawar diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index a61bf28408b..8548101590f 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -19,7 +19,7 @@ Please read the rest of this document to ensure a smooth contribution process. ## Quick Start Checklist -* Review the [Contribution License Agreement][CLA] requirement. +* Review the [Contributor License Agreement][CLA] requirement. * Get familiar with the [PowerShell repository](../docs/git). ## Contributing to Issues @@ -115,7 +115,7 @@ Please see [Building PowerShell](../README.md#building-the-repository). #### Testing PowerShell -Please see PowerShell [Testing Guidelines - Running Tests Outside of CI][running-tests-outside-of-ci] on how to test you build locally. +Please see PowerShell [Testing Guidelines - Running Tests Outside of CI][running-tests-outside-of-ci] on how to test your build locally. ### Finding or creating an issue @@ -167,11 +167,11 @@ Additional references: An issue title is to briefly describe what is wrong, while a PR title is to briefly describe what is changed. A better example is: "Add Ensure parameter to New-Item cmdlet", with "Fix #5" in the PR's body. * When you create a pull request, - including a summary about your changes in the PR description. + include a summary about your changes in the PR description. The description is used to create change logs, so try to have the first sentence explain the benefit to end users. If the changes are related to an existing GitHub issue, - please reference the issue in PR description (e.g. ```Fix #11```). + please reference the issue in the PR description (e.g. ```Fix #11```). See [this][closing-via-message] for more details. * Please use the present tense and imperative mood when describing your changes: @@ -196,7 +196,7 @@ Additional references: * For `.h`, `.cpp`, and `.cs` files use the copyright header with empty line after it: ```c# - // Copyright (c) Microsoft Corporation. All rights reserved. + // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. ``` @@ -204,7 +204,7 @@ Additional references: * For `.ps1` and `.psm1` files use the copyright header with empty line after it: ```powershell - # Copyright (c) Microsoft Corporation. All rights reserved. + # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ``` @@ -214,7 +214,7 @@ Additional references: ```powershell Author = "PowerShell" Company = "Microsoft Corporation" - Copyright = "Copyright (c) Microsoft Corporation. All rights reserved." + Copyright = "Copyright (c) Microsoft Corporation." ``` is at the top. @@ -277,10 +277,10 @@ Additional references: - `Request changes` if you believe the PR merge should be blocked if your feedback is not addressed, - `Approve` if you believe your feedback has been addressed or the code is fine as-is, it is customary (although not required) to leave a simple "Looks good to me" (or "LGTM") as the comment for approval. - `Comment` if you are making suggestions that the *author* does not have to accept. - Early in the review, it is acceptable to provide feedback on coding formatting based on the published [Coding Guidelines](../docs/dev-process/coding-guidelines.md), however, - after the PR has been approved, it is generally _not_ recommended to focus on formatting issues unless they go against the [Coding Guidelines](../docs/dev-process/coding-guidelines.md). + Early in the review, it is acceptable to provide feedback on coding formatting based on the published [Coding Guidelines][coding-guidelines], however, + after the PR has been approved, it is generally _not_ recommended to focus on formatting issues unless they go against the [Coding Guidelines][coding-guidelines]. Non-critical late feedback (after PR has been approved) can be submitted as a new issue or new pull request from the *reviewer*. -1. *Assignee* who are always *Maintainers* ensure that proper review has occurred and if they believe one approval is not sufficient, the *maintainer* is responsible to add more reviewers. +1. *Assignees* who are always *Maintainers* ensure that proper review has occurred and if they believe one approval is not sufficient, the *maintainer* is responsible to add more reviewers. An *assignee* may also be a reviewer, but the roles are distinct. Once the PR has been approved and the CI system is passing, the *assignee* will merge the PR after giving one business day for any critical feedback. For more information on the PowerShell Maintainers' process, see the [documentation](../docs/maintainers). @@ -302,22 +302,22 @@ In these cases: ## Making Breaking Changes When you make code changes, -please pay attention to these that can affect the [Public Contract](../docs/dev-process/breaking-change-contract.md). +please pay attention to these that can affect the [Public Contract][breaking-changes-contract]. For example, changing PowerShell parameters, APIs, or protocols break the public contract. Before making changes to the code, -first review the [breaking changes contract](../docs/dev-process/breaking-change-contract.md) +first review the [breaking changes contract][breaking-changes-contract] and follow the guidelines to keep PowerShell backward compatible. ## Making Design Changes To add new features such as cmdlets or making design changes, -please follow the [PowerShell Request for Comments (RFC)](https://github.com/PowerShell/PowerShell-RFC) process. +please follow the [PowerShell Request for Comments (RFC)][rfc-process] process. ## Common Engineering Practices -Other than the guidelines for ([coding](../docs/dev-process/coding-guidelines.md), -the [RFC process](https://github.com/PowerShell/PowerShell-RFC) for design, -[documentation](#contributing-to-documentation) and [testing](../docs/testing-guidelines/testing-guidelines.md)) discussed above, +Other than the guidelines for [coding][coding-guidelines], +the [RFC process][rfc-process] for design, +[documentation](#contributing-to-documentation) and [testing](../docs/testing-guidelines/testing-guidelines.md) discussed above, we encourage contributors to follow these common engineering practices: * Format commit messages following these guidelines: @@ -359,7 +359,7 @@ is also appropriate, as is using Markdown syntax. If you find code that you think is a good fit to add to PowerShell, file an issue and start a discussion before proceeding. * Create and/or update tests when making code changes. -* Run tests and ensure they are passing before pull request. +* Run tests and ensure they are passing before opening a pull request. * All pull requests **must** pass CI systems before they can be approved. * Avoid making big pull requests. Before you invest a large amount of time, @@ -368,7 +368,7 @@ is also appropriate, as is using Markdown syntax. ## Contributor License Agreement (CLA) To speed up the acceptance of any contribution to any PowerShell repositories, -you should to [sign a Microsoft Contribution Licensing Agreement (CLA)](https://cla.microsoft.com/) ahead of time. +you should sign the Microsoft [Contributor License Agreement (CLA)](https://cla.microsoft.com/) ahead of time. If you've already contributed to PowerShell or Microsoft repositories in the past, congratulations! You've already completed this step. This a one-time requirement for the PowerShell project. @@ -395,8 +395,10 @@ Once you sign a CLA, all your existing and future pull requests will have the st [up-for-grabs]: https://github.com/powershell/powershell/issues?q=is%3Aopen+is%3Aissue+label%3AUp-for-Grabs [semantic linefeeds]: https://rhodesmill.org/brandon/2012/one-sentence-per-line/ [PowerShell-Docs]: https://github.com/powershell/powershell-docs/ -[use-vscode-editor]: ../docs/learning-powershell/using-vscode.md#editing-with-visual-studio-code +[use-vscode-editor]: https://docs.microsoft.com/dotnet/core/tutorials/with-visual-studio-code [repository-maintainer]: ../docs/community/governance.md#repository-maintainers [area-expert]: ../docs/community/governance.md#area-experts -[ci-system]: ../docs/testing-guidelines/testing-guidelines.md#ci-system [first-time-issue]: https://github.com/powershell/powershell/issues?q=is%3Aopen+is%3Aissue+label%3AFirst-Time-Issue +[coding-guidelines]: ../docs/dev-process/coding-guidelines.md +[breaking-changes-contract]: ../docs/dev-process/breaking-change-contract.md +[rfc-process]: https://github.com/PowerShell/PowerShell-RFC diff --git a/.github/ISSUE_TEMPLATE/Bug_Report.md b/.github/ISSUE_TEMPLATE/Bug_Report.md index 5b188e071ae..2c51890e890 100644 --- a/.github/ISSUE_TEMPLATE/Bug_Report.md +++ b/.github/ISSUE_TEMPLATE/Bug_Report.md @@ -16,29 +16,29 @@ This repository is **ONLY** for PowerShell Core 6 and PowerShell 7+ issues. - Make sure you are able to repro it on the [latest released version](https://github.com/PowerShell/PowerShell/releases) - Search the existing issues. - Refer to the [FAQ](https://github.com/PowerShell/PowerShell/blob/master/docs/FAQ.md). -- Refer to the [known issues](https://docs.microsoft.com/powershell/scripting/whats-new/known-issues-ps6?view=powershell-6). +- Refer to the [known issues](https://docs.microsoft.com/powershell/scripting/whats-new/known-issues-ps6). --> -# Steps to reproduce +## Steps to reproduce ```powershell ``` -# Expected behavior +## Expected behavior ```none ``` -# Actual behavior +## Actual behavior ```none ``` -# Environment data +## Environment data diff --git a/.github/ISSUE_TEMPLATE/Distribution_Request.md b/.github/ISSUE_TEMPLATE/Distribution_Request.md index 63a503f440f..9aca6160bc7 100644 --- a/.github/ISSUE_TEMPLATE/Distribution_Request.md +++ b/.github/ISSUE_TEMPLATE/Distribution_Request.md @@ -1,30 +1,35 @@ --- name: Distribution Support Request -about: Requests suppoort for a new distribution +about: Requests support for a new distribution title: "Distribution Support Request" labels: Distribution-Request assignees: '' --- -# Details of the Distribution +## Details of the Distribution -- Name of the Distribution: +- Name of the Distribution: - Version of the Distribution: -- Processor Architecture (One per request): +- Package Types + - [ ] Deb + - [ ] RPM + - [ ] Tar.gz + - Snap - Please file issue in https://github.com/powershell/powershell-snap. This issues type is unrelated to snap packages with a distribution neutral. +- Processor Architecture (One per request): - [ ] **Required** - An issues has been filed to create a Docker image in https://github.com/powershell/powershell-docker - The following is a requirement for supporting a distribution **without exception.** - - [ ] The version and architecture of the Distribution is [supported by .NET Core](https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#linux). + - [ ] The version and architecture of the Distribution is [supported by .NET Core](https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#linux). - The following are requirements for supporting a distribution. - Please write a justification for any exception where these criteria are not met and - the PowerShell comittee will review the request. - - [ ] The version of the Distribution is supported for at least one year. - - [ ] The version of the Distribution is not an [interim release](https://ubuntu.com/about/release-cycle) or equivalent. + Please write a justification for any exception where these criteria are not met and + the PowerShell committee will review the request. + - [ ] The version of the Distribution is supported for at least one year. + - [ ] The version of the Distribution is not an [interim release](https://ubuntu.com/about/release-cycle) or equivalent. ## Progress - For PowerShell Team **ONLY** - [ ] Docker image created - [ ] Docker image published - [ ] Distribution tested -- [ ] Lifecycle updated +- [ ] [Lifecycle](https://github.com/MicrosoftDocs/PowerShell-Docs/blob/staging/reference/docs-conceptual/PowerShell-Support-Lifecycle.md) updated - [ ] Documentation Updated diff --git a/.github/ISSUE_TEMPLATE/Feature_Request.md b/.github/ISSUE_TEMPLATE/Feature_Request.md index 2b724b2eac3..cf91c6e3dc3 100644 --- a/.github/ISSUE_TEMPLATE/Feature_Request.md +++ b/.github/ISSUE_TEMPLATE/Feature_Request.md @@ -7,7 +7,7 @@ assignees: '' --- -# Summary of the new feature/enhancement +## Summary of the new feature/enhancement -# Proposed technical implementation details (optional) +## Proposed technical implementation details (optional) -# Release Process for v6.x.x +## Checklist - [ ] Verify that `PowerShell-Native` has been updated/released as needed. - [ ] Check for `PowerShellGet` and `PackageManagement` release plans. diff --git a/.github/ISSUE_TEMPLATE/Security_Issue_Report.md b/.github/ISSUE_TEMPLATE/Security_Issue_Report.md index a0222650f6a..f2304882dc3 100644 --- a/.github/ISSUE_TEMPLATE/Security_Issue_Report.md +++ b/.github/ISSUE_TEMPLATE/Security_Issue_Report.md @@ -7,7 +7,7 @@ assignees: 'TravisEz13' --- -# Security Issue +## Security Issue Excerpt from [Issue Management - Security Vulnerabilities](https://github.com/PowerShell/PowerShell/blob/master/.github/SECURITY.md) diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md index 655b55c65c5..a34d36186ed 100644 --- a/.github/SUPPORT.md +++ b/.github/SUPPORT.md @@ -5,9 +5,9 @@ If you do not see your problem captured, please file a [new issue][] and follow Also make sure to see the [Official Support Policy][]. If you know how to fix the issue, feel free to send a pull request our way. (The [Contribution Guides][] apply to that pull request, you may want to give it a read!) -[Official Support Policy]: https://docs.microsoft.com/powershell/scripting/powershell-support-lifecycle?view=powershell-6 +[Official Support Policy]: https://docs.microsoft.com/powershell/scripting/powershell-support-lifecycle [FAQ]: https://github.com/PowerShell/PowerShell/tree/master/docs/FAQ.md [Contribution Guides]: https://github.com/PowerShell/PowerShell/tree/master/.github/CONTRIBUTING.md -[known issues]: https://docs.microsoft.com/powershell/scripting/whats-new/known-issues-ps6?view=powershell-6 +[known issues]: https://docs.microsoft.com/powershell/scripting/whats-new/known-issues-ps6 [GitHub issues]: https://github.com/PowerShell/PowerShell/issues [new issue]: https://github.com/PowerShell/PowerShell/issues/new/choose diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml new file mode 100644 index 00000000000..3447bf1803d --- /dev/null +++ b/.github/workflows/daily.yml @@ -0,0 +1,55 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +name: PowerShell Daily +on: + schedule: + # At 13:00 UTC every day. + - cron: '0 13 * * *' + +defaults: + run: + shell: pwsh + +env: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + +jobs: + update-dotnet-preview: + name: Update .NET preview + timeout-minutes: 15 + runs-on: windows-latest + if: github.repository == 'PowerShell/PowerShell' + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Sync tags + run: | + git fetch --prune --unshallow --tags + - name: Execute Update .NET script + run: | + $currentVersion = (Get-Content .\global.json | ConvertFrom-Json).sdk.version + Write-Verbose "name=OLD_VERSION::$currentVersion" -Verbose + Write-Host "::set-env name=OLD_VERSION::$currentVersion" + + ./tools/UpdateDotnetRuntime.ps1 -UpdateMSIPackaging + $newVersion = (Get-Content .\global.json | ConvertFrom-Json).sdk.version + Write-Verbose "name=NEW_VERSION::$newVersion" -Verbose + Write-Host "::set-env name=NEW_VERSION::$newVersion" + + if ($currentVersion -ne $newVersion) { + Write-Verbose "name=CREATE_PR::true" -Verbose + Write-Host "::set-env name=CREATE_PR::true" + } + - name: Create Pull Request + uses: peter-evans/create-pull-request@v2 + id: cpr + if: env.CREATE_PR == 'true' + with: + commit-message: "Update .NET SDK version from `${{ env.OLD_VERSION }}` to `${{ env.NEW_VERSION }}`" + title: "Update .NET SDK version from `${{ env.OLD_VERSION }}` to `${{ env.NEW_VERSION }}`" + base: master + branch: dotnet_update + + diff --git a/.gitignore b/.gitignore index 4c6f04a3afc..fb19bcffa77 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ bin/ obj/ +.ionide/ project.lock.json *-tests.xml /debug/ diff --git a/.poshchan/settings.json b/.poshchan/settings.json index bb3c3661696..21ad0f08b48 100644 --- a/.poshchan/settings.json +++ b/.poshchan/settings.json @@ -6,11 +6,13 @@ "windows": "PowerShell-CI-Windows", "macos": "PowerShell-CI-macOS", "linux": "PowerShell-CI-Linux", + "ssh": "PowerShell-CI-SSH", "all": [ "PowerShell-CI-static-analysis", "PowerShell-CI-Windows", "PowerShell-CI-macOS", - "PowerShell-CI-Linux" + "PowerShell-CI-Linux", + "PowerShell-CI-SSH" ] }, "authorized_users": [ diff --git a/.spelling b/.spelling index caa00537206..958cb119706 100644 --- a/.spelling +++ b/.spelling @@ -3,9 +3,11 @@ # global dictionary is at the start, file overrides afterwards # one word per line, to define a file override use ' - filename' # where filename is relative to this configuration file +-title 0-powershell-crossplatform 0xfeeddeadbeef 100ms +1redone 2.x 2ae5d07 32-bit @@ -14,13 +16,16 @@ about_ about_debuggers about_jobs acl +adamdriscoll add-localgroupmember add-ons adelton adhoc aditya adityapatwardhan +ADOPTERS.md aiello +alepauly alexandair alexjordan6 alpha.10 @@ -36,8 +41,10 @@ alpha.7 alpha.8 alpha.9 alternatestream +alvarodelvalle amd64 andschwa +anmenaga api apis appimage @@ -51,6 +58,7 @@ asp.net assemblyloadcontext authenticodesignature azdevops +AzFileCopy azurerm.netcore.preview azurerm.profile.netcore.preview azurerm.resources.netcore.preview @@ -71,8 +79,10 @@ bgelens Bhaal22 bjh7242 bool +bpayette breakpoint brianbunke +britishben brucepay bugfix build.json @@ -84,8 +94,8 @@ cdxml celsius CentOS changelog -changelogs changelog.md +changelogs changeset changesets channel9 @@ -93,6 +103,7 @@ charset checkbox checksum childitem +ChrisLGardner cimsession cimsupport classlib @@ -108,6 +119,7 @@ codebase codecov.io codecoverage.zip codefactor +CodeFormatter codeowner codepage commanddiscovery @@ -149,23 +161,32 @@ csharp csmacnz csphysicallyinstalledmemory ctrl +CurrentCulture +DamirAinullin darquewarrior darwinjs +DateTime daxian-dbw dayofweek dchristian3188 ddwr debughandler dee-see +dependabot deps deserialization deserialize +deserialized +deserializing dest dest.txt dev devblackops +devcontainer deviceguard +devlead devops +Dictionary.TryAdd diddledan disable-localuser disable-psbreakpoint @@ -183,8 +204,9 @@ dlwyatt dockerbasedbuild dockerfile dockerfiles -dongbo +doctordns don'ts +dongbo dotcover dotnet dotnetcore @@ -194,6 +216,9 @@ dropdown e.g. ebook ebooks +ece-jacob-scott +EditorConfig +edyoung enable-localuser enable-psbreakpoint enable-pstrace @@ -201,13 +226,16 @@ enable-pswsmancombinedtrace enable-runspacedebug enable-wsmantrace encodings +endian enter-pshostprocess enter-pssession enum enums +Environment.NewLine ergo3114 errorrecord etl +eugenesmlv excludeversion exe executables @@ -221,6 +249,8 @@ export-formatdata export-modulemember failurecode failurecount +fbehrens +felixfbecker ffeldhaus filecatalog filename @@ -235,9 +265,11 @@ folderName foreach formatfileloading formatviewbinding +Francisco-Gamino frontload fullclr functionprovider +fxdependent gabrielsroka gamified gc.regions.xml @@ -250,6 +282,7 @@ get-ciminstance get-computerinfo get-cronjob get-eventsubscriber +Get-ExperimentalFeature get-filehash get-formatdata get-installedmodule @@ -262,7 +295,6 @@ get-localuser get-logproperties get-packageprovider get-packagesource -getparentprocess get-psbreakpoint get-pscallstack get-pshostprocessinfo @@ -274,11 +306,14 @@ get-pssession get-pssessioncapability get-runspacedebug get-systemdjournal -gettype get-typedata get-uiculture get-winevent get-wsmaninstance +GetExceptionForHR +getparentprocess +gettype +Geweldig gitcommitid github githug @@ -298,6 +333,7 @@ helpsystem hemant hemantmahawar himura2la +hololens homebrew hostname hotfix @@ -305,6 +341,7 @@ httpbin.org httpbin's https hubuk +hvitved i.e. idera ifdef'ed @@ -335,12 +372,15 @@ iscoreclr isnot itemtype itpro +jackdcasey jameswtruher Jawz84 jazzdelightsme jeffbi +jellyfrog jen joandrsn +joeltankam joeyaiello jokajak joshuacooper @@ -355,9 +395,11 @@ kanjibates kasper3 katacoda kevinmarquette +kevinoid keyfileparameter keyhandler khansen00 +kiazhi kirkmunro kittholland korygill @@ -367,35 +409,48 @@ kwiknick kwkam kylesferrazza labelling +LabhanshAgrawal lastwritetime launch.json ldspits lee303 +Leonhardt libpsl libpsl-native libunwind8 linux locationglobber +lockdown loopback lossless louistio +LucaFilipozzi +lukexjeremy +lupino3 lynda.com lzybkr +M1kep mababio macos macports maertendmsft mahawar +Markdig.Signed markekraus marktiedemann +Marusyk mcbobke md meir017 memberresolution +Menagarishvili messageanalyzer metadata +metadata.json miaromero microsoft +Microsoft.ApplicationInsights +Microsoft.CodeAnalysis.CSharp microsoft.com microsoft.management.infrastructure.cimcmdlets microsoft.management.infrastructure.native @@ -416,15 +471,18 @@ microsoft.powershell.security microsoft.powershell.utility microsoft.wsman.management microsoft.wsman.runtime +mikeTWC1984 mirichmo +mjanko5 mkdir mklement0 +MohiTheFish move-itemproperty +ms-psrp msbuild msftrncs mshsnapinloadunload msi -ms-psrp multiline multipart mv @@ -436,12 +494,15 @@ namespace nano nanoserver nativeexecution +net5.0 +netcoreapp5.0 netip.ps1. netstandard.dll new-apachevhost new-ciminstance new-cimsessionoption new-cronjob +New-DockerTestBuild new-guid new-itemproperty new-localgroup @@ -458,6 +519,9 @@ new-timespan new-winevent new-wsmaninstance new-wsmansessionoption +NextTurn +NJsonSchema +NoMoreFood non-22 non-cim non-https @@ -465,8 +529,9 @@ non-r2 noresume notcontains nuget -nugetfeed +nuget.config nuget.exe +nugetfeed numberbytes nupkg oauth @@ -476,6 +541,7 @@ omi omnisharp OneDrive oneget.org +OneScripter opencover opencover.zip openssh @@ -484,15 +550,19 @@ opensuse oss p1 packagemanagement +PackageVersion +parameshbabu parameterbinderbase parameterbindercontroller parameterbinding +ParseError.ToString pathresolution patochun patwardhan paulhigin pawamoy payette +perf perfview perfview.exe petseral @@ -504,9 +574,12 @@ pougetat powerbi powercode powershell +powershell-unix powershell.6 powershell.com +PowerShell.Common.props powershell.core.instrumentation +powershell.exe powershell.org powershellcore powershellgallery @@ -514,23 +587,25 @@ powershellget powershellmagazine.com powershellninja powershellproperties -powershell-unix ppadmavilasom pre-build pre-compiled pre-generated pre-installed -prepend -preprocessor pre-release pre-releases pre-requisites +prepend +preprocessor preview.1 preview.2 preview.3 preview.4 preview.5 preview.6 +preview.7 +preview.4.20258.7 +preview.4.20229.10 preview1-24530-04 preview7 productversion @@ -547,6 +622,7 @@ psdrive psdriveinfo pseudoparameterbinder psgallery +PSGalleryModules psm1 psobject psobjects @@ -559,21 +635,26 @@ pssnapinloadunload pssnapins psversion psversiontable +PSWindowsPowerShellCompatibility +PublishReadyToRun pvs-studio pwd pwrshplughin.dll pwsh qmfrederik raghav710 +RandomNoun7 raspbian rc rc.1 rc.2 +rc.3 rc2-24027 rc3-24011 readme readme.md readonly +ReadyToRun rebase rebasing receive-pssession @@ -606,7 +687,9 @@ remove-wsmaninstance rename-itemproperty rename-localgroup rename-localuser +renehernandez reparse +replicaJunction repo reportgenerator resgen @@ -618,12 +701,13 @@ resx richardszalay Rin rkeithhill +rkitover robo210 ronn rpalo runspace -runspaces runspaceinit +runspaces runtime runtimes sample-dotnet1 @@ -631,6 +715,7 @@ sample-dotnet2 sarithsutha savehelp sazonov +sba923 schvartzman schwartzmeyer scriptblock @@ -644,7 +729,6 @@ sessionstate sessionstatecontainer sessionstateitem set-ciminstance -sethvs set-itemproperty set-localgroup set-localuser @@ -658,9 +742,13 @@ set-psrepository set-strictmode set-wsmaninstance set-wsmanquickconfig +sethvs +setversionvariables +ShaydeNofziger shellexecute shouldbeerrorid showcommandinfo +silijon simonwahlin singleline smes @@ -669,18 +757,24 @@ snapin snover sometext source.txt +spongemike2 src ss64.com +st0le stackoverflow stanzilla start-codecoveragerun stdin stevel-msft +stevend811 stknohg strawgate streamdescribecifeaturescenariodescribecontextitcontextcontextbeforeallafterallbeforeeachaftereachshould +StrictMode +string.split stringbuilder stuntguy3000 +StyleCop submodule submodules sudo @@ -692,47 +786,55 @@ symlink symlinks syscall syslog +System.IO.Packaging system.manage system.management.automation systemd +SytzeAndr tabcompletion tadas tandasat +TargetFramework +test-modulemanifest +test-pssessionconfigurationfile +test-scriptfileinfo test.ps1 test.txt. test1.txt test2.txt testcase testdrive -test-modulemanifest -test-pssessionconfigurationfile tests.zip -test-scriptfileinfo tgz theflyingcorpse thenewstellw thezim +ThomasNieto threadjob throttlelimit throw-testcasesitmockdescribe +ThrowExceptionForHR timcurwick timestamp timothywlewis --title tobias +tokenizer.cs tokenizing tomconte +tommymaynard toolchain toolset tracesource travisez13 travisty truher +tylerleonhardt typecataloggen typeconversion typegen typematch ubuntu +un-versioned unicode unregister-event unregister-packagesource @@ -740,7 +842,7 @@ unregister-psrepository unregister-pssessionconfiguration unregistering untracked -un-versioned +unvalidated update-formatdata update-modulemanifest update-scriptfileinfo @@ -749,8 +851,8 @@ uri urls userdata uservoice -utf8 utf-8 +utf8 utf8nobom utils utils.cs @@ -763,6 +865,7 @@ v0.6.0 v141 v3 v4 +v5 v5.0 v6 v6.0. @@ -773,17 +876,22 @@ v6.0.4 v6.0.5 v6.1.0 v6.1.1 +v6.1.2 v6.2.0 v6.2.1 v6.2.2 v6.2.3 v6.2.4 +v7.0.0 validatenotnullorempty versioned versioning +vexx32 visualstudio +vmsilvamolina vorobev vors +vpondala vscode vstsbuild.ps1 walkthrough @@ -818,46 +926,12 @@ x86 xpath xtqqczze xunit +Xunit.SkippableFact yaml +yashrajbharti +yml youtube zackjknight -vexx32 -perf -britishben -felixfbecker -vpondala -dependabot -jellyfrog -1redone -tommymaynard -vmsilvamolina -fbehrens -lockdown -lukexjeremy -deserializing -kiazhi -v6.1.2 -Menagarishvili -anmenaga -fxdependent -sba923 -replicaJunction -lupino3 -hvitved -unvalidated -Geweldig -mjanko5 -v7.0.0 -renehernandez -ece-jacob-scott -st0le -MohiTheFish -CodeFormatter -StyleCop -SytzeAndr -yashrajbharti -Leonhardt -tylerleonhardt - CHANGELOG.md aavdberg asrosent @@ -903,7 +977,53 @@ Greg-Smulko danstur vdamewood MJECloud +DamirAinullin +NoMoreFood +silijon +NextTurn +mikeTWC1984 +Marusyk +M1kep +doctordns +alvarodelvalle +devlead +RandomNoun7 +edyoung +stevend811 +LabhanshAgrawal +ShaydeNofziger +alepauly +bpayette +joeltankam +OneScripter +Francisco-Gamino +adamdriscoll analytics +deserialized +string.Split +Dictionary.TryAdd +Environment.NewLine +ParseError.ToString +EditorConfig +GetExceptionForHR +ThrowExceptionForHR +Get-ExperimentalFeature +PSWindowsPowerShellCompatibility +currentculture +NJsonSchema +Microsoft.CodeAnalysis.CSharp +NJsonSchema +StrictMode +devcontainer +AzFileCopy +metadata.json +ADOPTERS.md +powershell.exe +SetVersionVariables +yml +DateTime +DeploymentScripts +Markdig.Signed - docs/debugging/README.md corehost - docs/learning-powershell/README.md @@ -931,3 +1051,6 @@ wpaProfile - CHANGELOG/preview.md ThomasNieto spongemike2 +davidseibel +HumanEquivalentUnit +jcotton42 diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 117f430270b..683a979ec46 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -4,7 +4,7 @@ "recommendations": [ "ms-azure-devops.azure-pipelines", "ms-vscode.cpptools", - "ms-vscode.csharp", + "ms-dotnettools.csharp", "ms-vscode.PowerShell", "twxs.cmake", "DavidAnson.vscode-markdownlint", diff --git a/.vsts-ci/linux-daily.yml b/.vsts-ci/linux-daily.yml new file mode 100644 index 00000000000..6ab1832dfd9 --- /dev/null +++ b/.vsts-ci/linux-daily.yml @@ -0,0 +1,157 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - /.vsts-ci/misc-analysis.yml + - /.github/ISSUE_TEMPLATE/* + - /.dependabot/config.yml +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '*' + exclude: + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* + - /.vsts-ci/misc-analysis.yml + - /.github/ISSUE_TEMPLATE/* + - /.dependabot/config.yml + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + __SuppressAnsiEscapeSequences: 1 + +resources: +- repo: self + clean: true + +stages: +- stage: BuildLinux + displayName: Build for Linux + jobs: + - template: templates/ci-build.yml + parameters: + pool: ubuntu-16.04 + jobName: linux_build + displayName: linux Build + +- stage: TestLinux + displayName: Test for Linux + jobs: + - job: linux_test + pool: + vmImage: ubuntu-16.04 + displayName: Linux Test + + steps: + - pwsh: | + Get-ChildItem -Path env: + displayName: Capture Environment + condition: succeededOrFailed() + + - task: DownloadBuildArtifacts@0 + displayName: 'Download Build Artifacts' + inputs: + downloadType: specific + itemPattern: | + build/**/* + xunit/**/* + downloadPath: '$(System.ArtifactsDirectory)' + + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture Artifacts Directory' + continueOnError: true + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\build.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + $output = (Get-PSOptions).Output + $rootPath = Split-Path (Split-Path $output) + Expand-Archive -Path '$(System.ArtifactsDirectory)\build\build.zip' -DestinationPath $rootPath -Force + + ## Fix permissions + Get-ChildItem $rootPath -Recurse | ForEach-Object { + if ($_ -is [System.IO.DirectoryInfo]) { + chmod +rwx $_.FullName + } else { + chmod +rw $_.FullName + } + } + chmod a+x $output + + Write-Host "=== Capture Unzipped Directory ===" + Get-ChildItem $rootPath -Recurse + displayName: 'Unzip Build and Fix Permissions' + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose UnelevatedPesterTests -TagSet CI + displayName: Test - UnelevatedPesterTests - CI + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose ElevatedPesterTests -TagSet CI + displayName: Test - ElevatedPesterTests - CI + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose UnelevatedPesterTests -TagSet Others + displayName: Test - UnelevatedPesterTests - Others + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose ElevatedPesterTests -TagSet Others + displayName: Test - ElevatedPesterTests - Others + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\build.psm1 + $xUnitTestResultsFile = "$(System.ArtifactsDirectory)\xunit\xUnitTestResults.xml" + Test-XUnitTestResults -TestResultsFile $xUnitTestResultsFile + displayName: Verify xUnit Test Results + condition: succeededOrFailed() + +- stage: CodeCovTestPackage + displayName: CodeCoverage and Test Packages + dependsOn: [] # by specifying an empty array, this stage doesn't depend on the stage before it + jobs: + - job: CodeCovTestPackage + displayName: CodeCoverage and Test Packages + pool: + vmImage: ubuntu-16.04 + steps: + - pwsh: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + displayName: CodeCoverage and Test Package diff --git a/.vsts-ci/linux.yml b/.vsts-ci/linux.yml index 6c7a94e0216..3b934fccb4a 100644 --- a/.vsts-ci/linux.yml +++ b/.vsts-ci/linux.yml @@ -11,7 +11,6 @@ trigger: include: - '*' exclude: - - /tools/releaseBuild/**/* - /.vsts-ci/misc-analysis.yml - /.github/ISSUE_TEMPLATE/* - /.dependabot/config.yml @@ -25,7 +24,8 @@ pr: include: - '*' exclude: - - /tools/releaseBuild/**/* + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* - /.vsts-ci/misc-analysis.yml - /.github/ISSUE_TEMPLATE/* - /.dependabot/config.yml @@ -40,59 +40,62 @@ variables: resources: - repo: self clean: true -jobs: -- template: templates/ci-build.yml - parameters: - pool: ubuntu-16.04 - jobName: linux_build - displayName: linux Build -- template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: UnelevatedPesterTests - tagSet: CI - parentJobs: - - linux_build +stages: +- stage: BuildLinux + displayName: Build for Linux + jobs: + - template: templates/ci-build.yml + parameters: + pool: ubuntu-16.04 + jobName: linux_build + displayName: linux Build -- template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: ElevatedPesterTests - tagSet: CI - parentJobs: - - linux_build +- stage: TestLinux + displayName: Test for Linux + jobs: + - template: templates/nix-test.yml + parameters: + name: Linux + pool: ubuntu-16.04 + purpose: UnelevatedPesterTests + tagSet: CI -- template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: UnelevatedPesterTests - tagSet: Others - parentJobs: - - linux_build + - template: templates/nix-test.yml + parameters: + name: Linux + pool: ubuntu-16.04 + purpose: ElevatedPesterTests + tagSet: CI -- template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: ElevatedPesterTests - tagSet: Others - parentJobs: - - linux_build + - template: templates/nix-test.yml + parameters: + name: Linux + pool: ubuntu-16.04 + purpose: UnelevatedPesterTests + tagSet: Others -- template: templates/verify-xunit.yml - parameters: - pool: ubuntu-16.04 - parentJobs: - - linux_build + - template: templates/nix-test.yml + parameters: + name: Linux + pool: ubuntu-16.04 + purpose: ElevatedPesterTests + tagSet: Others -- job: CodeCovTestPackage + - template: templates/verify-xunit.yml + parameters: + pool: ubuntu-16.04 + +- stage: CodeCovTestPackage displayName: CodeCoverage and Test Packages - steps: - - powershell: | - Import-Module .\tools\ci.psm1 - New-CodeCoverageAndTestPackage - displayName: CodeCoverage and Test Package + dependsOn: [] # by specifying an empty array, this stage doesn't depend on the stage before it + jobs: + - job: CodeCovTestPackage + displayName: CodeCoverage and Test Packages + pool: + vmImage: ubuntu-16.04 + steps: + - pwsh: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + displayName: CodeCoverage and Test Package diff --git a/.vsts-ci/mac.yml b/.vsts-ci/mac.yml index ca4a66fc7e6..445c0e3f463 100644 --- a/.vsts-ci/mac.yml +++ b/.vsts-ci/mac.yml @@ -25,10 +25,11 @@ pr: include: - '*' exclude: - - /tools/releaseBuild/**/* - /.vsts-ci/misc-analysis.yml - /.github/ISSUE_TEMPLATE/* - /.dependabot/config.yml + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* variables: DOTNET_CLI_TELEMETRY_OPTOUT: 1 @@ -42,51 +43,54 @@ variables: resources: - repo: self clean: true -jobs: -- template: templates/ci-build.yml - parameters: - pool: macOS-latest - jobName: mac_build - displayName: macOS Build -- template: templates/nix-test.yml - parameters: - purpose: UnelevatedPesterTests - tagSet: CI - parentJobs: - - mac_build +stages: +- stage: BuildMac + displayName: Build for macOS + jobs: + - template: templates/ci-build.yml + parameters: + pool: macOS-latest + jobName: mac_build + displayName: macOS Build + +- stage: TestMac + displayName: Test for macOS + jobs: + - template: templates/nix-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: CI -- template: templates/nix-test.yml - parameters: - purpose: ElevatedPesterTests - tagSet: CI - parentJobs: - - mac_build + - template: templates/nix-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: CI -- template: templates/nix-test.yml - parameters: - purpose: UnelevatedPesterTests - tagSet: Others - parentJobs: - - mac_build + - template: templates/nix-test.yml + parameters: + purpose: UnelevatedPesterTests + tagSet: Others -- template: templates/nix-test.yml - parameters: - purpose: ElevatedPesterTests - tagSet: Others - parentJobs: - - mac_build + - template: templates/nix-test.yml + parameters: + purpose: ElevatedPesterTests + tagSet: Others -- template: templates/verify-xunit.yml - parameters: - pool: macOS-latest - parentJobs: - - mac_build + - template: templates/verify-xunit.yml + parameters: + pool: macOS-latest -- job: CodeCovTestPackage +- stage: CodeCovTestPackage displayName: CodeCoverage and Test Packages - steps: - - powershell: | - Import-Module .\tools\ci.psm1 - New-CodeCoverageAndTestPackage - displayName: CodeCoverage and Test Package + dependsOn: [] # by specifying an empty array, this stage doesn't depend on the stage before it + jobs: + - job: CodeCovTestPackage + displayName: CodeCoverage and Test Packages + pool: + vmImage: macOS-latest + steps: + - pwsh: | + Import-Module .\tools\ci.psm1 + New-CodeCoverageAndTestPackage + displayName: CodeCoverage and Test Package diff --git a/.vsts-ci/misc-analysis.yml b/.vsts-ci/misc-analysis.yml index 0e4093b6f91..327e5528107 100644 --- a/.vsts-ci/misc-analysis.yml +++ b/.vsts-ci/misc-analysis.yml @@ -34,7 +34,7 @@ jobs: condition: succeededOrFailed() - powershell: | - Install-module pester -Scope CurrentUser -Force + Install-module Pester -Scope CurrentUser -Force -MaximumVersion 4.99 displayName: Install Pester condition: succeededOrFailed() @@ -68,3 +68,8 @@ jobs: } displayName: Run Common Tests condition: succeededOrFailed() + - task: ms.vss-governance-buildtask.governance-build-task-component-detection.ComponentGovernanceComponentDetection@0 + displayName: 'Component Detection' + inputs: + sourceScanPath: '$(Build.SourcesDirectory)' + snapshotForceEnabled: true diff --git a/.vsts-ci/sshremoting-tests.yml b/.vsts-ci/sshremoting-tests.yml new file mode 100644 index 00000000000..016f3bfddca --- /dev/null +++ b/.vsts-ci/sshremoting-tests.yml @@ -0,0 +1,86 @@ +name: PR-$(System.PullRequest.PullRequestNumber)-$(Date:yyyyMMdd)$(Rev:.rr) +trigger: + # Batch merge builds together while a merge build is running + batch: true + branches: + include: + - master + - release* + - feature* + paths: + include: + - '/src/System.Management.Automation/engine/*' + - '/test/SSHRemoting/*' +pr: + branches: + include: + - master + - release* + - feature* + paths: + include: + - '/src/System.Management.Automation/engine/*' + - '/test/SSHRemoting/*' + +variables: + DOTNET_CLI_TELEMETRY_OPTOUT: 1 + POWERSHELL_TELEMETRY_OPTOUT: 1 + # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + __SuppressAnsiEscapeSequences: 1 + +resources: +- repo: self + clean: true +jobs: +- job: SSHRemotingTests + container: mcr.microsoft.com/powershell/test-deps:ubuntu-18.04 + displayName: SSH Remoting Tests + + steps: + - pwsh: | + Get-ChildItem -Path env: + displayName: Capture Environment + condition: succeededOrFailed() + + - pwsh: Write-Host "##vso[build.updatebuildnumber]$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))" + displayName: Set Build Name for Non-PR + condition: ne(variables['Build.Reason'], 'PullRequest') + + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + + - pwsh: | + sudo apt-get update + sudo apt-get install -y git + displayName: Install Github + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall -SkipUser + displayName: Bootstrap + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Invoke-CIBuild + displayName: Build + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions + $options = (Get-PSOptions) + Import-Module .\test\tools\Modules\HelpersRemoting + Install-SSHRemoting -PowerShellFilePath $options.Output + displayName: Install SSH Remoting + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions + $options = (Get-PSOptions) + Import-Module .\build.psm1 + Start-PSPester -Path test/SSHRemoting -powershell $options.Output -OutputFile "$PWD/sshTestResults.xml" + displayName: Test + condition: succeeded() diff --git a/.vsts-ci/templates/nanoserver.yml b/.vsts-ci/templates/nanoserver.yml index d7575836f84..c989d01c2f8 100644 --- a/.vsts-ci/templates/nanoserver.yml +++ b/.vsts-ci/templates/nanoserver.yml @@ -34,7 +34,7 @@ jobs: continueOnError: true - pwsh: | - Install-module pester -Scope CurrentUser -Force + Install-module Pester -Scope CurrentUser -Force -MaximumVersion 4.99 displayName: 'Install Pester' continueOnError: true diff --git a/.vsts-ci/windows-daily.yml b/.vsts-ci/windows-daily.yml index c05b5735cb1..6a88011dff8 100644 --- a/.vsts-ci/windows-daily.yml +++ b/.vsts-ci/windows-daily.yml @@ -48,32 +48,125 @@ stages: - stage: TestWin displayName: Test for Windows + variables: + - group: CLR-CAP jobs: - - template: templates/windows-test.yml - parameters: - purpose: UnelevatedPesterTests - tagSet: CI + - job: win_test + pool: + vmImage: vs2017-win2016 + displayName: Windows Test - - template: templates/windows-test.yml - parameters: - purpose: ElevatedPesterTests - tagSet: CI + steps: + - pwsh: | + Get-ChildItem -Path env: + displayName: 'Capture Environment' + condition: succeededOrFailed() - - template: templates/windows-test.yml - parameters: - purpose: UnelevatedPesterTests - tagSet: Others + - task: DownloadBuildArtifacts@0 + displayName: 'Download Build Artifacts' + inputs: + downloadType: specific + itemPattern: | + build/**/* + xunit/**/* + downloadPath: '$(System.ArtifactsDirectory)' - - template: templates/windows-test.yml - parameters: - purpose: ElevatedPesterTests - tagSet: Others + - pwsh: | + Get-ChildItem "$(System.ArtifactsDirectory)\*" -Recurse + displayName: 'Capture Artifacts Directory' + continueOnError: true - - template: templates/verify-xunit.yml + - pwsh: | + $capRootDir = Join-Path ([System.IO.Path]::GetTempPath()) "CAP" + $capUtilDir = Join-Path $capRootDir "Utils" + + if (Test-Path $capRootDir) { Remove-Item $capRootDir -Recurse -Force } + New-Item $capUtilDir -ItemType Directory > $null + + $capZipFile = Join-Path $capRootDir "cap.zip" + Invoke-WebRequest -Uri https://pscoretestdata.blob.core.windows.net/dotnet-cap/windows.zip -OutFile $capZipFile + Unblock-File -Path $capZipFile + Expand-Archive -Path $capZipFile -DestinationPath $capUtilDir -Force + + Write-Host "=== Capture CAP Util Directory ===" + Get-ChildItem $capUtilDir -Recurse + + Write-Host "##vso[task.setvariable variable=CapRootDir]$capRootDir" + Write-Host "##vso[task.setvariable variable=CapUtilDir]$capUtilDir" + displayName: 'Download CAP package' + condition: succeededOrFailed() + + # must be run frow Windows PowerShell + - powershell: | + Import-Module .\tools\ci.psm1 + Invoke-CIInstall + displayName: Bootstrap + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\build.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + $path = Split-Path -Parent (Get-PSOutput -Options (Get-PSOptions)) + $rootPath = Split-Path -Path $path + Expand-Archive -Path '$(System.ArtifactsDirectory)\build\build.zip' -DestinationPath $rootPath -Force + displayName: 'Unzip Build' + condition: succeeded() + + - pwsh: | + Import-Module $(CapUtilDir)\CAPService.psm1 + $dataDir = Start-TraceCollection -RootDir $(CapRootDir) + Write-Host "##vso[task.setvariable variable=CapDataDir]$dataDir" + displayName: 'Start CLR Trace Collection' + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose UnelevatedPesterTests -TagSet CI + displayName: Test - UnelevatedPesterTests - CI + condition: succeeded() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose ElevatedPesterTests -TagSet CI + displayName: Test - ElevatedPesterTests - CI + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose UnelevatedPesterTests -TagSet Others + displayName: Test - UnelevatedPesterTests - Others + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\tools\ci.psm1 + Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' + Invoke-CITest -Purpose ElevatedPesterTests -TagSet Others + displayName: Test - ElevatedPesterTests - Others + condition: succeededOrFailed() + + - pwsh: | + Import-Module .\build.psm1 + $xUnitTestResultsFile = '$(System.ArtifactsDirectory)\xunit\xUnitTestResults.xml' + Test-XUnitTestResults -TestResultsFile $xUnitTestResultsFile + displayName: Verify xUnit Test Results + condition: succeededOrFailed() + + - pwsh: | + $capDataDir = '$(CapDataDir)' + $capModuleFile = '$(CapUtilDir)\CAPService.psm1' + + if ((Test-Path $capModuleFile) -and (Test-Path $capDataDir)) { + Import-Module $capModuleFile + Stop-TraceCollection -DataDir $capDataDir -RepoRoot $pwd -IngressToken '$(CapIngressToken)' + } + displayName: 'Upload CLR Trace' + condition: always() - stage: PackagingWin displayName: Packaging for Windows jobs: # Unlike daily builds, we do not upload nuget package to MyGet so we do not wait on tests to finish. - template: templates/windows-packaging.yml - diff --git a/.vsts-ci/windows.yml b/.vsts-ci/windows.yml index 81e74dcbc77..11bccbbbfa6 100644 --- a/.vsts-ci/windows.yml +++ b/.vsts-ci/windows.yml @@ -27,6 +27,8 @@ pr: - /.vsts-ci/misc-analysis.yml - /.github/ISSUE_TEMPLATE/* - /.dependabot/config.yml + - tools/releaseBuild/* + - tools/releaseBuild/azureDevOps/templates/* variables: GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" diff --git a/ADOPTERS.md b/ADOPTERS.md index 56ea9850a7d..182d36dd37f 100644 --- a/ADOPTERS.md +++ b/ADOPTERS.md @@ -17,7 +17,7 @@ This is a list of adopters of using PowerShell in production or in their product More information about Azure Cloud Shell is available at [Azure Cloud Shell Overview.](https://docs.microsoft.com/azure/cloud-shell/overview) * [Azure Functions - PowerShell](https://github.com/Azure/azure-functions-powershell-worker) is a serverless compute service to execute PowerShell scripts in the cloud without worrying about managing resources. In addition, Azure Functions provides client tools such as [`Az.Functions`](https://www.powershellgallery.com/packages/Az.Functions), a cross-platform PowerShell module to manage function apps and service plans in the cloud. - For more information about Functions, please visit [functions overview](https://docs.microsoft.com/en-us/azure/azure-functions/functions-overview). + For more information about Functions, please visit [functions overview](https://docs.microsoft.com/azure/azure-functions/functions-overview). * [PowerShell Universal Dashboard](https://ironmansoftware.com/powershell-universal-dashboard) is a cross-platform web framework for PowerShell. It provides the ability to create robust, interactive websites, REST APIs, and Electron-based desktop apps with PowerShell script. More information about PowerShell Universal Dashboard is available at the [PowerShell Universal Dashboard Docs](https://docs.universaldashboard.io). @@ -25,5 +25,12 @@ This is a list of adopters of using PowerShell in production or in their product Enable non-admins like help desk and tier 1 support teams to execute secure web based tools on any platform `without admin rights`. Configure flexible RBAC permissions from an intuitive interface, without a complex learning curve. Script output along with all actions are audited. Manage up to 5,000 nodes for free with the [Community Edition](https://systemfrontier.com/solutions/community-edition/). +* [Amazon AWS](https://aws.com) supports PowerShell in a wide variety of its products including [AWS tools for PowerShell](https://github.com/aws/aws-tools-for-powershell), + [AWS Lambda Support For PowerShell](https://github.com/aws/aws-lambda-dotnet/tree/master/PowerShell) and [AWS PowerShell Tools for `CodeBuild`](https://docs.aws.amazon.com/powershell/latest/reference/items/CodeBuild_cmdlets.html) + as well as supporting PowerShell Core in both Windows and Linux EC2 Images. * [Azure Resource Manager Deployment Scripts](https://docs.microsoft.com/azure/azure-resource-manager/templates/deployment-script-template) Complete the "last mile" of your Azure Resource Manager (ARM) template deployments with a Deployment Script, which enables you to run an arbitrary PowerShell script in the context of a deployment. Designed to let you complete tasks that should be part of a deployment, but are not possible in an ARM template today — for example, creating a Key Vault certificate or querying an external API for a new CIDR block. +* [Azure Pipelines Hosted Agents](https://docs.microsoft.com/azure/devops/pipelines/agents/hosted?view=azure-devops) Windows, Ubuntu, and MacOS Agents used by Azure Pipelines customers have PowerShell pre-installed so that customers can make use of it for all their CI/CD needs. +* [GitHub Actions Virtual-Environments for Hosted Runners](https://help.github.com/actions/reference/virtual-environments-for-github-hosted-runners) Windows, Ubuntu, and MacOS virtual environments used by customers of GitHub Actions include Powershell out of the box. +* [Microsoft HoloLens](https://www.microsoft.com/hololens) makes extensive use of PowerShell 7+ throughout the development cycle to automate tasks such as firmware assembly and automated testing. +* [Windows 10 IoT Core](https://docs.microsoft.com/windows/iot-core/windows-iot-core) is a small form factor Windows edition for IoT devices and now you can easily include the [PowerShell package](https://github.com/ms-iot/iot-adk-addonkit/blob/master/Tools/IoTCoreImaging/Docs/Import-PSCoreRelease.md#Import-PSCoreRelease) in your imaging process. diff --git a/CHANGELOG/6.0.md b/CHANGELOG/6.0.md index 23a486203d7..b5993b5be30 100644 --- a/CHANGELOG/6.0.md +++ b/CHANGELOG/6.0.md @@ -565,7 +565,7 @@ work is required for Microsoft to continue to sign and release packages from the PowerShell 6.0 will be exclusively built on top of CoreCLR, so we are removing a large amount of code that's built only for FullCLR. -To read more about this, check out [this blog post](https://blogs.msdn.microsoft.com/powershell/2017/07/14/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). +To read more about this, check out [this blog post](https://devblogs.microsoft.com/powershell/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). ## [6.0.0-beta.5] - 2017-08-02 @@ -623,7 +623,7 @@ To read more about this, check out [this blog post](https://blogs.msdn.microsoft PowerShell 6.0 will be exclusively built on top of CoreCLR, so we are removing a large amount of code that's built only for FullCLR. -To read more about this, check out [this blog post](https://blogs.msdn.microsoft.com/powershell/2017/07/14/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). +To read more about this, check out [this blog post](https://devblogs.microsoft.com/powershell/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). ## [6.0.0-beta.4] - 2017-07-12 @@ -736,7 +736,7 @@ For more information on this, we invite you to read [this blog post explaining P - Once the pipeline is running as a job, all of the standard `*-Job` cmdlets can be used to manage the job. - Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so `Copy-Item $foo $bar &` just works. - The job is also run in the current directory instead of the user's home directory. -- For more information about PowerShell jobs, see [about_Jobs](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-6). +- For more information about PowerShell jobs, see [about_Jobs](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_jobs). ### Engine updates and fixes @@ -767,7 +767,7 @@ For more information on this, we invite you to read [this blog post explaining P PowerShell Core has moved to using .NET Core 2.0 so that we can leverage all the benefits of .NET Standard 2.0. (#3556) To learn more about .NET Standard 2.0, there's some great starter content [on Youtube](https://www.youtube.com/playlist?list=PLRAdsfhKI4OWx321A_pr-7HhRNk7wOLLY), -on [the .NET blog](https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/), +on [the .NET blog](https://devblogs.microsoft.com/dotnet/introducing-net-standard/), and [on GitHub](https://github.com/dotnet/standard/blob/master/docs/faq.md). We'll also have more content soon in our [repository documentation](https://github.com/PowerShell/PowerShell/tree/master/docs) (which will eventually make its way to [official documentation](https://github.com/powershell/powershell-docs)). In a nutshell, .NET Standard 2.0 allows us to have universal, portable modules between Windows PowerShell (which uses the full .NET Framework) and PowerShell Core (which uses .NET Core). @@ -782,7 +782,7 @@ Many modules and cmdlets that didn't work in the past may now work on .NET Core, If you want to opt-out of this telemetry, simply delete `$PSHome\DELETE_ME_TO_DISABLE_CONSOLEHOST_TELEMETRY`. Even before the first run of Powershell, deleting this file will bypass all telemetry. In the future, we plan on also enabling a configuration value for whatever is approved as part of [RFC0015](https://github.com/PowerShell/PowerShell-RFC/blob/master/X-Rejected/RFC0015-PowerShell-StartupConfig.md). -We also plan on exposing this telemetry data (as well as whatever insights we leverage from the telemetry) in [our community dashboard](https://blogs.msdn.microsoft.com/powershell/2017/01/31/powershell-open-source-community-dashboard/). +We also plan on exposing this telemetry data (as well as whatever insights we leverage from the telemetry) in [our community dashboard](https://devblogs.microsoft.com/powershell/powershell-open-source-community-dashboard/). If you have any questions or comments about our telemetry, please file an issue. diff --git a/CHANGELOG/6.2.md b/CHANGELOG/6.2.md index 2aca4fc7475..23f3e4e3518 100644 --- a/CHANGELOG/6.2.md +++ b/CHANGELOG/6.2.md @@ -1,6 +1,23 @@ # 6.2 Changelog -## v6.2.4 - 01/27/2020 +## [6.2.5] - 2020-05-14 + +### Build and Packaging Improvements + +
+ +
    +
  • Port back the code for new changelog format.
  • +
  • Work around FPM issue with a specific version on macOS
  • +
  • Update the combined package build to release the daily builds (#10449)
  • +
  • Refactor packaging pipeline (#11852)
  • +
  • Bump .NET SDK version to the version 2.1.18
  • +
  • Move to standard internal pool for building (#12119)
  • +
+ +
+ +## [6.2.4] - 2020-01-27 ### General Cmdlet Updates and Fixes @@ -794,6 +811,8 @@ - Update `CONTRIBUTION.md` about adding an empty line after the copyright header (#7706) (Thanks @iSazonov!) - Update docs about .NET Core version `2.0` to be about version `2.x` (#7467) (Thanks @bergmeister!) +[6.2.5]: https://github.com/PowerShell/PowerShell/compare/v6.2.4...v6.2.5 +[6.2.4]: https://github.com/PowerShell/PowerShell/compare/v6.2.3...v6.2.4 [6.2.3]: https://github.com/PowerShell/PowerShell/compare/v6.2.2...v6.2.3 [6.2.2]: https://github.com/PowerShell/PowerShell/compare/v6.2.1...v6.2.2 [6.2.1]: https://github.com/PowerShell/PowerShell/compare/v6.2.0...v6.2.1 diff --git a/CHANGELOG/7.0.md b/CHANGELOG/7.0.md new file mode 100644 index 00000000000..380a258becc --- /dev/null +++ b/CHANGELOG/7.0.md @@ -0,0 +1,1012 @@ +# 7.0 Changelog + +## [7.0.1] - 2020-05-14 + +### Engine Updates and Fixes + +- Discover assemblies loaded by `Assembly.Load(byte[])` and `Assembly.LoadFile` (#12203) +- Allow case insensitive paths for determining `PSModulePath` (#12192) + +### General Cmdlet Updates and Fixes + +- Add `null` check for Windows PowerShell install path (#12296) +- Fix Null Reference error in CSV commands (#12281) (Thanks @iSazonov!) +- Fix `WinCompat` module loading to treat Core edition modules higher priority (#12269) +- Fix `` detection regex in web cmdlets (#12099) (Thanks @vexx32!) +- Miscellaneous minor updates to `WinCompat` (#11980) +- Fix `ConciseView` where error message is wider than window width and doesn't have whitespace (#11880, #11746) +- Make `Test-Connection` always use the default synchronization context for sending ping requests (#11517) + +### Tests + +- Fix CIM tab complete test failure (#12636) + +### Build and Packaging Improvements + +
+ + +Move to .NET Core 3.1.202 SDK and update packages. + + +
    +
  • Use dotnet core 3.1.202 (Internal 11551)
  • +
  • Bump PowerShellGet from 2.2.3 to 2.2.4 (#12342)
  • +
  • Move to standard internal pool for building (#12119)
  • +
  • Bump NJsonSchema from 10.1.5 to 10.1.7 (#12050)
  • +
+ +
+ +### Documentation and Help Content + +- Remove the version number of PowerShell from `LICENSE` (#12019) + +## [7.0.0] - 2020-03-04 + +### General Cmdlet Updates and Fixes + +- Enable `Ctrl+C` to work for global tool (#11959) +- Fix `ConciseView` to not show the line information within the error messages (#11952) + +### Build and Packaging Improvements + +- Publish PowerShell into the Windows engineering system package format (#11960) +- Bump .NET core framework to `3.1.2` (#11963) +- Ensure the man page `gzip` has the correct name for LTS release (#11956) +- Bump `Microsoft.ApplicationInsights` from `2.13.0` to `2.13.1` (#11925) + +## [7.0.0-rc.3] - 2020-02-21 + +### Breaking Changes + +- Fix `Invoke-Command` missing error on session termination (#11586) + +### Engine Updates and Fixes + +- Update the map between console color to `VT` sequences (#11891) +- Fix SSH remoting error on Windows platform (#11907) +- Restore the `PowerShellStreamType` `enum` with an `ObsoleteAttribute` (#11836) +- Handle cases where `CustomEvent` was not initially sent (#11807) +- Fix how COM objects are enumerated (#11795) +- Fix `NativeDllHandler` to not throw when file is not found (#11787) +- Restore `SetBreakpoints` API (#11622) +- Do not needlessly pass `-l login_name` or `-p port` to `ssh` (#11518) (Thanks @LucaFilipozzi!) +- Fix for `JEA` user role in virtual account (#11668) +- Do not resolve types from assemblies that are loaded in separate `AssemblyLoadContext` (#11088) + +### General Cmdlet Updates and Fixes + +- Sync current directory in `WinCompat` remote session (#11809) +- Add `WinCompat` deny list support using a setting in `powershell.config.json` (#11726) +- Fix unnecessary trimming of line resulting in incorrect index with `ConciseView` (#11670) + +### Code Cleanup + +- Change name of `ClrVersion` parameter back to revert change in capitalization (#11623) + +### Tools + +- Update changelog generation script (#11736) (Thanks @xtqqczze!) +- Update to `CredScan v2` (#11765) + +### Tests + +- Make sure to test whether we skip a test using consistent logic (#11892) +- Skip directory creation at root test on macOS (#11878) +- Update `Get-PlatformInfo` helper and tests for Debian 10, 11 and CentOS 8 (#11842) +- Ensure correct `pwsh` is used for test runs (#11486) (Thanks @iSazonov!) + +### Build and Packaging Improvements + +- Add `LTSRelease` value from `metadata.json` to `release.json` (#11897) +- Bump `Microsoft.ApplicationInsights` from `2.12.1` to `2.13.0` (#11894) +- Make LTS package always not a preview (#11895) +- Bump `System.Data.SqlClient` from `4.8.0` to `4.8.1` (#11879) +- Change `LTSRelease` value in `metadata.json` to true for `RC.3` release (Internal 10960) +- Update `LTS` logic to depend on `metadata.json` (#11877) +- Set default value of `LTSRelease` to false (#11874) +- Refactor packaging pipeline (#11852) +- Make sure `LTS` packages have symbolic links for `pwsh` and `pwsh-lts` (#11843) +- Bump `Microsoft.PowerShell.Native` from `7.0.0-rc.2` to `7.0.0` (#11839) +- Update the NuGet package generation to include `cimcmdlet.dll` and most of the built-in modules (#11832) +- Bump `Microsoft.PowerShell.Archive` from `1.2.4.0` to `1.2.5` (#11833) +- Bump `PSReadLine` from `2.0.0-rc2` to `2.0.0` (#11831) +- Add trace source and serialization primitives to the allowed assembly list (Internal 10911) +- Update the `NextReleaseTag` to be v7.0.0-preview.7 (#11372) +- Change packaging to produce `LTS` packages (#11772) +- Build tar packages only when building on Ubuntu (#11766) +- Bump `NJsonSchema` from `10.1.4` to `10.1.5` (#11730) +- Fix symbolic link creation in `packaging.psm1` (#11723) +- Bump `Microsoft.ApplicationInsights` from `2.12.0` to `2.12.1` (#11708) +- Bump `NJsonSchema` from `10.1.3` to `10.1.4` (#11620) +- Move to latest Azure DevOps agent images (#11704) +- Bump `Markdig.Signed` from `0.18.0` to `0.18.1` (#11641) + +### Documentation and Help Content + +- Add links to diffs on Github in changelog (#11652) (Thanks @xtqqczze!) +- Fix markdown-link test failure (#11653) (Thanks @xtqqczze!) + +## [7.0.0-rc.2] - 2020-01-16 + +### Breaking Changes +- Use `ISOWeek` for week numbers in `Get-Date` accounting for leap years #11536 (Thanks @paalbra!) + +### Engine Updates and Fixes +- Revert the PRs that made `DBNull.Value` and `NullString.Value` treated as `$null` (#11584) +- Support expanding `~` in `$env:PATH` when doing command discovery (#11552) +- Skip null data in output data received handler to fix a `NullReferenceException` (#11448) (Thanks @iSazonov!) +- Add `ssh` parameter sets for the parameter `-JobName` in `Invoke-Command` (#11444) +- Adding `PowerShell Editor Services` and `PSScriptAnalyzer` to tracked modules (#11514) +- Fix key exchange hang with `SecureString` for the `OutOfProc` transports (#11380, #11406) +- Add setting to disable the implicit `WinPS` module loading (#11332) + +### General Cmdlet Updates and Fixes +- Fix `NullReferenceException` in `ConciseView` (#11435) (Thanks @iSazonov!) +- Remove the default value of `$true` for the parameter `-RequireLicenseAcceptance` in `New-ModuleManifest` (#11512) (Thanks @ThomasNieto!) +- Make Web Cmdlets skip processing the content headers with a null or empty value for backward compatibility (#11421) (Thanks @spongemike2!) +- Don't format exceptions that are not `ErrorRecord` objects (#11415) +- Mark `InitialSessionState.ImportPSSnapIn` as Obsolete (#11399) +- Use `PositionMessage` for the line context information for `ConciseView` (#11398) +- Add trailing line number to `filename` for `ConciseView` (#11391) +- Update `HelpInfoUri` for all modules in PowerShell 7.0 (#11389) +- Remove unnecessary newline in `ConciseView` (#11383) +- Move `Set-StrictMode` to the outer script block for `ErrorView` (#11381) +- Remove the declaration of `Get-Error` experimental feature from module manifest (#11369) +- Update error message if `Update-Help` fails for the current `UICulture` (#11356) +- `Test-Connection`: Fallback to hop IP Address on `-Traceroute` without `-ResolveDestination` (#11335) (Thanks @vexx32!) +- Add null host name check in `WSMan` (#11288) (Thanks @iSazonov!) +- Add `Type` member to exceptions containing type of exception for `Get-Error` (#11076) +- Write an error if argument is a directory in `Get-FileHash` cmdlet (#11114) (Thanks @iSazonov!) +- Update `Get-Error` to not modify the original `$Error` object (#11125) + +### Code Cleanup +- Use .NET code to check for processor architecture instead of P/Invoke (#11046) (Thanks @iSazonov!) + +### Tests +- Test fixes for various platforms (#11579, #11541) +- Various test fixes for debugger and remoting (#11528) +- `DSC` test fixes for `Alpine` and `Raspbian` (#11508) +- Normalize line endings before comparing string in tests (#11499) +- Fix `ssh` remoting test to work on all platforms (#11500) +- Build test artifacts for `Alpine` (#11483) +- Make null member access tests as string to avoid parsing errors (#11385) +- Fix test failing when `UnixStat` feature is disabled (#11370) +- Update hosting tests to use the SDK version from the build property (#11368) +- Add retry to `Enter-PSHostProcess` test (#11360) + +### Build and Packaging Improvements +- Bump `Microsoft.PowerShell.Native` from `7.0.0-rc.1` to `7.0.0.rc.2` (#11583) +- Update .NET SDK version to 3.1.101 (#11582) +- Bump `PSReadLine` from `2.0.0-rc1` to `2.0.0-rc2` (#11581) +- Bump `NJsonSchema` from `10.0.28` to `10.1.3` (#11382, #11573) +- Generate the correct reference assembly for `Microsoft.PowerShell.ConsoleHost` NuGet package (#11545) +- Update building of `MSIX` for `RC` to use 100 range revision (#11526) +- Fix symbolic links on Debian 10 packages (#11474) +- Bump `Microsoft.PowerShell.Archive` from `1.2.3.0` to `1.2.4.0` (#11502) +- Add script to rebuild `WIX` component references (#11485) +- Bump `PackageManagement` from `1.4.5` to `1.4.6` (#11427) +- Bump `PowerShellGet` from `2.2.2` to `2.2.3` (#11426) +- Bump `ThreadJob` from `2.0.2` to `2.0.3` (#11416) +- Fix symbolic links to `libs` on Debian 10 (#11390) +- Improve Ubuntu detection for Ubuntu derivatives like `GalliumOS` etc (#11155) + +### Documentation and Help Content +- Fix broken link in debugging `README.md` (#11503) + +## [7.0.0-rc.1] - 2019-12-16 + +### Breaking Changes +- Make update notification support `LTS` and default channels (#11132) + +### Engine Updates and Fixes +- Improvements in breakpoint APIs for remote scenarios (#11312) +- Fix PowerShell class definition leaking into another Runspace (#11273) +- Fix a regression in formatting caused by the `FirstOrDefault` primitive added in `7.0.0-Preview1` (#11258) +- Additional Microsoft Modules to track in `PS7` Telemetry (#10751) +- Make approved features non-experimental (#11303) +- Update `ConciseView` to use `TargetObject` if applicable (#11075) +- Fix `NullReferenceException` in `CompletionCompleters` public methods (#11274) +- Fix apartment thread state check on non-Windows platforms (#11301) +- Update setting `PSModulePath` to concatenate the process and machine environment variables (#11276) +- Bump `.NET Core` to `3.1.0` (#11260) +- Fix detection of `$PSHOME` in front of `$env:PATH` (#11141) + +### General Cmdlet Updates and Fixes +- Fix for issue on Raspbian for setting date of file changes in `UnixStat` Experimental Feature (#11313) +- Add `-AsPlainText` to `ConvertFrom-SecureString` (#11142) +- Added `WindowsPS` version check for `WinCompat` (#11148) +- Fix error-reporting in some `WinCompat` scenarios (#11259) +- Add native binary resolver (#11032) (Thanks @iSazonov!) +- Update calculation of char width to respect `CJK` chars correctly (#11262) +- Add `Unblock-File` for macOS (#11137) +- Fix regression in `Get-PSCallStack` (#11210) (Thanks @iSazonov!) +- Avoid automatically loading the `ScheduledJob` module when using Job cmdlets (#11194) +- Add `OutputType` to `Get-Error` cmdlet and preserve original `TypeNames` (#10856) +- Fix null reference in `SupportsVirtualTerminal` property (#11105) + +### Code Cleanup +- Change comment and element text to meet Microsoft standards (#11304) + +### Tests +- Make unreliable `DSC` test pending (#11131) + +### Build and Packaging Improvements +- Fix Nuget package signing for Coordinated Package build (#11316) +- Update dependencies from PowerShell Gallery and NuGet (#11323) +- Bump `Microsoft.ApplicationInsights` from `2.11.0` to `2.12.0` (#11305) +- Bump `Microsoft.CodeAnalysis.CSharp` from `3.3.1` to `3.4.0` (#11265) +- Updates packages for Debian 10 and 11 (#11236) +- Only enable experimental features prior to `RC` (#11162) +- Update macOS minimum version (#11163) +- Bump `NJsonSchema` from `10.0.27` to `10.0.28` (#11170) + +### Documentation and Help Content +- Refactor change logs into one log per release (#11165) +- Fix `FWLinks` for PowerShell 7 online help documents (#11071) + +## [7.0.0-preview.6] - 2019-11-21 + +### Breaking Changes + +- Update `Test-Connection` to work more like the one in Windows PowerShell (#10697) (Thanks @vexx32!) +- Preserve `$?` for `ParenExpression`, `SubExpression` and `ArrayExpression` (#11040) +- Set working directory to current directory in `Start-Job` (#10920) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Allow `pwsh` to inherit `$env:PSModulePath` and enable `powershell.exe` to start correctly (#11057) + +### Experimental Features + +- Provide Unix stat information in filesystem output (#11042) +- Support null-conditional operators `?.` and `?[]` in PowerShell language (#10960) +- Support using non-compatible Windows PowerShell modules in PowerShell Core (#10973) + +### Performance + +- Avoid using closure in `Parser.SaveError` (#11006) +- Improve the caching when creating new `Regex` instances (#10657) (Thanks @iSazonov!) +- Improve processing of the PowerShell built-in type data from `types.ps1xml`, `typesV3.ps1xml` and `GetEvent.types.ps1xml` (#10898) +- Update `PSConfiguration.ReadValueFromFile` to make it faster and more memory efficient (#10839) + +### General Cmdlet Updates and Fixes + +- Add limit check in `Get-WinEvent` (#10648) (Thanks @iSazonov!) +- Fix command runtime so `StopUpstreamCommandsException` doesn't get populated in `-ErrorVariable` (#10840) +- Set the output encoding to `[Console]::OutputEncoding` for native commands (#10824) +- Support multi-line code blocks in examples (#10776) (Thanks @Greg-Smulko!) +- Add Culture parameter to `Select-String` cmdlet (#10943) (Thanks @iSazonov!) +- Fix `Start-Job` working directory path with trailing backslash (#11041) +- `ConvertFrom-Json`: Unwrap collections by default (#10861) (Thanks @danstur!) +- Use case-sensitive Hashtable for `Group-Object` cmdlet with `-CaseSensitive` and `-AsHashtable` switches (#11030) (Thanks @vexx32!) +- Handle exception if enumerating files fails when rebuilding path to have correct casing (#11014) +- Fix `ConciseView` to show `Activity` instead of `myCommand` (#11007) +- Allow web cmdlets to ignore HTTP error statuses (#10466) (Thanks @vdamewood!) +- Fix piping of more than one `CommandInfo` to `Get-Command` (#10929) +- Add back `Get-Counter` cmdlet for Windows (#10933) +- Make `ConvertTo-Json` treat `[AutomationNull]::Value` and `[NullString]::Value` as `$null` (#10957) +- Remove brackets from `ipv6` address for SSH remoting (#10968) +- Fix crash if command sent to pwsh is just whitespace (#10977) +- Added cross-platform `Get-Clipboard` and `Set-Clipboard` (#10340) +- Fix setting original path of filesystem object to not have extra trailing slash (#10959) +- Support `$null` for `ConvertTo-Json` (#10947) +- Add back `Out-Printer` command on Windows (#10906) +- Fix `Start-Job -WorkingDirectory` with whitespace (#10951) +- Return default value when getting `null` for a setting in `PSConfiguration.cs` (#10963) (Thanks @iSazonov!) +- Handle IO exception as non-terminating (#10950) +- Add `GraphicalHost` assembly to enable `Out-GridView`, `Show-Command`, and `Get-Help -ShowWindow` (#10899) +- Take `ComputerName` via pipeline in `Get-HotFix` (#10852) (Thanks @kvprasoon!) +- Fix tab completion for parameters so that it shows common parameters as available (#10850) +- Fix `GetCorrectCasedPath()` to first check if any system file entries is returned before calling `First()` (#10930) +- Set working directory to current directory in `Start-Job` (#10920) (Thanks @iSazonov!) +- Change `TabExpansion2` to not require `-CursorColumn` and treat as `$InputScript.Length` (#10849) +- Handle case where Host may not return Rows or Columns of screen (#10938) +- Fix use of accent colors for hosts that don't support them (#10937) +- Add back `Update-List` command (#10922) +- Update `FWLink` Id for `Clear-RecycleBin` (#10925) +- During tab completion, skip file if can't read file attributes (#10910) +- Add back `Clear-RecycleBin` for Windows (#10909) +- Add `$env:__SuppressAnsiEscapeSequences` to control whether to have VT escape sequence in output (#10814) + +### Code Cleanup + +- Cleanup style issues in `Compiler.cs` (#10368) (Thanks @iSazonov!) +- Remove the unused type converter for `CommaDelimitedStringCollection` (#11000) (Thanks @iSazonov!) +- Cleanup style in `InitialSessionState.cs` (#10865) (Thanks @iSazonov!) +- Code clean up for `PSSession` class (#11001) +- Remove the not-working 'run `Update-Help` from `Get-Help` when `Get-Help` runs for the first time' feature (#10974) +- Fix style issues (#10998) (Thanks @iSazonov!) +- Cleanup: use the built-in type alias (#10882) (Thanks @iSazonov!) +- Remove the unused setting key `ConsolePrompting` and avoid unnecessary string creation when querying `ExecutionPolicy` setting (#10985) +- Disable update notification check for daily builds (#10903) (Thanks @bergmeister!) +- Reinstate debugging API lost in #10338 (#10808) + +### Tools + +- Add default setting for the `SDKToUse` property so that it builds in VS (#11085) +- `Install-Powershell.ps1`: Add parameter to use MSI installation (#10921) (Thanks @MJECloud!) +- Add basic examples for `install-powershell.ps1` (#10914) (Thanks @kilasuit!) + +### Tests + +- Fix `stringdata` test to correctly validate keys of hashtables (#10810) +- Unload test modules (#11061) (Thanks @iSazonov!) +- Increase time between retries of testing URL (#11015) +- Update tests to accurately describe test actions. (#10928) (Thanks @romero126!) + +### Build and Packaging Improvements + +- Updating links in `README.md` and `metadata.json` for Preview.5 (#10854) +- Select the files for compliance tests which are owned by PowerShell (#10837) +- Allow `win7x86` `msix` package to build. (Internal 10515) +- Allow semantic versions to be passed to `NormalizeVersion` function (#11087) +- Bump .NET core framework to `3.1-preview.3` (#11079) +- Bump `PSReadLine` from `2.0.0-beta5` to `2.0.0-beta6` in /src/Modules (#11078) +- Bump `Newtonsoft.Json` from `12.0.2` to `12.0.3` (#11037) (#11038) +- Add Debian 10, 11 and CentOS 8 packages (#11028) +- Upload `Build-Info` Json file with the `ReleaseDate` field (#10986) +- Bump .NET core framework to `3.1-preview.2` (#10993) +- Enable build of x86 MSIX package (#10934) +- Update the dotnet SDK install script URL in `build.psm1` (#10927) +- Bump `Markdig.Signed` from `0.17.1` to `0.18.0` (#10887) +- Bump `ThreadJob` from `2.0.1` to `2.0.2` (#10886) +- Update `AppX` Manifest and Packaging module to conform to MS Store requirements (#10878) + +### Documentation and Help Content + +- Update `CONTRIBUTING.md` (#11096) (Thanks @mklement0!) +- Fix installation doc links in `README.md` (#11083) +- Adds examples to `install-powershell.ps1` script (#11024) (Thanks @kilasuit!) +- Fix to `Select-String` emphasis and `Import-DscResource` in CHANGELOG.md (#10890) +- Remove the stale link from `powershell-beginners-guide.md` (#10926) + +## [7.0.0-preview.5] - 2019-10-23 + +### Breaking Changes + +- Make `$PSCulture` consistently reflect in-session culture changes (#10138) (Thanks @iSazonov!) + +### Engine Updates and Fixes + +- Move to `.NET Core 3.1 preview 1` (#10798) +- Refactor reparse tag checks in file system provider (#10431) (Thanks @iSazonov!) +- Replace `CR` and new line with a `0x23CE` character in script logging (#10616) +- Fix a resource leak by unregistering the event handler from `AppDomain.CurrentDomain.ProcessExit` (#10626) + +### Experimental Features + +- Implement `Get-Error` cmdlet as Experimental Feature (#10727,#10800) +- Add `ConciseView` for `$ErrorView` and update it to remove unnecessary text and not color entire line in red (#10641,#10724) +- Support the pipeline chain operators `&&` and `||` in PowerShell language (#9849,#10825,#10836) +- Implement null coalescing (`??`) and null coalescing assignment (`??=`) operators (#10636) +- Support notification on `pwsh` startup when a new release is available and update notification message (#10689,#10777) + +### General Cmdlet Updates and Fixes + +- Add emphasis to `Select-String` output (with `-NoEmphasis` parameter to opt-out) (#8963) (Thanks @derek-xia!) +- Add back `Get-HotFix` cmdlet (#10740) +- Make `Add-Type` usable in applications that host `PowerShell` (#10587) +- Use more effective evaluation order in `LanguagePrimitives.IsNullLike()` (#10781) (Thanks @vexx32!) +- Improve handling of mixed-collection piped input and piped streams of input in `Format-Hex` (#8674) (Thanks @vexx32!) +- Use type conversion in `SSHConnection` hashtables when value doesn't match expected type (#10720) (Thanks @SeeminglyScience!) +- Fix `Get-Content -ReadCount 0` behavior when `-TotalCount` is set (#10749) (Thanks @eugenesmlv!) +- Reword access denied error message in `Get-WinEvent` (#10639) (Thanks @iSazonov!) +- Enable tab completion for variable assignment that is enum or type constrained (#10646) +- Remove unused `SourceLength` remoting property causing formatting issues (#10765) +- Add `-Delimiter` parameter to `ConvertFrom-StringData` (#10665) (Thanks @steviecoaster!) +- Add positional parameter for `ScriptBlock` when using `Invoke-Command` with `SSH` (#10721) (Thanks @machgo!) +- Show line context information if multiple lines but no script name for `ConciseView` (#10746) +- Add support for `\\wsl$\` paths to file system provider (#10674) +- Add the missing token text for `TokenKind.QuestionMark` in parser (#10706) +- Set current working directory of each `ForEach-Object -Parallel` running script to the same location as the calling script. (#10672) +- Replace `api-ms-win-core-file-l1-2-2.dll` with `Kernell32.dll` for `FindFirstStreamW` and `FindNextStreamW` APIs (#10680) (Thanks @iSazonov!) +- Tweak help formatting script to be more `StrictMode` tolerant (#10563) +- Add `-SecurityDescriptorSDDL` parameter to `New-Service` (#10483) (Thanks @kvprasoon!) +- Remove informational output, consolidate ping usage in `Test-Connection` (#10478) (Thanks @vexx32!) +- Read special reparse points without accessing them (#10662) (Thanks @iSazonov!) +- Direct `Clear-Host` output to terminal (#10681) (Thanks @iSazonov!) +- Add back newline for grouping with `Format-Table` and `-Property` (#10653) +- Remove [ValidateNotNullOrEmpty] from `-InputObject` on `Get-Random` to allow empty string (#10644) +- Make suggestion system string distance algorithm case-insensitive (#10549) (Thanks @iSazonov!) +- Fix null reference exception in `ForEach-Object -Parallel` input processing (#10577) + +### Code Cleanup + +- Remove `WorkflowJobSourceAdapter` reference that is no longer used (#10326) (Thanks @KirkMunro!) +- Cleanup `COM` interfaces in jump list code by fixing `PreserveSig` attributes (#9899) (Thanks @weltkante!) +- Add a comment describing why `-ia` is not the alias for `-InformationAction` common parameter (#10703) (Thanks @KirkMunro!) +- Rename `InvokeCommandCmdlet.cs` to `InvokeExpressionCommand.cs` (#10659) (Thanks @kilasuit!) +- Add minor code cleanups related to update notifications (#10698) +- Remove deprecated workflow logic from the remoting setup scripts (#10320) (Thanks @KirkMunro!) +- Update help format to use proper case (#10678) (Thanks @tnieto88!) +- Clean up `CodeFactor` style issues coming in commits for the last month (#10591) (Thanks @iSazonov!) +- Fix typo in description of `PSTernaryOperator` experimental feature (#10586) (Thanks @bergmeister!) + +### Performance + +- Add minor performance improvements for runspace initialization (#10569) (Thanks @iSazonov!) + +### Tools + +- Make `Install-PowerShellRemoting.ps1` handle empty string in `PowerShellHome` parameter (#10526) (Thanks @Orca88!) +- Switch from `/etc/lsb-release` to `/etc/os-release` in `install-powershell.sh` (#10773) (Thanks @Himura2la!) +- Check `pwsh.exe` and `pwsh` in daily version on Windows (#10738) (Thanks @centreboard!) +- Remove unneeded tap in `installpsh-osx.sh` (#10752) + +### Tests + +- Temporary skip the flaky test `TestAppDomainProcessExitEvenHandlerNotLeaking` (#10827) +- Make the event handler leaking test stable (#10790) +- Sync capitalization in `CI` `YAML` (#10767) (Thanks @RDIL!) +- Add test for the event handler leaking fix (#10768) +- Add `Get-ChildItem` test (#10507) (Thanks @iSazonov!) +- Replace ambiguous language for tests from `switch` to `parameter` for accuracy (#10666) (Thanks @romero126!) + +### Build and Packaging Improvements + +- Update package reference for `PowerShell SDK` to `preview.5` (Internal 10295) +- Update `ThirdPartyNotices.txt` (#10834) +- Bump `Microsoft.PowerShell.Native` to `7.0.0-preview.3` (#10826) +- Bump `Microsoft.ApplicationInsights` from `2.10.0` to `2.11.0` (#10608) +- Bump `NJsonSchema` from `10.0.24` to `10.0.27` (#10756) +- Add `MacPorts` support to the build system (#10736) (Thanks @Lucius-Q-User!) +- Bump `PackageManagement` from `1.4.4` to `1.4.5` (#10728) +- Bump `NJsonSchema` from `10.0.23` to `10.0.24` (#10635) +- Add environment variable to differentiate client/server telemetry in `MSI` (#10612) +- Bump `PSDesiredStateConfiguration` from `2.0.3` to `2.0.4` (#10603) +- Bump `Microsoft.CodeAnalysis.CSharp` from `3.2.1` to `3.3.1` (#10607) +- Update to `.Net Core 3.0 RTM` (#10604) (Thanks @bergmeister!) +- Update `MSIX` packaging so the version to `Windows Store` requirements (#10588) + +### Documentation and Help Content + +- Merge stable and servicing change logs (#10527) +- Update used `.NET` version in build docs (#10775) (Thanks @Greg-Smulko!) +- Replace links from `MSDN` to `docs.microsoft.com` in `powershell-beginners-guide.md` (#10778) (Thanks @iSazonov!) +- Fix broken `DSC` overview link (#10702) +- Update `Support_Question.md` to link to `Stack Overflow` as another community resource (#10638) (Thanks @mklement0!) +- Add processor architecture to distribution request template (#10661) +- Add new PowerShell MoL book to learning PowerShell docs (#10602) + +## [7.0.0-preview.4] - 2019-09-19 + +### Engine Updates and Fixes + +- Add support to `ActionPreference.Break` to break into debugger when `Debug`, `Error`, `Information`, `Progress`, `Verbose` or `Warning` messages are generated (#8205) (Thanks @KirkMunro!) +- Enable starting control panel add-ins within PowerShell Core without specifying `.CPL` extension. (#9828) + +### Performance + +- Make `ForEach-Object` faster for its commonly used scenarios (#10454) and fix `ForEach-Object -Parallel` performance problem with many runspaces (#10455) + +### Experimental Features + +- Update `PSDesiredStateConfiguration` module version to `2.0.3` and bring new tests; enable compilation to MOF on non-Windows and use of Invoke-DSCResource without LCM (#10516) +- Add APIs for breakpoint management in runspaces and enable attach to process without `BreakAll` for PowerShell Editor Services (#10338) (Thanks @KirkMunro!) +- Support [ternary operator](https://github.com/PowerShell/PowerShell-RFC/pull/218) in PowerShell language (#10367) + +### General Cmdlet Updates and Fixes + +- Add PowerShell Core group policy definitions (#10468) +- Update console host to support `XTPUSHSGR`/`XTPOPSGR` VT control sequences that are used in [composability scenarios](https://github.com/microsoft/terminal/issues/1796). (#10208) +- Add `WorkingDirectory` parameter to `Start-Job` (#10324) (Thanks @davinci26!) +- Remove the event handler that was causing breakpoint changes to be erroneously replicated to the host runspace debugger (#10503) (Thanks @KirkMunro!) +- Replace `api-ms-win-core-job-12-1-0.dll` with `Kernell32.dll` in `Microsoft.PowerShell.Commands.NativeMethods` P/Invoke API(#10417) (Thanks @iSazonov!) +- Fix wrong output for `New-Service` in variable assignment and `-OutVariable` (#10444) (Thanks @kvprasoon!) +- Fix global tool issues around exit code, command line parameters and path with spaces (#10461) +- Fix recursion into OneDrive - change `FindFirstFileEx()` to use `SafeFindHandle` type (#10405) +- Skip auto-loading `PSReadLine` on Windows if the [NVDA screen reader](https://www.nvaccess.org/about-nvda/) is active (#10385) +- Increase built-with-PowerShell module versions to `7.0.0.0` (#10356) +- Add throwing an error in `Add-Type` if a type with the same name already exists (#9609) (Thanks @iSazonov!) + +### Code Cleanup + +- Convert `ActionPreference.Suspend` enumeration value into a non-supported, reserved state, and remove restriction on using `ActionPreference.Ignore` in preference variables (#10317) (Thanks @KirkMunro!) +- Replace `ArrayList` with `List` to get more readable and reliable code without changing functionality (#10333) (Thanks @iSazonov!) +- Make code style fixes to `TestConnectionCommand` (#10439) (Thanks @vexx32!) +- Cleanup `AutomationEngine` and remove extra `SetSessionStateDrive` method call (#10416) (Thanks @iSazonov!) +- Rename default `ParameterSetName` back to `Delimiter` for `ConvertTo-Csv` and `ConvertFrom-Csv` (#10425) + +### Tools + +- Update `install-powershell.ps1` to check for already installed daily build (#10489) + +### Tests + +- Add experimental check to `ForEach-Object -Parallel` tests (#10354) (Thanks @KirkMunro!) +- Update tests for Alpine validation (#10428) + +### Build and Packaging Improvements + +- Bump `PowerShellGet` version from `2.2` to `2.2.1` (#10382) +- Bump `PackageManagement` version from `1.4.3` to `1.4.4` (#10383) +- Update `README.md` and `metadata.json` for `7.0.0-preview.4` (Internal 10011) +- Upgrade `.Net Core 3.0` version from `Preview 9` to `RC1` (#10552) (Thanks @bergmeister!) +- Fix `ExperimentalFeature` list generation (Internal 9996) +- Bump `PSReadLine` version from `2.0.0-beta4` to `2.0.0-beta5` (#10536) +- Fix release build script to set release tag +- Update version of `Microsoft.PowerShell.Native` to `7.0.0-preview.2` (#10519) +- Upgrade to `Netcoreapp3.0 preview9` (#10484) (Thanks @bergmeister!) +- Make sure the daily coordinated build, knows it is a daily build (#10464) +- Update the combined package build to release the daily builds (#10449) +- Remove appveyor reference (#10445) (Thanks @RDIL!) +- Bump `NJsonSchema` version from `10.0.22` to `10.0.23` (#10421) +- Remove the deletion of `linux-x64` build folder because some dependencies for Alpine need it (#10407) + +### Documentation and Help Content + +- Update `README.md` and metadata for `v6.1.6` and `v6.2.3` releases (#10523) +- Fix a typo in `README.md` (#10465) (Thanks @vedhasp!) +- Add a reference to `PSKoans` module to Learning Resources documentation (#10369) (Thanks @vexx32!) +- Update `README.md` and `metadata.json` for `7.0.0-preview.3` (#10393) + +## [7.0.0-preview.3] - 2019-08-20 + +### Breaking Changes + +- Remove `kill` alias for `Stop-Process` cmdlet on Unix (#10098) (Thanks @iSazonov!) +- Support for starting PowerShell as a login shell (`pwsh -Login` / `pwsh -l`) support (#10050) + +### Engine Updates and Fixes + +- Additional Telemetry - implementation of [`RFC0036`](https://github.com/PowerShell/PowerShell-RFC/pull/158) (#10336) +- Implement `ForEach-Object -Parallel` as an experimental feature (#10229) +- Skip `JumpList` on `NanoServer` and `IoT` (#10164) +- Make `Get-DscResource` work with class based resources (#10350) +- Fix `#requires -version` for `pwsh` 7 to include `6.1` and `6.2` in `PSCompatibleVersions` (#9943) (Thanks @bgelens!) +- Add dispose of `_runspaceDebugCompleteEvent` event object. (#10323) +- Fix performance regression from disabling debugger in system lockdown mode (#10269) +- Special case the `posix` locale in `WildcardPattern` (#10186) +- Use `Platform.IsWindowsDesktop` instead of checking both NanoServer and IoT (#10205) + +### General Cmdlet Updates and Fixes + +- Enable Experimental Features by default on Preview builds (#10228) +- Enable `-sta` and `-mta` switches for `pwsh` (`-sta` is required for `GUIs`) (#10061) +- Make breakpoints display better over PowerShell remoting (#10339) (Thanks @KirkMunro!) +- Add support for `AppX` reparse points (#10331) +- Make module name matching for `get-module -FullyQualifiedName` case insensitive (#10329) +- Expose `PreRelease` label in `PSModuleInfo` formatter (#10316) +- Add `-Raw` switch to `Select-String` which allows returning only the string that was matched (#9901) (Thanks @Jawz84!) + +- ### Performance + +- Reduce allocations in `MakePath()` method (#10027) (Thanks @iSazonov!) +- Remove extra check that the system dll exists (#10244) (Thanks @iSazonov!) +- Avoid boxing when passing value type arguments to `PSTraceSource.WriteLine` (#10052) (Thanks @iSazonov!) +- Reduce allocations in `Escape()` and `Unescape()` (#10041) (Thanks @iSazonov!) + +### Code Cleanup + +- Add the license header to `nanoserver.tests.ps1` (#10171) +- Mark `-parallel` and `-throttlelimit` reserved for `foreach` and `switch` statements (#10328) (Thanks @KirkMunro!) +- Deprecate workflow debugging code (#10321) (Thanks @KirkMunro!) +- Fix style issues in `InternalCommands.cs` (#10352) (Thanks @iSazonov!) +- Deprecate internal `HelpCategory.Workflow` enumeration (#10319) (Thanks @KirkMunro!) +- Update `Microsoft.PowerShell.CoreCLR.Eventing` to resolve conflict with `System.Diagnostics.EventLog` (#10305) +- Don't collect process start time as it's not being used on `consolehost` startup (#10294) +- .NET Core 3.0 now aborts the thread for us. Remove the `ThreadAbortException` code (#10230) (Thanks @iSazonov!) +- Use `nameof()` in `LocationGlobber` and `PathInfo` (#10200) (Thanks @iSazonov!) + +### Tools + +- Fix Hungarian prefix `my` (#9976) (Thanks @RDIL!) +- Fix spelling error in issue template (#10256) +- Quote arguments in `.vscode/tasks.json` in case of spaces (#10204) (Thanks @msftrncs!) + +### Tests + +- Remove `markdownlint` tests due to security issues (#10163) +- Add tests for `WildcardPattern.Escape()` and `Unescape()` (#10090) (Thanks @iSazonov!) +- Cleanup Docker release testing (#10310) (Thanks @RDIL!) + +### Build and Packaging Improvements + +- Update `Microsoft.Management.Infrastructure` version to `2.0.0-preview.2` (#10366) +- Move to `.NET Core 3.0 preview.8` (#10351) (#10227) (Thanks @bergmeister!) +- Bump `NJsonSchema` from `10.0.21` to `10.0.22` (#10364) +- Add `Microsoft.PowerShell.CoreCLR.Eventing.dll` to exception list for build fix (#10337) +- Bump `Microsoft.CodeAnalysis.CSharp` from `3.1.0` to `3.2.1` (#10273) (#10330) +- Revert the temporary AzDevOps artifact workaround (#10260) +- Fix macOS build break (#10207) + +### Documentation and Help Content + +- Update docs for `7.0.0-preview.2` release (#10160) (#10176) +- `PSSA` also includes formatting (#10172) +- Refactor security policy documentation so that they appear in the Security policy tab of GitHub (#9905) (Thanks @bergmeister!) +- Add tooling section to PR template (#10144) +- Update `README.md` and `metadata.json` for next releases (#10087) +- Update DotNet Support links (#10145) +- Update our language on our policy applying to security issues (#10304) +- Update dead links from `powershell.com` (#10297) +- Create `Distribution_Request` issue template (#10253) +- Fix: Removed dependency file with `Dependabot` (#10212) (Thanks @RDIL!) + +## [7.0.0-preview.2] - 2019-07-17 + +### Breaking Changes + +- Cleanup workflow - remove `PSProxyJob` (#10083) (Thanks @iSazonov!) +- Disable `Enter-PSHostProcess` cmdlet when system in lock down mode (Internal 9168) + +### Engine Updates and Fixes + +- Consider `DBNull.Value` and `NullString.Value` the same as `$null` when comparing with `$null` and casting to bool (#9794) (Thanks @vexx32!) +- Allow methods to be named after keywords (#9812) (Thanks @vexx32!) +- Create `JumpList` in `STA` thread as some `COM` `APIs` are strictly `STA` only to avoid sporadic `CLR` crashes (#9928) (#10057) (Thanks @bergmeister!) +- Skip `JumpList` on `NanoServer` and `IoT` (#10164) +- Display `COM` method signature with argument names (#9858) (Thanks @nbkalex!) +- Use the original precision (prior-dotnet-core-3) for double/float-to-string conversion (#9893) +- `Import-DscResource` can now clobber built-in DSC resource names (#9879) +- Add ability to pass `InitialSessionState` to the `ConsoleShell.Start` (#9802) (Thanks @asrosent!) +- Have console host not enter command prompt mode when using `Read-Host -Prompt` (#9743) +- Fix use of `Start-Process http://bing.com` (#9793) +- Support negative numbers in `-split` operator (#8960) (Thanks @ece-jacob-scott!) + +### General Cmdlet Updates and Fixes + +- Support DSC compilation on Linux. (#9834) +- Add alias for Service `StartType` (#9940) (Thanks @NeoBeum!) +- Add `-SecurityDescriptorSddl` parameter to `Set-Service` (#8626) (Thanks @kvprasoon!) +- Fix auto-download of files when enumerating files from a `OneDrive` folder (#9895) +- Set request headers when request body is empty in Web Cmdlets (#10034) (Thanks @markekraus!) +- Fix wrong comparison in `CertificateProvider` (#9987) (Thanks @iSazonov!) +- Sync docs changes into the embedded help for `pwsh` (#9952) +- Display Duration when displaying `HistoryInfo` (#9751) (Thanks @rkeithhill!) +- Update console startup and help `url` for PowerShell docs (#9775) +- Make `UseAbbreviationExpansion` and `TempDrive` official features (#9872) +- Fix `Get-ChildItem -Path` with wildcard `char` (#9257) (Thanks @kwkam!) + +### Performance + +- Add another fast path to `WildcardPattern.IsMatch` for patterns that only have an asterisk in the end (#10054) (Thanks @iSazonov!) +- Move some of the creations of `WildcardPattern` in outer loop to avoid unnecessary allocation (#10053) (Thanks @iSazonov!) +- Make `Foreach-Object` 2 times faster by reducing unnecessary allocations and boxing (#10047) +- Use a static cache for `PSVersionInfo.PSVersion` to avoid casting `SemanticVersion` to `Version` every time accessing that property (#10028) +- Reduce allocations in `NavigationCmdletProvider.NormalizePath()` (#10038) (Thanks @iSazonov!) +- Add fast path for wildcard patterns that contains no wildcard characters (#10020) +- Avoid `Assembly.GetName()` in `ClrFacade.GetAssemblies(string)` to reduce allocations of `CultureInfo` objects (#10024) (Thanks @iSazonov!) +- Avoid the `int[]` and `int[,]` allocation when tokenizing line comments and matching wildcard pattern (#10009) + +### Tools + +- Update change log generation tool to deal with private commits (#10096) +- Update `Start-PSBuild -Clean` logic of `git clean` to ignore locked files from `VS2019` (#10071) (Thanks @bergmeister!) +- Indent fix in `markdown-link.tests.ps1` (#10049) (Thanks @RDIL!) +- `Start-PSBuild -Clean` does not remove all untracked files (#10022) (Thanks @vexx32!) +- Add module to support Pester tests for automating debugger commands (`stepInto`, `stepOut`, etc.), along with basic tests (#9825) (Thanks @KirkMunro!) +- Remove `markdownlint` tests due to security issues (#10163) + +### Code Cleanup + +- Cleanup `CompiledScriptBlock.cs` (#9735) (Thanks @vexx32!) +- Cleanup workflow code (#9638) (Thanks @iSazonov!) +- Use `AddOrUpdate()` instead of `Remove` then `Add` to register runspace (#10007) (Thanks @iSazonov!) +- Suppress `PossibleIncorrectUsageOfAssignmentOperator` rule violation by adding extra parenthesis (#9460) (Thanks @xtqqczze!) +- Use `AddRange` in `GetModules()` (#9975) (Thanks @iSazonov!) +- Code cleanup: use `IndexOf(char)` overload (#9722) (Thanks @iSazonov!) +- Move `consts` and methods to single `CharExtensions` class (#9992) (Thanks @iSazonov!) +- Cleanup: Use `EndsWith(char)` and `StartsWith(char)` (#9994) (Thanks @iSazonov!) +- Remove `LCIDToLocaleName` `P/Invoke` from `GetComputerInfoCommand` (#9716) (Thanks @iSazonov!) +- Cleanup Parser tests (#9792) (Thanks @vexx32!) +- Remove `EtwActivity` empty constructor and make minor style fixes (#9958) (Thanks @RDIL!) +- Fix style issues from last commits (#9937) (Thanks @iSazonov!) +- Remove dead code about `IsTransparentProxy` (#9966) +- Fix minor typos in code comments (#9917) (Thanks @RDIL!) +- Style fixes for `CimAsyncOperations` (#9945) (Thanks @RDIL!) +- Fix minor `CodeFactor` style issues in `ModuleCmdletBase` (#9915) (Thanks @RDIL!) +- Clean up the use of `SetProfileRoot` and `StartProfile` in ConsoleHost (#9931) +- Fix minor style issues come from last commits (#9640) (Thanks @iSazonov!) +- Improve whitespace for Parser tests (#9806) (Thanks @vexx32!) +- Use new `string.ConCat()` in `Process.cs` (#9720) (Thanks @iSazonov!) +- Code Cleanup: Tidy up `scriptblock.cs` (#9732) (Thanks @vexx32!) + +### Tests + +- Mark `Set-Service` tests with password as `Pending` (#10146) +- Fix test password generation rule to meet Windows complexity requirements (#10143) +- Add test for `New-Item -Force` (#9971) (Thanks @robdy!) +- Fix gulp versions (#9916) (Thanks @RDIL!) +- Indentation fixes in `ci.psm1` (#9947) (Thanks @RDIL!) +- Remove some `Travis-CI` references (#9919) (Thanks @RDIL!) +- Improve release testing Docker images (#9942) (Thanks @RDIL!) +- Use `yarn` to install global tools (#9904) (Thanks @RDIL!) +- Attempt to work around the zip download issue in Azure DevOps Windows CI (#9911) +- Update PowerShell SDK version for hosting tests (Internal 9185) + +### Build and Packaging Improvements + +- Update the target framework for reference assemblies to `netcoreapp3.0` (#9747) +- Pin version of `netDumbster` to `2.0.0.4` (#9748) +- Fix daily `CodeCoverageAndTest` build by explicitly calling `Start-PSBootStrap` (#9724) +- Split the `fxdependent` package on Windows into two packages (#10134) +- Bump `System.Data.SqlClient` (#10109) +- Bump `System.Security.AccessControl` (#10100) +- Add performance tag to change log command (Internal) +- Upgrade .Net Core 3 SDK from `preview5` to `preview6` and related out of band `Nuget` packages from `2.1` to `3.0-preview6` (#9888) (Thanks @bergmeister!) +- Add to `/etc/shells` on macOS (#10066) +- Bump `Markdig.Signed` from `0.17.0` to `0.17.1` (#10062) +- Update copyright symbol for `NuGet` packages (#9936) +- Download latest version `(6.2.0)` of `PSDesiredStateConfiguration` `nuget` package. (#9932) +- Add automated `RPM` signing to release build (#10013) +- Bump `ThreadJob` from `1.1.2` to `2.0.1` in `/src/Modules` (#10003) +- Bump `PowerShellGet` from `2.1.4` to `2.2` in /src/Modules (#9933) (#10085) +- Bump `PackageManagement` from `1.4` to `1.4.3` in `/src/Modules` (#9820) (#9918) (#10084) +- Update to use `TSAv2` (#9914) +- Bump `NJsonSchema` from `9.14.1` to `10.0.21` (#9805) (#9843) (#9854) (#9862) (#9875) (#9885) (#9954) (#10017) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.3` to `4.5.4` (#9786) +- Bump `Microsoft.ApplicationInsights` from `2.9.1` to `2.10.0` (#9757) +- Increase timeout of NuGet job to workaround build timeout (#9772) + +### Documentation and Help Content + +- Change log `6.1.4` (#9759) +- Change log for release `6.2.1` (#9760) +- Add quick steps for adding docs to cmdlets (#9978) +- Update readme `gitter` badge (#9920) (Thanks @RDIL!) +- Update `README` and `metadata.json` for `7.0.0-preview.1` release (#9767) + +## [7.0.0-preview.1] - 2019-05-30 + +### Breaking Changes + +- Disable the debugger when in system lock-down mode (#9645) +- Fix `Get-Module -FullyQualifiedName` option to work with paths (#9101) (Thanks @pougetat!) +- Fix `-NoEnumerate` behavior in `Write-Output` (#9069) (Thanks @vexx32!) +- Make command searcher treat wildcard as literal if target exists for execution (#9202) + +### Engine Updates and Fixes + +- Port PowerShell to .NET Core 3.0 (#9597) +- Make sure we always return an object in command searcher (#9623) +- Support line continuance with pipe at the start of a line (#8938) (Thanks @KirkMunro!) +- Add support for `ValidateRangeKind` to `ParameterMetadata.GetProxyAttributeData` (#9059) (Thanks @indented-automation!) +- Allow passing just a dash as an argument to a file via pwsh (#9479) +- Fix tab completion for functions (#9383) +- Reduce string allocation in console output code (#6882) (Thanks @iSazonov!) +- Fixing test run crash by not passing script block to the callback (#9298) +- Add Binary Parsing Support & Refactor `TryGetNumberValue` & `ScanNumberHelper` (#7993) (Thanks @vexx32!) +- Add PowerShell remoting enable/disable cmdlet warning messages (#9203) +- Add `xsd` for `cdxml` (#9177) +- Improve formatting performance by having better primitives on `PSObject` (#8785) (Thanks @powercode!) +- Improve type inference of array literals and foreach statement variables (#8100) (Thanks @SeeminglyScience!) +- Fix for `FormatTable` remote deserialization regression (#9116) +- Get `MethodInfo` from .NET public type with explicit parameter types (#9029) (Thanks @iSazonov!) +- Add retry logic to the operation that updates `powershell.config.json` (#8779) (Thanks @iSazonov!) +- Update the task-based `async` APIs added to PowerShell to return a Task object directly (#9079) +- Add 5 `InvokeAsync` overloads and `StopAsync` to the `PowerShell` type (#8056) (Thanks @KirkMunro!) +- Remove unused cached types (#9015) + +### General Cmdlet Updates and Fixes + +- Fix use of unicode ellipsis in `XML` for truncating error messages (#9589) +- Improve error message in FileSystemProvider when removing a folder containing hidden or read only files (#9551) (Thanks @iSazonov!) +- Enable recursion into `OneDrive` by not treating placeholders as symlinks (#9509) +- Change `MatchType` for `EnumerationOptions` to be `Win32` making this consistent with Windows PowerShell (#9529) +- Add Support for null Usernames in Web Cmdlet Basic Auth (#9536) (Thanks @markekraus!) +- Fix null reference when `Microsoft.PowerShell.Utility` is loaded as a `snapin` in hosting scenarios (#9404) +- Update width of `DateTime` to accommodate change in Japan `DateTime` format with new era starting 5/1/19 (#9503) +- Fix `Get-Runspace` runspace object format Type column (#9438) +- Return correct casing of filesystem path during normalization (#9250) +- Move warning message to `EndProcessing` so it only shows up once (#9385) +- Fix the platform check in `CimDSCParser.cs` (#9338) +- New `New-PSBreakpoint` cmdlet & new `-Breakpoint` parameter for `Debug-Runspace` (#8923) +- Fix help paging issues on macOS/Linux and with custom pager that takes arguments (#9033) (Thanks @rkeithhill!) +- Add `QuoteFields` parameter to `ConvertTo-Csv` and `Export-Csv` (#9132) (Thanks @iSazonov!) +- Fix progress for Get-ComputerInfo (#9236) (Thanks @powercode!) +- Add `ItemSeparator` and `AltItemSeparator` properties in `ProviderInfo` (#8587) (Thanks @renehernandez!) +- Add timestamp to `pshost` trace listener (#9230) +- Implement `Get-Random -Count` without specifying an `InputObject` list (#9111) (Thanks @pougetat!) +- Enable `SecureString` cmdlets for non-Windows (#9199) +- Add Obsolete message to `Send-MailMessage` (#9178) +- Fix `Restart-Computer` to work on `localhost` when WinRM is not present (#9160) +- Make `Start-Job` throw terminating exception when `-RunAs32` is specified in 64-bit pwsh (#9143) +- Make `Start-Job` throw terminating error when PowerShell is being hosted (#9128) +- Made `-Subject` parameter of `Send-MailMessage` command no longer mandatory. (#8961) (Thanks @ece-jacob-scott!) +- Make `New-ModuleManifest` consistent with `Update-ModuleManifest` (#9104) (Thanks @pougetat!) +- Add support for empty `NoteProperty` in `Group-Object` (#9109) (Thanks @iSazonov!) +- Remove `Hardlink` from `Mode` property in default file system format (#8789) (Thanks @powercode!) +- Fixing issue with help progress with `Get-Help` not calling `Completed` (#8788) (Thanks @powercode!) +- Allow `Test-ModuleManifest` to work when `RootModule` has no file extension (#8687) (Thanks @pougetat!) +- Add `UseQuotes` parameter to `Export-Csv` and `ConvertTo-Csv` cmdlets (#8951) (Thanks @iSazonov!) +- Update version for `PowerShell.Native` and hosting tests (#8983) +- Refactor shuffle in `Get-Random` to save a full iteration of the objects. (#8969) (Thanks @st0le!) +- Suggest `-Id pid` for `Get-Process pid` (#8959) (Thanks @MohiTheFish!) + +### Code Cleanup + +- `Attributes.cs` - Style / Formatting Fixes (#9625) (Thanks @vexx32!) +- Remove Workflow from `PSSessionType` (#9618) (Thanks @iSazonov!) +- Update use of "PowerShell Core" to just "PowerShell" (#9513) +- Use `IPGlobalProperties` on all platforms for getting host name (#9530) (Thanks @iSazonov!) +- Remove `IsSymLink()` P/Invoke on Unix (#9534) (Thanks @iSazonov!) +- Cleanup unused P/Invokes on Unix (#9531) (Thanks @iSazonov!) +- Update use of `Windows PowerShell` to just `PowerShell` (#9508) +- Cleanup: sort `usings` (#9490) (Thanks @iSazonov!) +- Cleanup `Export-Command` from `AssemblyInfo` (#9455) (Thanks @iSazonov!) +- Run CodeFormatter for `System.Management.Automation` (#9402) (Thanks @iSazonov!) +- Run CodeFormatter with `BraceNewLine`,`UsingLocation`,`FormatDocument`,`NewLineAbove` rules (#9393) (Thanks @iSazonov!) +- Run CodeFormatter for `WSMan.Management` (#9400) (Thanks @iSazonov!) +- Run CodeFormatter for `WSMan.Runtime` (#9401) (Thanks @iSazonov!) +- Run CodeFormatter for `Security` module (#9399) (Thanks @iSazonov!) +- Run CodeFormatter for `MarkdownRender` (#9398) (Thanks @iSazonov!) +- Run CodeFormatter for `Eventing` (#9394) (Thanks @iSazonov!) +- Use `Environment.NewLine` for new lines in `ConsoleHost` code (#9392) (Thanks @iSazonov!) +- Run CodeFormatter for Diagnostics module (#9378) (Thanks @iSazonov!) +- Run CodeFormatter for `Microsoft.PowerShell.Commands.Management` (#9377) (Thanks @iSazonov!) +- Run CodeFormatter for Utility module (#9376) (Thanks @iSazonov!) +- Style: Match file name casings of C# source files for Utility commands (#9329) (Thanks @ThreeFive-O!) +- Update repo for Ubuntu 14.04 EOL (#9324) +- Cleanup: sort `usings` (#9283) (Thanks @iSazonov!) +- Fix StyleCop Hungarian Notation (#9281) (Thanks @iSazonov!) +- Style: Update StyleCop rules (#8500) +- Enhance the P/Invoke code for `LookupAccountSid` in `Process.cs` (#9197) (Thanks @iSazonov!) +- Fix coding style for `NewModuleManifestCommand` (#9134) (Thanks @pougetat!) +- Remove unused method `CredUIPromptForCredential` from `HostUtilities.cs` (#9220) (Thanks @iSazonov!) +- Remove non-existent paths from `.csproj` files (#9214) (Thanks @ThreeFive-O!) +- Typo in new parameter set (#9205) +- Minor `FileSystemProvider` cleanup (#9182) (Thanks @RDIL!) +- Cleanup style issues in `CoreAdapter` and `MshObject` (#9190) (Thanks @iSazonov!) +- Minor cleanups in `Process.cs` (#9195) (Thanks @iSazonov!) +- Refactor `ReadConsole` P/Invoke in `ConsoleHost` (#9165) (Thanks @iSazonov!) +- Clean up `Get-Random` cmdlet (#9133) (Thanks @pougetat!) +- Fix to not pass `StringBuilder` by reference (`out` or `ref`) in P/Invoke (#9066) (Thanks @iSazonov!) +- Update AppVeyor comments in `Implicit.Remoting.Tests.ps1` (#9020) (Thanks @RDIL!) +- Remove AppImage from tools (#9100) (Thanks @Geweldig!) +- Using supported syntax for restoring warnings - Visual Studio 2019 complains about enable. (#9107) (Thanks @powercode!) +- Use `Type.EmptyTypes` and `Array.Empty()` to replace our custom code of the same functionality (#9042) (Thanks @iSazonov!) +- Rename private methods in `MshCommandRuntime.cs` (#9074) (Thanks @vexx32!) +- Cleanup & update `ErrorRecord` class code style (#9021) (Thanks @vexx32!) +- Remove unused cached types from `CachedReflectionInfo` (#9019) (Thanks @iSazonov!) +- Fix CodeFactor brace style issues in `FileSystemProvider` (#8992) (Thanks @RDIL!) +- Use `List.AddRange` to optimize `-Split` (#9001) (Thanks @iSazonov!) +- Remove Arch Linux Dockerfile (#8990) (Thanks @RDIL!) +- Cleanup `dllimport` (#8847) (Thanks @iSazonov!) + +### Tools + +- Convert custom attribute `ValidatePathNotInSettings` to function (#9406) +- Create `DependaBot` `config.yml` (#9368) +- Add more users to failures detection and fix alias for static analysis (#9292) +- Make `install-powershell.ps1` work on Windows Server 2012 R2 (#9271) +- Enable `PoshChan` for getting and automatic retrieval of test failures for a PR (#9232) +- Fix capitalization cases for `PoshChan` (#9188) (Thanks @RDIL!) +- Update to new format for `PoshChan` settings and allow all users access to reminders (#9198) +- Fix settings to use dashes instead of underscore (#9167) +- Fix `AzDevOps` context names and add all PowerShell team members (#9164) +- Add settings for `PoshChan` (#9162) +- Adding `CmdletsToExport` and `AliasesToExport` to test module manifests. (#9108) (Thanks @powercode!) +- Delete Docker manifest creation script (#9076) (Thanks @RDIL!) +- Make install scripts more consistent over different operating systems (#9071) (Thanks @Geweldig!) +- Comment cleanup in `releaseTools.psm1` (#9064) (Thanks @RDIL!) +- Fix duplicate recommendation of Azure DevOps extension for Visual Studio Code (#9032) (Thanks @ThreeFive-O!) +- Code coverage artifacts (#8993) + +### Tests + +- Update version tests to use `NextReleaseVersion` from `metadata.json` (#9646) +- Convert Windows CI to stages (#9607) +- Multiple test fixes and improved logging for fragile tests (#9569) +- Add unit and feature tests for `Send-MailMessage` (#9213) (Thanks @ThreeFive-O!) +- Update to Pester `4.8.0` (#9510) +- Ensure `Wait-UntilTrue` returns `$true` in Pester tests (#9458) (Thanks @xtqqczze!) +- Adding tests for `Remove-Module` (#9276) (Thanks @pougetat!) +- Allow CI to run on branches with this name pattern: `feature*` (#9415) +- Mark tests in macOS CI which use `AppleScript` as pending/inconclusive (#9352) +- Reduce time for stack overflow test (#9302) +- Added more tests for `Import-Alias` by file regarding parsing difficult aliases strings (#9247) (Thanks @SytzeAndr!) +- Move from `npm` to `Yarn` for markdown tests (#9312) (Thanks @RDIL!) +- Only search for functions in Constrained Language help tests (#9301) +- Fix skipping of tests in `RemoteSession.Basic.Tests.ps1` (#9304) +- Make sure non-Windows CI fails when a test fails (#9303) +- Update tests to account for when `$PSHOME` is read only (#9279) +- Add tests for command globbing (#9180) +- Fix tab completion test to handle multiple matches (#8891) +- Refactor macOS CI so that tests run in parallel (#9056) +- Fix `Enter-PSHostProcess` tests flakiness (#9007) +- Add source for `Install-Package` to install `netDumbster` (#9081) +- Style fixes for `Select-Xml` tests (#9037) (Thanks @ThreeFive-O!) +- Enable cross-platform `Send-MailMessage` tests for CI (#8859) (Thanks @ThreeFive-O!) +- Added `RequireSudoOnUnix` tags to `PowerShellGet` tests and remove pending parameter (#8954) (Thanks @RDIL!) +- Style fixes for `ConvertTo-Xml` tests (#9036) (Thanks @ThreeFive-O!) +- Align name schemes for test files (#9034) (Thanks @ThreeFive-O!) +- Pending `NamedPipeConnectionInfo` test (#9003) (Thanks @iSazonov!) +- Add test for `-WhatIf` for `New-FileCatalog` (#8966) (Thanks @mjanko5!) + +### Build and Packaging Improvements + +- Fix the PowerShell version number in MSI packages (Internal 8547) +- Add cleanup before building test package (Internal 8529) +- Update version for SDK tests and `Microsoft.PowerShell.Native` package (Internal 8512) +- Update the target framework for reference assemblies to `netcoreapp3.0` (Internal 8510) +- Fix syncing modules from PowerShell gallery by normalizing version numbers (Internal 8504) +- Add `tsaVersion` property as `TsaV1` for compliance build phase (#9176) +- Add ability to cross compile (#9374) +- Add `AcessToken` variable to jobs that perform signing (#9351) +- Add CI for `install-powershell.sh` and Amazon Linux (#9314) +- Add component detection to all jobs (#8964) +- Add Preview assets for `MSIX` (#9375) +- Add secret scanning to CI (#9249) +- Build test packages for `windows`, `linux-x64`, `linux-arm`, `linux-arm64` and `macOS` (#9476) +- Bump `gulp` from `4.0.0` to `4.0.2` (#9441, #9544) +- Bump `Markdig.Signed` from `0.15.7` to `0.17.0` (#8981, #9579) +- Bump `Microsoft.CodeAnalysis.CSharp` from `2.10.0` to `3.1.0` (#9277, 9653) +- Bump `Microsoft.PowerShell.Native` from `6.2.0-rc.1` to `6.2.0` (#9200) +- Bump `Microsoft.Windows.Compatibility` from `2.0.1` to `2.1.1` (#9605) +- Bump `Newtonsoft.Json` from `12.0.1` to `12.0.2` (#9431, #9434) +- Bump `NJsonSchema` from `9.13.19` to `9.14.1` (#9044, #9136, #9166, #9172, #9184, #9196, #9265, #9349, #9388, #9421, #9429, #9478, #9523, #9616) +- Bump `PackageManagement` from `1.3.1` to `1.4` (#9567, #9650) +- Bump `PowerShellGet` from `2.0.4` to `2.1.4` in /src/Modules (#9110, #9145, #9600, #9691) +- Bump `PSReadLine` from `2.0.0-beta3` to `2.0.0-beta4` (#9554) +- Bump `SelfSignedCertificate` (#9055) +- Bump `System.Data.SqlClient` from `4.6.0` to `4.6.1` (#9601) +- Bump `System.Net.Http.WinHttpHandler` from `4.5.2` to `4.5.3` (#9333) +- Bump `Microsoft.PowerShell.Archive` from `1.2.2.0` to `1.2.3.0` (#9593) +- Check to be sure that the test result file has actual results before uploading (#9253) +- Clean up static analysis config (#9113) (Thanks @RDIL!) +- Create `codecoverage` and test packages for non-Windows (#9373) +- Create test package for macOS on release builds (#9344) +- Disable Homebrew analytics in macOS Azure DevOps builds (#9130) (Thanks @RDIL!) +- Enable building of `MSIX` package (#9289) +- Enable building on Kali Linux (#9471) +- Fix artifact Download issue in release build (#9095) +- Fix build order in `windows-daily` build (#9275) +- Fix dependencies of NuGet build to wait on `DEB` uploads to finish (#9118) +- Fix `MSI` Upgrade failure for preview builds (#9013) +- Fix publishing daily `nupkg` to MyGet (#9269) +- Fix the failed test and update `Publish-TestResults` to make Azure DevOps fail the task when any tests failed (#9457) +- Fix variable name in `windows-daily.yml` (#9274) +- Fixed Dockerfile syntax highlighting (#8991) (Thanks @RDIL!) +- Make `CodeCoverage` configuration build portable symbol files (#9346) +- Make Linux CI parallel (#9209) +- Move artifacts to artifact staging directory before uploading (#9273) +- Performance improvements for release build (#9179) +- Preserve user shortcuts pinned to TaskBar during MSI upgrade (#9305) (Thanks @bergmeister!) +- Publish global tool packages to `pwshtool` blob and bug fixes (#9163) +- Publish test package on release builds (#9063) +- Publish windows daily build to MyGet (#9288) +- Remove appveyor references from packaging tools (#9117) (Thanks @RDIL!) +- Remove code from `CI.psm1` to optionally run Feature tests (#9212) (Thanks @RDIL!) +- Remove duplicate `PoliCheck` task and pin to specific version (#9297) +- Run `Start-PSBootStrap` in Code Coverage build to install .NET SDK (#9690) +- Switch from `BMP` to `PNG` for graphical `MSI` installer assets (#9606) +- Translate Skipped the test results into something Azure DevOps does NOT understand (#9124) +- Update Markdown test dependencies (#9075) (Thanks @RDIL!) +- Update UML to represent SDK and Global tool builds (#8997) +- Use IL assemblies for NuGet packages to reduce size (#9171) + +### Documentation and Help Content + +- Add checkbox to PR checklist for experimental feature use (#9619) (Thanks @KirkMunro!) +- Updating committee membership (#9577) (Thanks @HemantMahawar!) +- Update `CODEOWNERS` file to reduce noise (#9547) +- add download link to `raspbian64` to readme (#9520) +- Update `Support_Question.md` (#9218) (Thanks @vexx32!) +- Fix version of `PowerShellGet` in changelog (#9335) +- Update release process template to clarify that most tasks are coordinated by the release pipeline (#9238) +- Fix several problems in `WritingPesterTests` guideline (#9078) (Thanks @ThreeFive-O!) +- Update `ChangeLog` for `6.2.0` (#9245) +- Update docs for `v6.2.0` (#9229) +- Update `feature-request` issue template to move instructions into comments. (#9187) (Thanks @mklement0!) +- Update link to Contributing guide to new `PowerShell-Doc` repo (#9090) (Thanks @iSazonov!) +- Correct punctuation in `README.md` (#9045) (Thanks @yashrajbharti!) +- Update Docker `README.md` (#9010) (Thanks @RDIL!) +- Update release process issue template (#9051) (Thanks @RDIL!) +- Documentation Cleanup (#8851) (Thanks @RDIL!) +- Update docs for `6.2.0-rc.1` release (#9022) +- Update release template (#8996) + +[7.0.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0...v7.0.1 +[7.0.0]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.3...v7.0.0 +[7.0.0-rc.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.2...v7.0.0-rc.3 +[7.0.0-rc.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.1...v7.0.0-rc.2 +[7.0.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.6...v7.0.0-rc.1 +[7.0.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.5...v7.0.0-preview.6 +[7.0.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.4...v7.0.0-preview.5 +[7.0.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.3...v7.0.0-preview.4 +[7.0.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.2...v7.0.0-preview.3 +[7.0.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.1...v7.0.0-preview.2 +[7.0.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-rc.1...v7.0.0-preview.1 diff --git a/CHANGELOG/README.md b/CHANGELOG/README.md index a7028154524..4c271de1a2c 100644 --- a/CHANGELOG/README.md +++ b/CHANGELOG/README.md @@ -1,6 +1,7 @@ # Changelogs * [Current preview changelog](preview.md) +* [7.0 changelog](7.0.md) * [6.2 changelog](6.2.md) * [6.1 changelog](6.1.md) * [6.0 changelog](6.0.md) diff --git a/CHANGELOG/preview.md b/CHANGELOG/preview.md index e0d9c74a518..18c054aa31a 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,881 +1,364 @@ -# Current preview Changelog +# Current preview release -## [7.0.0-rc.2] - 2020-01-16 +## [7.1.0-preview.3] - 2020-05-14 ### Breaking Changes -- Use `ISOWeek` for week numbers in `Get-Date` accounting for leap years #11536 (Thanks @paalbra!) -### Engine Updates and Fixes -- Revert the PRs that made `DBNull.Value` and `NullString.Value` treated as `$null` (#11584) -- Support expanding `~` in `$env:PATH` when doing command discovery (#11552) -- Skip null data in output data received handler to fix a `NullReferenceException` (#11448) (Thanks @iSazonov!) -- Add `ssh` parameter sets for the parameter `-JobName` in `Invoke-Command` (#11444) -- Adding `PowerShell Editor Services` and `PSScriptAnalyzer` to tracked modules (#11514) -- Fix key exchange hang with `SecureString` for the `OutOfProc` transports (#11380, #11406) -- Add setting to disable the implicit `WinPS` module loading (#11332) - -### General Cmdlet Updates and Fixes -- Fix `NullReferenceException` in `ConciseView` (#11435) (Thanks @iSazonov!) -- Remove the default value of `$true` for the parameter `-RequireLicenseAcceptance` in `New-ModuleManifest` (#11512) (Thanks @ThomasNieto!) -- Make Web Cmdlets skip processing the content headers with a null or empty value for backward compatibility (#11421) (Thanks @spongemike2!) -- Don't format exceptions that are not `ErrorRecord` objects (#11415) -- Mark `InitialSessionState.ImportPSSnapIn` as Obsolete (#11399) -- Use `PositionMessage` for the line context information for `ConciseView` (#11398) -- Add trailing line number to `filename` for `ConciseView` (#11391) -- Update `HelpInfoUri` for all modules in PowerShell 7.0 (#11389) -- Remove unnecessary newline in `ConciseView` (#11383) -- Move `Set-StrictMode` to the outer script block for `ErrorView` (#11381) -- Remove the declaration of `Get-Error` experimental feature from module manifest (#11369) -- Update error message if `Update-Help` fails for the current `UICulture` (#11356) -- `Test-Connection`: Fallback to hop IP Address on `-Traceroute` without `-ResolveDestination` (#11335) (Thanks @vexx32!) -- Add null host name check in `WSMan` (#11288) (Thanks @iSazonov!) -- Add `Type` member to exceptions containing type of exception for `Get-Error` (#11076) -- Write an error if argument is a directory in `Get-FileHash` cmdlet (#11114) (Thanks @iSazonov!) -- Update `Get-Error` to not modify the original `$Error` object (#11125) - -### Code Cleanup -- Use .NET code to check for processor architecture instead of P/Invoke (#11046) (Thanks @iSazonov!) - -### Tests -- Test fixes for various platforms (#11579, #11541) -- Various test fixes for debugger and remoting (#11528) -- `DSC` test fixes for `Alpine` and `Raspbian` (#11508) -- Normalize line endings before comparing string in tests (#11499) -- Fix `ssh` remoting test to work on all platforms (#11500) -- Build test artifacts for `Alpine` (#11483) -- Make null member access tests as string to avoid parsing errors (#11385) -- Fix test failing when `UnixStat` feature is disabled (#11370) -- Update hosting tests to use the SDK version from the build property (#11368) -- Add retry to `Enter-PSHostProcess` test (#11360) - -### Build and Packaging Improvements -- Bump `Microsoft.PowerShell.Native` from `7.0.0-rc.1` to `7.0.0.rc.2` (#11583) -- Update .NET SDK version to 3.1.101 (#11582) -- Bump `PSReadLine` from `2.0.0-rc1` to `2.0.0-rc2` (#11581) -- Bump `NJsonSchema` from `10.0.28` to `10.1.3` (#11382, #11573) -- Generate the correct reference assembly for `Microsoft.PowerShell.ConsoleHost` NuGet package (#11545) -- Update building of `MSIX` for `RC` to use 100 range revision (#11526) -- Fix symbolic links on Debian 10 packages (#11474) -- Bump `Microsoft.PowerShell.Archive` from `1.2.3.0` to `1.2.4.0` (#11502) -- Add script to rebuild `WIX` component references (#11485) -- Bump `PackageManagement` from `1.4.5` to `1.4.6` (#11427) -- Bump `PowerShellGet` from `2.2.2` to `2.2.3` (#11426) -- Bump `ThreadJob` from `2.0.2` to `2.0.3` (#11416) -- Fix symbolic links to `libs` on Debian 10 (#11390) -- Improve Ubuntu detection for Ubuntu derivatives like `GalliumOS` etc (#11155) - -### Documentation and Help Content -- Fix broken link in debugging `README.md` (#11503) - -## [7.0.0-rc.1] - 2019-12-16 - -### Breaking Changes -- Make update notification support `LTS` and default channels (#11132) +- Fix string parameter binding for `BigInteger` numeric literals (#11634) (Thanks @vexx32!) ### Engine Updates and Fixes -- Improvements in breakpoint APIs for remote scenarios (#11312) -- Fix PowerShell class definition leaking into another Runspace (#11273) -- Fix a regression in formatting caused by the `FirstOrDefault` primitive added in `7.0.0-Preview1` (#11258) -- Additional Microsoft Modules to track in `PS7` Telemetry (#10751) -- Make approved features non-experimental (#11303) -- Update `ConciseView` to use `TargetObject` if applicable (#11075) -- Fix `NullReferenceException` in `CompletionCompleters` public methods (#11274) -- Fix apartment thread state check on non-Windows platforms (#11301) -- Update setting `PSModulePath` to concatenate the process and machine environment variables (#11276) -- Bump `.NET Core` to `3.1.0` (#11260) -- Fix detection of `$PSHOME` in front of `$env:PATH` (#11141) -### General Cmdlet Updates and Fixes -- Fix for issue on Raspbian for setting date of file changes in `UnixStat` Experimental Feature (#11313) -- Add `-AsPlainText` to `ConvertFrom-SecureString` (#11142) -- Added `WindowsPS` version check for `WinCompat` (#11148) -- Fix error-reporting in some `WinCompat` scenarios (#11259) -- Add native binary resolver (#11032) (Thanks @iSazonov!) -- Update calculation of char width to respect `CJK` chars correctly (#11262) -- Add `Unblock-File` for macOS (#11137) -- Fix regression in `Get-PSCallStack` (#11210) (Thanks @iSazonov!) -- Avoid automatically loading the `ScheduledJob` module when using Job cmdlets (#11194) -- Add `OutputType` to `Get-Error` cmdlet and preserve original `TypeNames` (#10856) -- Fix null reference in `SupportsVirtualTerminal` property (#11105) - -### Code Cleanup -- Change comment and element text to meet Microsoft standards (#11304) - -### Tests -- Make unreliable `DSC` test pending (#11131) - -### Build and Packaging Improvements -- Fix Nuget package signing for Coordinated Package build (#11316) -- Update dependencies from PowerShell Gallery and NuGet (#11323) -- Bump `Microsoft.ApplicationInsights` from `2.11.0` to `2.12.0` (#11305) -- Bump `Microsoft.CodeAnalysis.CSharp` from `3.3.1` to `3.4.0` (#11265) -- Updates packages for Debian 10 and 11 (#11236) -- Only enable experimental features prior to `RC` (#11162) -- Update macOS minimum version (#11163) -- Bump `NJsonSchema` from `10.0.27` to `10.0.28` (#11170) +- Set correct `PSProvider` full name at module load time (#11813) (Thanks @iSazonov!) -### Documentation and Help Content -- Refactor change logs into one log per release (#11165) -- Fix `FWLinks` for PowerShell 7 online help documents (#11071) - -## [7.0.0-preview.6] - 2019-11-21 - -### Breaking Changes - -- Update `Test-Connection` to work more like the one in Windows PowerShell (#10697) (Thanks @vexx32!) -- Preserve `$?` for `ParenExpression`, `SubExpression` and `ArrayExpression` (#11040) -- Set working directory to current directory in `Start-Job` (#10920) (Thanks @iSazonov!) +### Experimental Features -### Engine Updates and Fixes +- Support passing `PSPath` to native commands (#12386) -- Allow `pwsh` to inherit `$env:PSModulePath` and enable `powershell.exe` to start correctly (#11057) +### General Cmdlet Updates and Fixes -### Experimental Features +- Fix incorrect index in format string in ParameterBinderBase (#12630) (Thanks @powercode!) +- Copy the `CommandInfo` property in `Command.Clone()` (#12301) (Thanks @TylerLeonhardt!) +- Apply `-IncludeEqual` in `Compare-Object` when `-ExcludeDifferent` is specified (#12317) (Thanks @davidseibel!) +- Change `Get-FileHash` to close file handles before writing output (#12474) (Thanks @HumanEquivalentUnit!) +- Fix inconsistent exception message in `-replace` operator (#12388) (Thanks @jackdcasey!) -- Provide Unix stat information in filesystem output (#11042) -- Support null-conditional operators `?.` and `?[]` in PowerShell language (#10960) -- Support using non-compatible Windows PowerShell modules in PowerShell Core (#10973) +### Code Cleanup -### Performance +
-- Avoid using closure in `Parser.SaveError` (#11006) -- Improve the caching when creating new `Regex` instances (#10657) (Thanks @iSazonov!) -- Improve processing of the PowerShell built-in type data from `types.ps1xml`, `typesV3.ps1xml` and `GetEvent.types.ps1xml` (#10898) -- Update `PSConfiguration.ReadValueFromFile` to make it faster and more memory efficient (#10839) + -### General Cmdlet Updates and Fixes +

We thank the following contributors!

+

@xtqqczze, @RDIL, @powercode, @xtqqczze, @xtqqczze

-- Add limit check in `Get-WinEvent` (#10648) (Thanks @iSazonov!) -- Fix command runtime so `StopUpstreamCommandsException` doesn't get populated in `-ErrorVariable` (#10840) -- Set the output encoding to `[Console]::OutputEncoding` for native commands (#10824) -- Support multi-line code blocks in examples (#10776) (Thanks @Greg-Smulko!) -- Add Culture parameter to `Select-String` cmdlet (#10943) (Thanks @iSazonov!) -- Fix `Start-Job` working directory path with trailing backslash (#11041) -- `ConvertFrom-Json`: Unwrap collections by default (#10861) (Thanks @danstur!) -- Use case-sensitive Hashtable for `Group-Object` cmdlet with `-CaseSensitive` and `-AsHashtable` switches (#11030) (Thanks @vexx32!) -- Handle exception if enumerating files fails when rebuilding path to have correct casing (#11014) -- Fix `ConciseView` to show `Activity` instead of `myCommand` (#11007) -- Allow web cmdlets to ignore HTTP error statuses (#10466) (Thanks @vdamewood!) -- Fix piping of more than one `CommandInfo` to `Get-Command` (#10929) -- Add back `Get-Counter` cmdlet for Windows (#10933) -- Make `ConvertTo-Json` treat `[AutomationNull]::Value` and `[NullString]::Value` as `$null` (#10957) -- Remove brackets from `ipv6` address for SSH remoting (#10968) -- Fix crash if command sent to pwsh is just whitespace (#10977) -- Added cross-platform `Get-Clipboard` and `Set-Clipboard` (#10340) -- Fix setting original path of filesystem object to not have extra trailing slash (#10959) -- Support `$null` for `ConvertTo-Json` (#10947) -- Add back `Out-Printer` command on Windows (#10906) -- Fix `Start-Job -WorkingDirectory` with whitespace (#10951) -- Return default value when getting `null` for a setting in `PSConfiguration.cs` (#10963) (Thanks @iSazonov!) -- Handle IO exception as non-terminating (#10950) -- Add `GraphicalHost` assembly to enable `Out-GridView`, `Show-Command`, and `Get-Help -ShowWindow` (#10899) -- Take `ComputerName` via pipeline in `Get-HotFix` (#10852) (Thanks @kvprasoon!) -- Fix tab completion for parameters so that it shows common parameters as available (#10850) -- Fix `GetCorrectCasedPath()` to first check if any system file entries is returned before calling `First()` (#10930) -- Set working directory to current directory in `Start-Job` (#10920) (Thanks @iSazonov!) -- Change `TabExpansion2` to not require `-CursorColumn` and treat as `$InputScript.Length` (#10849) -- Handle case where Host may not return Rows or Columns of screen (#10938) -- Fix use of accent colors for hosts that don't support them (#10937) -- Add back `Update-List` command (#10922) -- Update `FWLink` Id for `Clear-RecycleBin` (#10925) -- During tab completion, skip file if can't read file attributes (#10910) -- Add back `Clear-RecycleBin` for Windows (#10909) -- Add `$env:__SuppressAnsiEscapeSequences` to control whether to have VT escape sequence in output (#10814) +
-### Code Cleanup +
    +
  • Replace Unicode non-breaking space character with space (#12576) (Thanks @xtqqczze!)
  • +
  • Remove unused New-DockerTestBuild.ps1 (#12610) (Thanks @RDIL!)
  • +
  • Annotate Assert methods for better code analysis (#12618) (Thanks @powercode!)
  • +
  • Use correct casing for cmdlet names and parameters in *.ps1 files throughout the codebase (#12584) (Thanks @xtqqczze!)
  • +
  • Document why PackageVersion is used in PowerShell.Common.props (#12523) (Thanks @xtqqczze!)
  • +
-- Cleanup style issues in `Compiler.cs` (#10368) (Thanks @iSazonov!) -- Remove the unused type converter for `CommaDelimitedStringCollection` (#11000) (Thanks @iSazonov!) -- Cleanup style in `InitialSessionState.cs` (#10865) (Thanks @iSazonov!) -- Code clean up for `PSSession` class (#11001) -- Remove the not-working 'run `Update-Help` from `Get-Help` when `Get-Help` runs for the first time' feature (#10974) -- Fix style issues (#10998) (Thanks @iSazonov!) -- Cleanup: use the built-in type alias (#10882) (Thanks @iSazonov!) -- Remove the unused setting key `ConsolePrompting` and avoid unnecessary string creation when querying `ExecutionPolicy` setting (#10985) -- Disable update notification check for daily builds (#10903) (Thanks @bergmeister!) -- Reinstate debugging API lost in #10338 (#10808) +
### Tools -- Add default setting for the `SDKToUse` property so that it builds in VS (#11085) -- `Install-Powershell.ps1`: Add parameter to use MSI installation (#10921) (Thanks @MJECloud!) -- Add basic examples for `install-powershell.ps1` (#10914) (Thanks @kilasuit!) +- Update `@PoshChan` config to include `SSH` (#12526) (Thanks @vexx32!) +- Update log message in `Start-PSBootstrap` (#12573) (Thanks @xtqqczze!) +- Add the `.NET SDK` installation path to the current process path in `tools/UpdateDotnetRuntime.ps1` (#12525) ### Tests -- Fix `stringdata` test to correctly validate keys of hashtables (#10810) -- Unload test modules (#11061) (Thanks @iSazonov!) -- Increase time between retries of testing URL (#11015) -- Update tests to accurately describe test actions. (#10928) (Thanks @romero126!) +- Make CIM tab completion test case insensitive (#12636) +- Mark ping tests as Pending due to stability issues in macOS (#12504) ### Build and Packaging Improvements -- Updating links in `README.md` and `metadata.json` for Preview.5 (#10854) -- Select the files for compliance tests which are owned by PowerShell (#10837) -- Allow `win7x86` `msix` package to build. (Internal 10515) -- Allow semantic versions to be passed to `NormalizeVersion` function (#11087) -- Bump .NET core framework to `3.1-preview.3` (#11079) -- Bump `PSReadLine` from `2.0.0-beta5` to `2.0.0-beta6` in /src/Modules (#11078) -- Bump `Newtonsoft.Json` from `12.0.2` to `12.0.3` (#11037) (#11038) -- Add Debian 10, 11 and CentOS 8 packages (#11028) -- Upload `Build-Info` Json file with the `ReleaseDate` field (#10986) -- Bump .NET core framework to `3.1-preview.2` (#10993) -- Enable build of x86 MSIX package (#10934) -- Update the dotnet SDK install script URL in `build.psm1` (#10927) -- Bump `Markdig.Signed` from `0.17.1` to `0.18.0` (#10887) -- Bump `ThreadJob` from `2.0.1` to `2.0.2` (#10886) -- Update `AppX` Manifest and Packaging module to conform to MS Store requirements (#10878) +
+ + + +

We thank the following contributors!

+

@jcotton42, @iSazonov, @iSazonov, @iSazonov

+ +
+ +
    +
  • Update build to use the new .NET SDK 5.0.100-preview.4.20258.7 (#12637)
  • +
  • Bump NJsonSchema from 10.1.14 to 10.1.15 (#12608)
  • +
  • Bump NJsonSchema from 10.1.13 to 10.1.14 (#12598)
  • +
  • Bump NJsonSchema from 10.1.12 to 10.1.13 (#12583)
  • +
  • Update the build to sign any unsigned files as 3rd party Dlls (#12581)
  • +
  • Update .NET SDK to 5.0.100-preview.4.20229.10 (#12538)
  • +
  • Add ability to Install-Dotnet to specify directory (#12469)
  • +
  • Allow / in relative paths for using module (#7424) (#12492) (Thanks @jcotton42!)
  • +
  • Update dotnet metadata for next channel for automated updates (#12502)
  • +
  • Bump .NET to 5.0.0-preview.4 (#12507)
  • +
  • Bump Microsoft.ApplicationInsights from 2.13.1 to 2.14.0 (#12479)
  • +
  • Bump PackageManagement from 1.4.6 to 1.4.7 in /src/Modules (#12506)
  • +
  • Bump Xunit.SkippableFact from 1.3.12 to 1.4.8 (#12480)
  • +
  • Fix quotes to allow variable expansion (#12512)
  • +
  • Use new TargetFramework as net5.0 in packaging scripts (#12503) (Thanks @iSazonov!)
  • +
  • Use new value for TargetFramework as net5.0 instead of netcoreapp5.0 (#12486) (Thanks @iSazonov!)
  • +
  • Disable PublishReadyToRun for framework dependent packages (#12450)
  • +
  • Add dependabot rules to ignore updates from .NET (#12466)
  • +
  • Update README.md and metadata.json for upcoming release (#12441)
  • +
  • Turn on ReadyToRun (#12361) (Thanks @iSazonov!)
  • +
  • Add summary to compressed sections of change log (#12429)
  • +
+ +
### Documentation and Help Content -- Update `CONTRIBUTING.md` (#11096) (Thanks @mklement0!) -- Fix installation doc links in `README.md` (#11083) -- Adds examples to `install-powershell.ps1` script (#11024) (Thanks @kilasuit!) -- Fix to `Select-String` emphasis and `Import-DscResource` in CHANGELOG.md (#10890) -- Remove the stale link from `powershell-beginners-guide.md` (#10926) +- Add link to life cycle doc to distribution request template (#12638) +- Update TFM reference in build docs (#12514) (Thanks @xtqqczze!) +- Fix broken link for blogs in documents (#12471) -## [7.0.0-preview.5] - 2019-10-23 +## [7.1.0-preview.2] - 2020-04-23 ### Breaking Changes -- Make `$PSCulture` consistently reflect in-session culture changes (#10138) (Thanks @iSazonov!) +- On Windows, `Start-Process` creates a process environment with + all the environment variables from current session, + using `-UseNewEnvironment` creates a new default process environment (#10830) (Thanks @iSazonov!) +- Do not wrap return result to `PSObject` when converting ScriptBlock to delegate (#10619) ### Engine Updates and Fixes -- Move to `.NET Core 3.1 preview 1` (#10798) -- Refactor reparse tag checks in file system provider (#10431) (Thanks @iSazonov!) -- Replace `CR` and new line with a `0x23CE` character in script logging (#10616) -- Fix a resource leak by unregistering the event handler from `AppDomain.CurrentDomain.ProcessExit` (#10626) - -### Experimental Features - -- Implement `Get-Error` cmdlet as Experimental Feature (#10727,#10800) -- Add `ConciseView` for `$ErrorView` and update it to remove unnecessary text and not color entire line in red (#10641,#10724) -- Support the pipeline chain operators `&&` and `||` in PowerShell language (#9849,#10825,#10836) -- Implement null coalescing (`??`) and null coalescing assignment (`??=`) operators (#10636) -- Support notification on `pwsh` startup when a new release is available and update notification message (#10689,#10777) +- Allow case insensitive paths for determining `PSModulePath` (#12192) +- Add PowerShell version 7.0 to compatible version list (#12184) +- Discover assemblies loaded by `Assembly.Load(byte[])` and `Assembly.LoadFile` (#12203) ### General Cmdlet Updates and Fixes -- Add emphasis to `Select-String` output (with `-NoEmphasis` parameter to opt-out) (#8963) (Thanks @derek-xia!) -- Add back `Get-HotFix` cmdlet (#10740) -- Make `Add-Type` usable in applications that host `PowerShell` (#10587) -- Use more effective evaluation order in `LanguagePrimitives.IsNullLike()` (#10781) (Thanks @vexx32!) -- Improve handling of mixed-collection piped input and piped streams of input in `Format-Hex` (#8674) (Thanks @vexx32!) -- Use type conversion in `SSHConnection` hashtables when value doesn't match expected type (#10720) (Thanks @SeeminglyScience!) -- Fix `Get-Content -ReadCount 0` behavior when `-TotalCount` is set (#10749) (Thanks @eugenesmlv!) -- Reword access denied error message in `Get-WinEvent` (#10639) (Thanks @iSazonov!) -- Enable tab completion for variable assignment that is enum or type constrained (#10646) -- Remove unused `SourceLength` remoting property causing formatting issues (#10765) -- Add `-Delimiter` parameter to `ConvertFrom-StringData` (#10665) (Thanks @steviecoaster!) -- Add positional parameter for `ScriptBlock` when using `Invoke-Command` with `SSH` (#10721) (Thanks @machgo!) -- Show line context information if multiple lines but no script name for `ConciseView` (#10746) -- Add support for `\\wsl$\` paths to file system provider (#10674) -- Add the missing token text for `TokenKind.QuestionMark` in parser (#10706) -- Set current working directory of each `ForEach-Object -Parallel` running script to the same location as the calling script. (#10672) -- Replace `api-ms-win-core-file-l1-2-2.dll` with `Kernell32.dll` for `FindFirstStreamW` and `FindNextStreamW` APIs (#10680) (Thanks @iSazonov!) -- Tweak help formatting script to be more `StrictMode` tolerant (#10563) -- Add `-SecurityDescriptorSDDL` parameter to `New-Service` (#10483) (Thanks @kvprasoon!) -- Remove informational output, consolidate ping usage in `Test-Connection` (#10478) (Thanks @vexx32!) -- Read special reparse points without accessing them (#10662) (Thanks @iSazonov!) -- Direct `Clear-Host` output to terminal (#10681) (Thanks @iSazonov!) -- Add back newline for grouping with `Format-Table` and `-Property` (#10653) -- Remove [ValidateNotNullOrEmpty] from `-InputObject` on `Get-Random` to allow empty string (#10644) -- Make suggestion system string distance algorithm case-insensitive (#10549) (Thanks @iSazonov!) -- Fix null reference exception in `ForEach-Object -Parallel` input processing (#10577) +- Fix `WinCompat` module loading to treat PowerShell 7 modules with higher priority (#12269) +- Implement `ForEach-Object -Parallel` runspace reuse (#12122) +- Fix `Get-Service` to not modify collection while enumerating it (#11851) (Thanks @NextTurn!) +- Clean up the IPC named pipe on PowerShell exit (#12187) +- Fix `` detection regex in web cmdlets (#12099) (Thanks @vexx32!) +- Allow shorter signed hex literals with appropriate type suffixes (#11844) (Thanks @vexx32!) +- Update `UseNewEnvironment` parameter behavior of `Start-Process` cmdlet on Windows (#10830) (Thanks @iSazonov!) +- Add `-Shuffle` switch to `Get-Random` command (#11093) (Thanks @eugenesmlv!) +- Make `GetWindowsPowerShellModulePath` compatible with multiple PS installations (#12280) +- Fix `Start-Job` to work on systems that don't have Windows PowerShell registered as default shell (#12296) +- Specifying an alias and `-Syntax` to `Get-Command` returns the aliased commands syntax (#10784) (Thanks @ChrisLGardner!) +- Make CSV cmdlets work when using `-AsNeeded` and there is an incomplete row (#12281) (Thanks @iSazonov!) +- In local invocations, do not require `-PowerShellVersion 5.1` for `Get-FormatData` in order to see all format data. (#11270) (Thanks @mklement0!) +- Added Support For Big Endian `UTF-32` (#11947) (Thanks @NoMoreFood!) +- Fix possible race that leaks PowerShell object dispose in `ForEach-Object -Parallel` (#12227) +- Add `-FromUnixTime` to `Get-Date` to allow Unix time input (#12179) (Thanks @jackdcasey!) +- Change default progress foreground and background colors to provide improved contrast (#11455) (Thanks @rkeithhill!) +- Fix `foreach -parallel` when current drive is not available (#12197) +- Do not wrap return result to `PSObject` when converting `ScriptBlock` to `delegate` (#10619) +- Don't write DNS resolution errors on `Test-Connection -Quiet` (#12204) (Thanks @vexx32!) +- Use dedicated threads to read the redirected output and error streams from the child process for out-of-proc jobs (#11713) ### Code Cleanup -- Remove `WorkflowJobSourceAdapter` reference that is no longer used (#10326) (Thanks @KirkMunro!) -- Cleanup `COM` interfaces in jump list code by fixing `PreserveSig` attributes (#9899) (Thanks @weltkante!) -- Add a comment describing why `-ia` is not the alias for `-InformationAction` common parameter (#10703) (Thanks @KirkMunro!) -- Rename `InvokeCommandCmdlet.cs` to `InvokeExpressionCommand.cs` (#10659) (Thanks @kilasuit!) -- Add minor code cleanups related to update notifications (#10698) -- Remove deprecated workflow logic from the remoting setup scripts (#10320) (Thanks @KirkMunro!) -- Update help format to use proper case (#10678) (Thanks @tnieto88!) -- Clean up `CodeFactor` style issues coming in commits for the last month (#10591) (Thanks @iSazonov!) -- Fix typo in description of `PSTernaryOperator` experimental feature (#10586) (Thanks @bergmeister!) +
-### Performance + -- Add minor performance improvements for runspace initialization (#10569) (Thanks @iSazonov!) - -### Tools - -- Make `Install-PowerShellRemoting.ps1` handle empty string in `PowerShellHome` parameter (#10526) (Thanks @Orca88!) -- Switch from `/etc/lsb-release` to `/etc/os-release` in `install-powershell.sh` (#10773) (Thanks @Himura2la!) -- Check `pwsh.exe` and `pwsh` in daily version on Windows (#10738) (Thanks @centreboard!) -- Remove unneeded tap in `installpsh-osx.sh` (#10752) - -### Tests +

We thank the following contributors!

+

@ShaydeNofziger, @RDIL

-- Temporary skip the flaky test `TestAppDomainProcessExitEvenHandlerNotLeaking` (#10827) -- Make the event handler leaking test stable (#10790) -- Sync capitalization in `CI` `YAML` (#10767) (Thanks @RDIL!) -- Add test for the event handler leaking fix (#10768) -- Add `Get-ChildItem` test (#10507) (Thanks @iSazonov!) -- Replace ambiguous language for tests from `switch` to `parameter` for accuracy (#10666) (Thanks @romero126!) +
-### Build and Packaging Improvements - -- Update package reference for `PowerShell SDK` to `preview.5` (Internal 10295) -- Update `ThirdPartyNotices.txt` (#10834) -- Bump `Microsoft.PowerShell.Native` to `7.0.0-preview.3` (#10826) -- Bump `Microsoft.ApplicationInsights` from `2.10.0` to `2.11.0` (#10608) -- Bump `NJsonSchema` from `10.0.24` to `10.0.27` (#10756) -- Add `MacPorts` support to the build system (#10736) (Thanks @Lucius-Q-User!) -- Bump `PackageManagement` from `1.4.4` to `1.4.5` (#10728) -- Bump `NJsonSchema` from `10.0.23` to `10.0.24` (#10635) -- Add environment variable to differentiate client/server telemetry in `MSI` (#10612) -- Bump `PSDesiredStateConfiguration` from `2.0.3` to `2.0.4` (#10603) -- Bump `Microsoft.CodeAnalysis.CSharp` from `3.2.1` to `3.3.1` (#10607) -- Update to `.Net Core 3.0 RTM` (#10604) (Thanks @bergmeister!) -- Update `MSIX` packaging so the version to `Windows Store` requirements (#10588) - -### Documentation and Help Content - -- Merge stable and servicing change logs (#10527) -- Update used `.NET` version in build docs (#10775) (Thanks @Greg-Smulko!) -- Replace links from `MSDN` to `docs.microsoft.com` in `powershell-beginners-guide.md` (#10778) (Thanks @iSazonov!) -- Fix broken `DSC` overview link (#10702) -- Update `Support_Question.md` to link to `Stack Overflow` as another community resource (#10638) (Thanks @mklement0!) -- Add processor architecture to distribution request template (#10661) -- Add new PowerShell MoL book to learning PowerShell docs (#10602) - -## [7.0.0-preview.4] - 2019-09-19 - -### Engine Updates and Fixes - -- Add support to `ActionPreference.Break` to break into debugger when `Debug`, `Error`, `Information`, `Progress`, `Verbose` or `Warning` messages are generated (#8205) (Thanks @KirkMunro!) -- Enable starting control panel add-ins within PowerShell Core without specifying `.CPL` extension. (#9828) - -### Performance - -- Make `ForEach-Object` faster for its commonly used scenarios (#10454) and fix `ForEach-Object -Parallel` performance problem with many runspaces (#10455) - -### Experimental Features +
    +
  • Fix erroneous comment in tokenizer.cs (#12206) (Thanks @ShaydeNofziger!)
  • +
  • Fix terms checker issues (#12189)
  • +
  • Update copyright notice to latest guidance (#12190)
  • +
  • CodeFactor cleanup (#12251) (Thanks @RDIL!)
  • +
-- Update `PSDesiredStateConfiguration` module version to `2.0.3` and bring new tests; enable compilation to MOF on non-Windows and use of Invoke-DSCResource without LCM (#10516) -- Add APIs for breakpoint management in runspaces and enable attach to process without `BreakAll` for PowerShell Editor Services (#10338) (Thanks @KirkMunro!) -- Support [ternary operator](https://github.com/PowerShell/PowerShell-RFC/pull/218) in PowerShell language (#10367) - -### General Cmdlet Updates and Fixes - -- Add PowerShell Core group policy definitions (#10468) -- Update console host to support `XTPUSHSGR`/`XTPOPSGR` VT control sequences that are used in [composability scenarios](https://github.com/microsoft/terminal/issues/1796). (#10208) -- Add `WorkingDirectory` parameter to `Start-Job` (#10324) (Thanks @davinci26!) -- Remove the event handler that was causing breakpoint changes to be erroneously replicated to the host runspace debugger (#10503) (Thanks @KirkMunro!) -- Replace `api-ms-win-core-job-12-1-0.dll` with `Kernell32.dll` in `Microsoft.PowerShell.Commands.NativeMethods` P/Invoke API(#10417) (Thanks @iSazonov!) -- Fix wrong output for `New-Service` in variable assignment and `-OutVariable` (#10444) (Thanks @kvprasoon!) -- Fix global tool issues around exit code, command line parameters and path with spaces (#10461) -- Fix recursion into OneDrive - change `FindFirstFileEx()` to use `SafeFindHandle` type (#10405) -- Skip auto-loading `PSReadLine` on Windows if the [NVDA screen reader](https://www.nvaccess.org/about-nvda/) is active (#10385) -- Increase built-with-PowerShell module versions to `7.0.0.0` (#10356) -- Add throwing an error in `Add-Type` if a type with the same name already exists (#9609) (Thanks @iSazonov!) - -### Code Cleanup - -- Convert `ActionPreference.Suspend` enumeration value into a non-supported, reserved state, and remove restriction on using `ActionPreference.Ignore` in preference variables (#10317) (Thanks @KirkMunro!) -- Replace `ArrayList` with `List` to get more readable and reliable code without changing functionality (#10333) (Thanks @iSazonov!) -- Make code style fixes to `TestConnectionCommand` (#10439) (Thanks @vexx32!) -- Cleanup `AutomationEngine` and remove extra `SetSessionStateDrive` method call (#10416) (Thanks @iSazonov!) -- Rename default `ParameterSetName` back to `Delimiter` for `ConvertTo-Csv` and `ConvertFrom-Csv` (#10425) +
### Tools -- Update `install-powershell.ps1` to check for already installed daily build (#10489) +- Update .NET dependency update script to include test `csproj` files (#12372) +- Scripts to update to .NET prerelease version (#12284) ### Tests -- Add experimental check to `ForEach-Object -Parallel` tests (#10354) (Thanks @KirkMunro!) -- Update tests for Alpine validation (#10428) +- Pin major Pester version to 4 to prevent breaking changes caused by upcoming release of v5 (#12262) (Thanks @bergmeister!) ### Build and Packaging Improvements -- Bump `PowerShellGet` version from `2.2` to `2.2.1` (#10382) -- Bump `PackageManagement` version from `1.4.3` to `1.4.4` (#10383) -- Update `README.md` and `metadata.json` for `7.0.0-preview.4` (Internal 10011) -- Upgrade `.Net Core 3.0` version from `Preview 9` to `RC1` (#10552) (Thanks @bergmeister!) -- Fix `ExperimentalFeature` list generation (Internal 9996) -- Bump `PSReadLine` version from `2.0.0-beta4` to `2.0.0-beta5` (#10536) -- Fix release build script to set release tag -- Update version of `Microsoft.PowerShell.Native` to `7.0.0-preview.2` (#10519) -- Upgrade to `Netcoreapp3.0 preview9` (#10484) (Thanks @bergmeister!) -- Make sure the daily coordinated build, knows it is a daily build (#10464) -- Update the combined package build to release the daily builds (#10449) -- Remove appveyor reference (#10445) (Thanks @RDIL!) -- Bump `NJsonSchema` version from `10.0.22` to `10.0.23` (#10421) -- Remove the deletion of `linux-x64` build folder because some dependencies for Alpine need it (#10407) - -### Documentation and Help Content - -- Update `README.md` and metadata for `v6.1.6` and `v6.2.3` releases (#10523) -- Fix a typo in `README.md` (#10465) (Thanks @vedhasp!) -- Add a reference to `PSKoans` module to Learning Resources documentation (#10369) (Thanks @vexx32!) -- Update `README.md` and `metadata.json` for `7.0.0-preview.3` (#10393) +
-## [7.0.0-preview.3] - 2019-08-20 + -### Breaking Changes +

We thank the following contributors!

+

@rkitover, @bergmeister

-- Remove `kill` alias for `Stop-Process` cmdlet on Unix (#10098) (Thanks @iSazonov!) -- Support for starting PowerShell as a login shell (`pwsh -Login` / `pwsh -l`) support (#10050) +
-### Engine Updates and Fixes - -- Additional Telemetry - implementation of [`RFC0036`](https://github.com/PowerShell/PowerShell-RFC/pull/158) (#10336) -- Implement `ForEach-Object -Parallel` as an experimental feature (#10229) -- Skip `JumpList` on `NanoServer` and `IoT` (#10164) -- Make `Get-DscResource` work with class based resources (#10350) -- Fix `#requires -version` for `pwsh` 7 to include `6.1` and `6.2` in `PSCompatibleVersions` (#9943) (Thanks @bgelens!) -- Add dispose of `_runspaceDebugCompleteEvent` event object. (#10323) -- Fix performance regression from disabling debugger in system lockdown mode (#10269) -- Special case the `posix` locale in `WildcardPattern` (#10186) -- Use `Platform.IsWindowsDesktop` instead of checking both NanoServer and IoT (#10205) - -### General Cmdlet Updates and Fixes +
    +
  • Add the nuget.config from root to the temporary build folder (#12394)
  • +
  • Bump System.IO.Packaging (#12365)
  • +
  • Bump Markdig.Signed from 0.18.3 to 0.20.0 (#12379)
  • +
  • Bump to .NET 5 Preview 3 pre-release (#12353)
  • +
  • Bump PowerShellGet from 2.2.3 to 2.2.4 (#12342)
  • +
  • Linux: Initial support for Gentoo installations. (#11429) (Thanks @rkitover!)
  • +
  • Upgrade to .NET 5 Preview 2 (#12250) (Thanks @bergmeister!)
  • +
  • Fix the Sync PSGalleryModules to Artifacts build (#12277)
  • +
  • Bump PSReadLine from 2.0.0 to 2.0.1 (#12243)
  • +
  • Bump NJsonSchema from 10.1.11 to 10.1.12 (#12230)
  • +
  • Update change log generation script to support collapsible sections (#12214)
  • +
-- Enable Experimental Features by default on Preview builds (#10228) -- Enable `-sta` and `-mta` switches for `pwsh` (`-sta` is required for `GUIs`) (#10061) -- Make breakpoints display better over PowerShell remoting (#10339) (Thanks @KirkMunro!) -- Add support for `AppX` reparse points (#10331) -- Make module name matching for `get-module -FullyQualifiedName` case insensitive (#10329) -- Expose `PreRelease` label in `PSModuleInfo` formatter (#10316) -- Add `-Raw` switch to `Select-String` which allows returning only the string that was matched (#9901) (Thanks @Jawz84!) - -- ### Performance - -- Reduce allocations in `MakePath()` method (#10027) (Thanks @iSazonov!) -- Remove extra check that the system dll exists (#10244) (Thanks @iSazonov!) -- Avoid boxing when passing value type arguments to `PSTraceSource.WriteLine` (#10052) (Thanks @iSazonov!) -- Reduce allocations in `Escape()` and `Unescape()` (#10041) (Thanks @iSazonov!) - -### Code Cleanup - -- Add the license header to `nanoserver.tests.ps1` (#10171) -- Mark `-parallel` and `-throttlelimit` reserved for `foreach` and `switch` statements (#10328) (Thanks @KirkMunro!) -- Deprecate workflow debugging code (#10321) (Thanks @KirkMunro!) -- Fix style issues in `InternalCommands.cs` (#10352) (Thanks @iSazonov!) -- Deprecate internal `HelpCategory.Workflow` enumeration (#10319) (Thanks @KirkMunro!) -- Update `Microsoft.PowerShell.CoreCLR.Eventing` to resolve conflict with `System.Diagnostics.EventLog` (#10305) -- Don't collect process start time as it's not being used on `consolehost` startup (#10294) -- .NET Core 3.0 now aborts the thread for us. Remove the `ThreadAbortException` code (#10230) (Thanks @iSazonov!) -- Use `nameof()` in `LocationGlobber` and `PathInfo` (#10200) (Thanks @iSazonov!) - -### Tools - -- Fix Hungarian prefix `my` (#9976) (Thanks @RDIL!) -- Fix spelling error in issue template (#10256) -- Quote arguments in `.vscode/tasks.json` in case of spaces (#10204) (Thanks @msftrncs!) - -### Tests - -- Remove `markdownlint` tests due to security issues (#10163) -- Add tests for `WildcardPattern.Escape()` and `Unescape()` (#10090) (Thanks @iSazonov!) -- Cleanup Docker release testing (#10310) (Thanks @RDIL!) - -### Build and Packaging Improvements - -- Update `Microsoft.Management.Infrastructure` version to `2.0.0-preview.2` (#10366) -- Move to `.NET Core 3.0 preview.8` (#10351) (#10227) (Thanks @bergmeister!) -- Bump `NJsonSchema` from `10.0.21` to `10.0.22` (#10364) -- Add `Microsoft.PowerShell.CoreCLR.Eventing.dll` to exception list for build fix (#10337) -- Bump `Microsoft.CodeAnalysis.CSharp` from `3.1.0` to `3.2.1` (#10273) (#10330) -- Revert the temporary AzDevOps artifact workaround (#10260) -- Fix macOS build break (#10207) +
### Documentation and Help Content -- Update docs for `7.0.0-preview.2` release (#10160) (#10176) -- `PSSA` also includes formatting (#10172) -- Refactor security policy documentation so that they appear in the Security policy tab of GitHub (#9905) (Thanks @bergmeister!) -- Add tooling section to PR template (#10144) -- Update `README.md` and `metadata.json` for next releases (#10087) -- Update DotNet Support links (#10145) -- Update our language on our policy applying to security issues (#10304) -- Update dead links from `powershell.com` (#10297) -- Create `Distribution_Request` issue template (#10253) -- Fix: Removed dependency file with `Dependabot` (#10212) (Thanks @RDIL!) +- Add documentation for `WebResponseObject` and `BasicHtmlWebResponseObject` properties (#11876) (Thanks @kevinoid!) +- Add Windows 10 IoT Core reference in `Adopters.md` (#12266) (Thanks @parameshbabu!) +- Update `README.md` and `metadata.json` for `7.1.0-preview.1` (#12211) -## [7.0.0-preview.2] - 2019-07-17 +## [7.1.0-preview.1] - 2020-03-26 ### Breaking Changes -- Cleanup workflow - remove `PSProxyJob` (#10083) (Thanks @iSazonov!) -- Disable `Enter-PSHostProcess` cmdlet when system in lock down mode (Internal 9168) +- Use invariant culture string conversion for `-replace` operator (#10954) (Thanks @iSazonov!) ### Engine Updates and Fixes -- Consider `DBNull.Value` and `NullString.Value` the same as `$null` when comparing with `$null` and casting to bool (#9794) (Thanks @vexx32!) -- Allow methods to be named after keywords (#9812) (Thanks @vexx32!) -- Create `JumpList` in `STA` thread as some `COM` `APIs` are strictly `STA` only to avoid sporadic `CLR` crashes (#9928) (#10057) (Thanks @bergmeister!) -- Skip `JumpList` on `NanoServer` and `IoT` (#10164) -- Display `COM` method signature with argument names (#9858) (Thanks @nbkalex!) -- Use the original precision (prior-dotnet-core-3) for double/float-to-string conversion (#9893) -- `Import-DscResource` can now clobber built-in DSC resource names (#9879) -- Add ability to pass `InitialSessionState` to the `ConsoleShell.Start` (#9802) (Thanks @asrosent!) -- Have console host not enter command prompt mode when using `Read-Host -Prompt` (#9743) -- Fix use of `Start-Process http://bing.com` (#9793) -- Support negative numbers in `-split` operator (#8960) (Thanks @ece-jacob-scott!) - -### General Cmdlet Updates and Fixes - -- Support DSC compilation on Linux. (#9834) -- Add alias for Service `StartType` (#9940) (Thanks @NeoBeum!) -- Add `-SecurityDescriptorSddl` parameter to `Set-Service` (#8626) (Thanks @kvprasoon!) -- Fix auto-download of files when enumerating files from a `OneDrive` folder (#9895) -- Set request headers when request body is empty in Web Cmdlets (#10034) (Thanks @markekraus!) -- Fix wrong comparison in `CertificateProvider` (#9987) (Thanks @iSazonov!) -- Sync docs changes into the embedded help for `pwsh` (#9952) -- Display Duration when displaying `HistoryInfo` (#9751) (Thanks @rkeithhill!) -- Update console startup and help `url` for PowerShell docs (#9775) -- Make `UseAbbreviationExpansion` and `TempDrive` official features (#9872) -- Fix `Get-ChildItem -Path` with wildcard `char` (#9257) (Thanks @kwkam!) - -### Performance - -- Add another fast path to `WildcardPattern.IsMatch` for patterns that only have an asterisk in the end (#10054) (Thanks @iSazonov!) -- Move some of the creations of `WildcardPattern` in outer loop to avoid unnecessary allocation (#10053) (Thanks @iSazonov!) -- Make `Foreach-Object` 2 times faster by reducing unnecessary allocations and boxing (#10047) -- Use a static cache for `PSVersionInfo.PSVersion` to avoid casting `SemanticVersion` to `Version` every time accessing that property (#10028) -- Reduce allocations in `NavigationCmdletProvider.NormalizePath()` (#10038) (Thanks @iSazonov!) -- Add fast path for wildcard patterns that contains no wildcard characters (#10020) -- Avoid `Assembly.GetName()` in `ClrFacade.GetAssemblies(string)` to reduce allocations of `CultureInfo` objects (#10024) (Thanks @iSazonov!) -- Avoid the `int[]` and `int[,]` allocation when tokenizing line comments and matching wildcard pattern (#10009) - -### Tools - -- Update change log generation tool to deal with private commits (#10096) -- Update `Start-PSBuild -Clean` logic of `git clean` to ignore locked files from `VS2019` (#10071) (Thanks @bergmeister!) -- Indent fix in `markdown-link.tests.ps1` (#10049) (Thanks @RDIL!) -- `Start-PSBuild -Clean` does not remove all untracked files (#10022) (Thanks @vexx32!) -- Add module to support Pester tests for automating debugger commands (`stepInto`, `stepOut`, etc.), along with basic tests (#9825) (Thanks @KirkMunro!) -- Remove `markdownlint` tests due to security issues (#10163) - -### Code Cleanup - -- Cleanup `CompiledScriptBlock.cs` (#9735) (Thanks @vexx32!) -- Cleanup workflow code (#9638) (Thanks @iSazonov!) -- Use `AddOrUpdate()` instead of `Remove` then `Add` to register runspace (#10007) (Thanks @iSazonov!) -- Suppress `PossibleIncorrectUsageOfAssignmentOperator` rule violation by adding extra parenthesis (#9460) (Thanks @xtqqczze!) -- Use `AddRange` in `GetModules()` (#9975) (Thanks @iSazonov!) -- Code cleanup: use `IndexOf(char)` overload (#9722) (Thanks @iSazonov!) -- Move `consts` and methods to single `CharExtensions` class (#9992) (Thanks @iSazonov!) -- Cleanup: Use `EndsWith(char)` and `StartsWith(char)` (#9994) (Thanks @iSazonov!) -- Remove `LCIDToLocaleName` `P/Invoke` from `GetComputerInfoCommand` (#9716) (Thanks @iSazonov!) -- Cleanup Parser tests (#9792) (Thanks @vexx32!) -- Remove `EtwActivity` empty constructor and make minor style fixes (#9958) (Thanks @RDIL!) -- Fix style issues from last commits (#9937) (Thanks @iSazonov!) -- Remove dead code about `IsTransparentProxy` (#9966) -- Fix minor typos in code comments (#9917) (Thanks @RDIL!) -- Style fixes for `CimAsyncOperations` (#9945) (Thanks @RDIL!) -- Fix minor `CodeFactor` style issues in `ModuleCmdletBase` (#9915) (Thanks @RDIL!) -- Clean up the use of `SetProfileRoot` and `StartProfile` in ConsoleHost (#9931) -- Fix minor style issues come from last commits (#9640) (Thanks @iSazonov!) -- Improve whitespace for Parser tests (#9806) (Thanks @vexx32!) -- Use new `string.ConCat()` in `Process.cs` (#9720) (Thanks @iSazonov!) -- Code Cleanup: Tidy up `scriptblock.cs` (#9732) (Thanks @vexx32!) - -### Tests - -- Mark `Set-Service` tests with password as `Pending` (#10146) -- Fix test password generation rule to meet Windows complexity requirements (#10143) -- Add test for `New-Item -Force` (#9971) (Thanks @robdy!) -- Fix gulp versions (#9916) (Thanks @RDIL!) -- Indentation fixes in `ci.psm1` (#9947) (Thanks @RDIL!) -- Remove some `Travis-CI` references (#9919) (Thanks @RDIL!) -- Improve release testing Docker images (#9942) (Thanks @RDIL!) -- Use `yarn` to install global tools (#9904) (Thanks @RDIL!) -- Attempt to work around the zip download issue in Azure DevOps Windows CI (#9911) -- Update PowerShell SDK version for hosting tests (Internal 9185) +- Revert the PRs that made `DBNull.Value` and `NullString.Value` treated as `$null` (#11648) -### Build and Packaging Improvements - -- Update the target framework for reference assemblies to `netcoreapp3.0` (#9747) -- Pin version of `netDumbster` to `2.0.0.4` (#9748) -- Fix daily `CodeCoverageAndTest` build by explicitly calling `Start-PSBootStrap` (#9724) -- Split the `fxdependent` package on Windows into two packages (#10134) -- Bump `System.Data.SqlClient` (#10109) -- Bump `System.Security.AccessControl` (#10100) -- Add performance tag to change log command (Internal) -- Upgrade .Net Core 3 SDK from `preview5` to `preview6` and related out of band `Nuget` packages from `2.1` to `3.0-preview6` (#9888) (Thanks @bergmeister!) -- Add to `/etc/shells` on macOS (#10066) -- Bump `Markdig.Signed` from `0.17.0` to `0.17.1` (#10062) -- Update copyright symbol for `NuGet` packages (#9936) -- Download latest version `(6.2.0)` of `PSDesiredStateConfiguration` `nuget` package. (#9932) -- Add automated `RPM` signing to release build (#10013) -- Bump `ThreadJob` from `1.1.2` to `2.0.1` in `/src/Modules` (#10003) -- Bump `PowerShellGet` from `2.1.4` to `2.2` in /src/Modules (#9933) (#10085) -- Bump `PackageManagement` from `1.4` to `1.4.3` in `/src/Modules` (#9820) (#9918) (#10084) -- Update to use `TSAv2` (#9914) -- Bump `NJsonSchema` from `9.14.1` to `10.0.21` (#9805) (#9843) (#9854) (#9862) (#9875) (#9885) (#9954) (#10017) -- Bump `System.Net.Http.WinHttpHandler` from `4.5.3` to `4.5.4` (#9786) -- Bump `Microsoft.ApplicationInsights` from `2.9.1` to `2.10.0` (#9757) -- Increase timeout of NuGet job to workaround build timeout (#9772) - -### Documentation and Help Content - -- Change log `6.1.4` (#9759) -- Change log for release `6.2.1` (#9760) -- Add quick steps for adding docs to cmdlets (#9978) -- Update readme `gitter` badge (#9920) (Thanks @RDIL!) -- Update `README` and `metadata.json` for `7.0.0-preview.1` release (#9767) - -## [7.0.0-preview.1] - 2019-05-30 - -### Breaking Changes - -- Disable the debugger when in system lock-down mode (#9645) -- Fix `Get-Module -FullyQualifiedName` option to work with paths (#9101) (Thanks @pougetat!) -- Fix `-NoEnumerate` behavior in `Write-Output` (#9069) (Thanks @vexx32!) -- Make command searcher treat wildcard as literal if target exists for execution (#9202) - -### Engine Updates and Fixes +### Experimental Features -- Port PowerShell to .NET Core 3.0 (#9597) -- Make sure we always return an object in command searcher (#9623) -- Support line continuance with pipe at the start of a line (#8938) (Thanks @KirkMunro!) -- Add support for `ValidateRangeKind` to `ParameterMetadata.GetProxyAttributeData` (#9059) (Thanks @indented-automation!) -- Allow passing just a dash as an argument to a file via pwsh (#9479) -- Fix tab completion for functions (#9383) -- Reduce string allocation in console output code (#6882) (Thanks @iSazonov!) -- Fixing test run crash by not passing script block to the callback (#9298) -- Add Binary Parsing Support & Refactor `TryGetNumberValue` & `ScanNumberHelper` (#7993) (Thanks @vexx32!) -- Add PowerShell remoting enable/disable cmdlet warning messages (#9203) -- Add `xsd` for `cdxml` (#9177) -- Improve formatting performance by having better primitives on `PSObject` (#8785) (Thanks @powercode!) -- Improve type inference of array literals and foreach statement variables (#8100) (Thanks @SeeminglyScience!) -- Fix for `FormatTable` remote deserialization regression (#9116) -- Get `MethodInfo` from .NET public type with explicit parameter types (#9029) (Thanks @iSazonov!) -- Add retry logic to the operation that updates `powershell.config.json` (#8779) (Thanks @iSazonov!) -- Update the task-based `async` APIs added to PowerShell to return a Task object directly (#9079) -- Add 5 `InvokeAsync` overloads and `StopAsync` to the `PowerShell` type (#8056) (Thanks @KirkMunro!) -- Remove unused cached types (#9015) +- Use invariant culture string conversion for `-replace` operator (#10954) (Thanks @iSazonov!) ### General Cmdlet Updates and Fixes -- Fix use of unicode ellipsis in `XML` for truncating error messages (#9589) -- Improve error message in FileSystemProvider when removing a folder containing hidden or read only files (#9551) (Thanks @iSazonov!) -- Enable recursion into `OneDrive` by not treating placeholders as symlinks (#9509) -- Change `MatchType` for `EnumerationOptions` to be `Win32` making this consistent with Windows PowerShell (#9529) -- Add Support for null Usernames in Web Cmdlet Basic Auth (#9536) (Thanks @markekraus!) -- Fix null reference when `Microsoft.PowerShell.Utility` is loaded as a `snapin` in hosting scenarios (#9404) -- Update width of `DateTime` to accommodate change in Japan `DateTime` format with new era starting 5/1/19 (#9503) -- Fix `Get-Runspace` runspace object format Type column (#9438) -- Return correct casing of filesystem path during normalization (#9250) -- Move warning message to `EndProcessing` so it only shows up once (#9385) -- Fix the platform check in `CimDSCParser.cs` (#9338) -- New `New-PSBreakpoint` cmdlet & new `-Breakpoint` parameter for `Debug-Runspace` (#8923) -- Fix help paging issues on macOS/Linux and with custom pager that takes arguments (#9033) (Thanks @rkeithhill!) -- Add `QuoteFields` parameter to `ConvertTo-Csv` and `Export-Csv` (#9132) (Thanks @iSazonov!) -- Fix progress for Get-ComputerInfo (#9236) (Thanks @powercode!) -- Add `ItemSeparator` and `AltItemSeparator` properties in `ProviderInfo` (#8587) (Thanks @renehernandez!) -- Add timestamp to `pshost` trace listener (#9230) -- Implement `Get-Random -Count` without specifying an `InputObject` list (#9111) (Thanks @pougetat!) -- Enable `SecureString` cmdlets for non-Windows (#9199) -- Add Obsolete message to `Send-MailMessage` (#9178) -- Fix `Restart-Computer` to work on `localhost` when WinRM is not present (#9160) -- Make `Start-Job` throw terminating exception when `-RunAs32` is specified in 64-bit pwsh (#9143) -- Make `Start-Job` throw terminating error when PowerShell is being hosted (#9128) -- Made `-Subject` parameter of `Send-MailMessage` command no longer mandatory. (#8961) (Thanks @ece-jacob-scott!) -- Make `New-ModuleManifest` consistent with `Update-ModuleManifest` (#9104) (Thanks @pougetat!) -- Add support for empty `NoteProperty` in `Group-Object` (#9109) (Thanks @iSazonov!) -- Remove `Hardlink` from `Mode` property in default file system format (#8789) (Thanks @powercode!) -- Fixing issue with help progress with `Get-Help` not calling `Completed` (#8788) (Thanks @powercode!) -- Allow `Test-ModuleManifest` to work when `RootModule` has no file extension (#8687) (Thanks @pougetat!) -- Add `UseQuotes` parameter to `Export-Csv` and `ConvertTo-Csv` cmdlets (#8951) (Thanks @iSazonov!) -- Update version for `PowerShell.Native` and hosting tests (#8983) -- Refactor shuffle in `Get-Random` to save a full iteration of the objects. (#8969) (Thanks @st0le!) -- Suggest `-Id pid` for `Get-Process pid` (#8959) (Thanks @MohiTheFish!) +- Fix an operator preference order issue in binder code (#12075) (Thanks @DamirAinullin!) +- Fix `NullReferenceException` when binding common parameters of type `ActionPreference` (#12124) +- Fix default formatting for deserialized `MatchInfo` (#11728) (Thanks @iSazonov!) +- Use asynchronous streams in `Invoke-RestMethod` (#11095) (Thanks @iSazonov!) +- Address UTF-8 Detection In `Get-Content -Tail` (#11899) (Thanks @NoMoreFood!) +- Handle the `IOException` in `Get-FileHash` (#11944) (Thanks @iSazonov!) +- Change `PowerShell Core` to `PowerShell` in a resource string (#11928) (Thanks @alexandair!) +- Bring back `MainWindowTitle` in `PSHostProcessInfo` (#11885) (Thanks @iSazonov!) +- Miscellaneous minor updates to Windows Compatibility (#11980) +- Fix `ConciseView` to split `PositionMessage` using `[Environment]::NewLine` (#12010) +- Remove network hop restriction for interactive sessions (#11920) +- Fix `NullReferenceException` in `SuspendStoppingPipeline()` and `RestoreStoppingPipeline()` (#11870) (Thanks @iSazonov!) +- Generate GUID for `FormatViewDefinition` `InstanceId` if not provided (#11896) +- Fix `ConciseView` where error message is wider than window width and doesn't have whitespace (#11880) +- Allow cross-platform `CAPI-compatible` remote key exchange (#11185) (Thanks @silijon!) +- Fix error message (#11862) (Thanks @NextTurn!) +- Fix `ConciseView` to handle case where there isn't a console to obtain the width (#11784) +- Update `CmsCommands` to use Store vs certificate provider (#11643) (Thanks @mikeTWC1984!) +- Enable `pwsh` to work on Windows systems where `mpr.dll` and STA is not available (#11748) +- Refactor and implement `Restart-Computer` for `Un*x` and macOS (#11319) +- Add an implementation of `Stop-Computer` for Linux and macOS (#11151) +- Fix `help` function to check if `less` is available before using (#11737) +- Update `PSPath` in `certificate_format_ps1.xml` (#11603) (Thanks @xtqqczze!) +- Change regular expression to match relation-types without quotes in Link header (#11711) (Thanks @Marusyk!) +- Fix error message during symbolic link deletion (#11331) +- Add custom `Selected.*` type to `PSCustomObject` in `Select-Object` only once (#11548) (Thanks @iSazonov!) +- Add `-AsUTC` to the `Get-Date` cmdlet (#11611) +- Fix grouping behavior with Boolean values in `Format-Hex` (#11587) (Thanks @vexx32!) +- Make `Test-Connection` always use the default synchronization context for sending ping requests (#11517) +- Correct startup error messages (#11473) (Thanks @iSazonov!) +- Ignore headers with null values in web cmdlets (#11424) (Thanks @iSazonov!) +- Re-add check for `Invoke-Command` job dispose. (#11388) +- Revert "Update formatter to not write newlines if content is empty (#11193)" (#11342) (Thanks @iSazonov!) +- Allow `CompleteInput` to return results from `ArgumentCompleter` when `AST` or Script has matching function definition (#10574) (Thanks @M1kep!) +- Update formatter to not write new lines if content is empty (#11193) ### Code Cleanup -- `Attributes.cs` - Style / Formatting Fixes (#9625) (Thanks @vexx32!) -- Remove Workflow from `PSSessionType` (#9618) (Thanks @iSazonov!) -- Update use of "PowerShell Core" to just "PowerShell" (#9513) -- Use `IPGlobalProperties` on all platforms for getting host name (#9530) (Thanks @iSazonov!) -- Remove `IsSymLink()` P/Invoke on Unix (#9534) (Thanks @iSazonov!) -- Cleanup unused P/Invokes on Unix (#9531) (Thanks @iSazonov!) -- Update use of `Windows PowerShell` to just `PowerShell` (#9508) -- Cleanup: sort `usings` (#9490) (Thanks @iSazonov!) -- Cleanup `Export-Command` from `AssemblyInfo` (#9455) (Thanks @iSazonov!) -- Run CodeFormatter for `System.Management.Automation` (#9402) (Thanks @iSazonov!) -- Run CodeFormatter with `BraceNewLine`,`UsingLocation`,`FormatDocument`,`NewLineAbove` rules (#9393) (Thanks @iSazonov!) -- Run CodeFormatter for `WSMan.Management` (#9400) (Thanks @iSazonov!) -- Run CodeFormatter for `WSMan.Runtime` (#9401) (Thanks @iSazonov!) -- Run CodeFormatter for `Security` module (#9399) (Thanks @iSazonov!) -- Run CodeFormatter for `MarkdownRender` (#9398) (Thanks @iSazonov!) -- Run CodeFormatter for `Eventing` (#9394) (Thanks @iSazonov!) -- Use `Environment.NewLine` for new lines in `ConsoleHost` code (#9392) (Thanks @iSazonov!) -- Run CodeFormatter for Diagnostics module (#9378) (Thanks @iSazonov!) -- Run CodeFormatter for `Microsoft.PowerShell.Commands.Management` (#9377) (Thanks @iSazonov!) -- Run CodeFormatter for Utility module (#9376) (Thanks @iSazonov!) -- Style: Match file name casings of C# source files for Utility commands (#9329) (Thanks @ThreeFive-O!) -- Update repo for Ubuntu 14.04 EOL (#9324) -- Cleanup: sort `usings` (#9283) (Thanks @iSazonov!) -- Fix StyleCop Hungarian Notation (#9281) (Thanks @iSazonov!) -- Style: Update StyleCop rules (#8500) -- Enhance the P/Invoke code for `LookupAccountSid` in `Process.cs` (#9197) (Thanks @iSazonov!) -- Fix coding style for `NewModuleManifestCommand` (#9134) (Thanks @pougetat!) -- Remove unused method `CredUIPromptForCredential` from `HostUtilities.cs` (#9220) (Thanks @iSazonov!) -- Remove non-existent paths from `.csproj` files (#9214) (Thanks @ThreeFive-O!) -- Typo in new parameter set (#9205) -- Minor `FileSystemProvider` cleanup (#9182) (Thanks @RDIL!) -- Cleanup style issues in `CoreAdapter` and `MshObject` (#9190) (Thanks @iSazonov!) -- Minor cleanups in `Process.cs` (#9195) (Thanks @iSazonov!) -- Refactor `ReadConsole` P/Invoke in `ConsoleHost` (#9165) (Thanks @iSazonov!) -- Clean up `Get-Random` cmdlet (#9133) (Thanks @pougetat!) -- Fix to not pass `StringBuilder` by reference (`out` or `ref`) in P/Invoke (#9066) (Thanks @iSazonov!) -- Update AppVeyor comments in `Implicit.Remoting.Tests.ps1` (#9020) (Thanks @RDIL!) -- Remove AppImage from tools (#9100) (Thanks @Geweldig!) -- Using supported syntax for restoring warnings - Visual Studio 2019 complains about enable. (#9107) (Thanks @powercode!) -- Use `Type.EmptyTypes` and `Array.Empty()` to replace our custom code of the same functionality (#9042) (Thanks @iSazonov!) -- Rename private methods in `MshCommandRuntime.cs` (#9074) (Thanks @vexx32!) -- Cleanup & update `ErrorRecord` class code style (#9021) (Thanks @vexx32!) -- Remove unused cached types from `CachedReflectionInfo` (#9019) (Thanks @iSazonov!) -- Fix CodeFactor brace style issues in `FileSystemProvider` (#8992) (Thanks @RDIL!) -- Use `List.AddRange` to optimize `-Split` (#9001) (Thanks @iSazonov!) -- Remove Arch Linux Dockerfile (#8990) (Thanks @RDIL!) -- Cleanup `dllimport` (#8847) (Thanks @iSazonov!) +
+ +
    +
  • Use span-based overloads (#11884) (Thanks @iSazonov!)
  • +
  • Use new string.Split() overloads (#11867) (Thanks @iSazonov!)
  • +
  • Remove unreachable DSC code (#12076) (Thanks @DamirAinullin!)
  • +
  • Remove old dead code from FullCLR (#11886) (Thanks @iSazonov!)
  • +
  • Use Dictionary.TryAdd() where possible (#11767) (Thanks @iSazonov!)
  • +
  • Use Environment.NewLine instead of hard-coded linefeed in ParseError.ToString (#11746)
  • +
  • Fix FileSystem provider error message (#11741) (Thanks @iSazonov!)
  • +
  • Reformat code according to EditorConfig rules (#11681) (Thanks @xtqqczze!)
  • +
  • Replace use of throw GetExceptionForHR with ThrowExceptionForHR (#11640) (Thanks @xtqqczze!)
  • +
  • Refactor delegate types to lambda expressions (#11690) (Thanks @xtqqczze!)
  • +
  • Remove Unicode BOM from text files (#11546) (Thanks @xtqqczze!)
  • +
  • Fix Typo in Get-ComputerInfo cmdlet description (#11321) (Thanks @doctordns!)
  • +
  • Fix typo in description for Get-ExperimentalFeature PSWindowsPowerShellCompatibility (#11282) (Thanks @alvarodelvalle!)
  • +
  • Cleanups in command discovery (#10815) (Thanks @iSazonov!)
  • +
  • Review CurrentCulture (#11044) (Thanks @iSazonov!)
  • +
+ +
### Tools -- Convert custom attribute `ValidatePathNotInSettings` to function (#9406) -- Create `DependaBot` `config.yml` (#9368) -- Add more users to failures detection and fix alias for static analysis (#9292) -- Make `install-powershell.ps1` work on Windows Server 2012 R2 (#9271) -- Enable `PoshChan` for getting and automatic retrieval of test failures for a PR (#9232) -- Fix capitalization cases for `PoshChan` (#9188) (Thanks @RDIL!) -- Update to new format for `PoshChan` settings and allow all users access to reminders (#9198) -- Fix settings to use dashes instead of underscore (#9167) -- Fix `AzDevOps` context names and add all PowerShell team members (#9164) -- Add settings for `PoshChan` (#9162) -- Adding `CmdletsToExport` and `AliasesToExport` to test module manifests. (#9108) (Thanks @powercode!) -- Delete Docker manifest creation script (#9076) (Thanks @RDIL!) -- Make install scripts more consistent over different operating systems (#9071) (Thanks @Geweldig!) -- Comment cleanup in `releaseTools.psm1` (#9064) (Thanks @RDIL!) -- Fix duplicate recommendation of Azure DevOps extension for Visual Studio Code (#9032) (Thanks @ThreeFive-O!) -- Code coverage artifacts (#8993) +- Change recommended VS Code extension name from `ms-vscode.csharp` to `ms-dotnettools.csharp` (#12083) (Thanks @devlead!) +- Specify `csharp_preferred_modifier_order` in `EditorConfig` (#11775) (Thanks @xtqqczze!) +- Update `.editorconfig` (#11675) (Thanks @xtqqczze!) +- Enable `EditorConfig` support in `OmniSharp` (#11627) (Thanks @xtqqczze!) +- Specify charset in `.editorconfig` as `utf-8` (no BOM) (#11654) (Thanks @xtqqczze!) +- Configure the issue label bot (#11527) +- Avoid variable names that conflict with automatic variables (#11392) (Thanks @xtqqczze!) ### Tests -- Update version tests to use `NextReleaseVersion` from `metadata.json` (#9646) -- Convert Windows CI to stages (#9607) -- Multiple test fixes and improved logging for fragile tests (#9569) -- Add unit and feature tests for `Send-MailMessage` (#9213) (Thanks @ThreeFive-O!) -- Update to Pester `4.8.0` (#9510) -- Ensure `Wait-UntilTrue` returns `$true` in Pester tests (#9458) (Thanks @xtqqczze!) -- Adding tests for `Remove-Module` (#9276) (Thanks @pougetat!) -- Allow CI to run on branches with this name pattern: `feature*` (#9415) -- Mark tests in macOS CI which use `AppleScript` as pending/inconclusive (#9352) -- Reduce time for stack overflow test (#9302) -- Added more tests for `Import-Alias` by file regarding parsing difficult aliases strings (#9247) (Thanks @SytzeAndr!) -- Move from `npm` to `Yarn` for markdown tests (#9312) (Thanks @RDIL!) -- Only search for functions in Constrained Language help tests (#9301) -- Fix skipping of tests in `RemoteSession.Basic.Tests.ps1` (#9304) -- Make sure non-Windows CI fails when a test fails (#9303) -- Update tests to account for when `$PSHOME` is read only (#9279) -- Add tests for command globbing (#9180) -- Fix tab completion test to handle multiple matches (#8891) -- Refactor macOS CI so that tests run in parallel (#9056) -- Fix `Enter-PSHostProcess` tests flakiness (#9007) -- Add source for `Install-Package` to install `netDumbster` (#9081) -- Style fixes for `Select-Xml` tests (#9037) (Thanks @ThreeFive-O!) -- Enable cross-platform `Send-MailMessage` tests for CI (#8859) (Thanks @ThreeFive-O!) -- Added `RequireSudoOnUnix` tags to `PowerShellGet` tests and remove pending parameter (#8954) (Thanks @RDIL!) -- Style fixes for `ConvertTo-Xml` tests (#9036) (Thanks @ThreeFive-O!) -- Align name schemes for test files (#9034) (Thanks @ThreeFive-O!) -- Pending `NamedPipeConnectionInfo` test (#9003) (Thanks @iSazonov!) -- Add test for `-WhatIf` for `New-FileCatalog` (#8966) (Thanks @mjanko5!) +- Add empty `preview.md` file to fix broken link (#12041) +- Add helper functions for SSH remoting tests (#11955) +- Add new tests for `Get-ChildItem` for `FileSystemProvider` (#11602) (Thanks @iSazonov!) +- Ensure that types referenced by `PowerShellStandard` are present (#10634) +- Check state and report reason if it's not "opened" (#11574) +- Fixes for running tests on Raspbian (#11661) +- Unify pester test syntax for the arguments of `-BeOfType` (#11558) (Thanks @xtqqczze!) +- Correct casing for automatic variables (#11568) (Thanks @iSazonov!) +- Avoid variable names that conflict with automatic variables part 2 (#11559) (Thanks @xtqqczze!) +- Update pester syntax to v4 (#11544) (Thanks @xtqqczze!) +- Allow error 504 (Gateway Timeout) in `markdown-link` tests (#11439) (Thanks @xtqqczze!) +- Re-balance CI tests (#11420) (Thanks @iSazonov!) +- Include URL in the markdown-links test error message (#11438) (Thanks @xtqqczze!) +- Use CIM cmdlets instead of WMI cmdlets in tests (#11423) (Thanks @xtqqczze!) ### Build and Packaging Improvements -- Fix the PowerShell version number in MSI packages (Internal 8547) -- Add cleanup before building test package (Internal 8529) -- Update version for SDK tests and `Microsoft.PowerShell.Native` package (Internal 8512) -- Update the target framework for reference assemblies to `netcoreapp3.0` (Internal 8510) -- Fix syncing modules from PowerShell gallery by normalizing version numbers (Internal 8504) -- Add `tsaVersion` property as `TsaV1` for compliance build phase (#9176) -- Add ability to cross compile (#9374) -- Add `AcessToken` variable to jobs that perform signing (#9351) -- Add CI for `install-powershell.sh` and Amazon Linux (#9314) -- Add component detection to all jobs (#8964) -- Add Preview assets for `MSIX` (#9375) -- Add secret scanning to CI (#9249) -- Build test packages for `windows`, `linux-x64`, `linux-arm`, `linux-arm64` and `macOS` (#9476) -- Bump `gulp` from `4.0.0` to `4.0.2` (#9441, #9544) -- Bump `Markdig.Signed` from `0.15.7` to `0.17.0` (#8981, #9579) -- Bump `Microsoft.CodeAnalysis.CSharp` from `2.10.0` to `3.1.0` (#9277, 9653) -- Bump `Microsoft.PowerShell.Native` from `6.2.0-rc.1` to `6.2.0` (#9200) -- Bump `Microsoft.Windows.Compatibility` from `2.0.1` to `2.1.1` (#9605) -- Bump `Newtonsoft.Json` from `12.0.1` to `12.0.2` (#9431, #9434) -- Bump `NJsonSchema` from `9.13.19` to `9.14.1` (#9044, #9136, #9166, #9172, #9184, #9196, #9265, #9349, #9388, #9421, #9429, #9478, #9523, #9616) -- Bump `PackageManagement` from `1.3.1` to `1.4` (#9567, #9650) -- Bump `PowerShellGet` from `2.0.4` to `2.1.4` in /src/Modules (#9110, #9145, #9600, #9691) -- Bump `PSReadLine` from `2.0.0-beta3` to `2.0.0-beta4` (#9554) -- Bump `SelfSignedCertificate` (#9055) -- Bump `System.Data.SqlClient` from `4.6.0` to `4.6.1` (#9601) -- Bump `System.Net.Http.WinHttpHandler` from `4.5.2` to `4.5.3` (#9333) -- Bump `Microsoft.PowerShell.Archive` from `1.2.2.0` to `1.2.3.0` (#9593) -- Check to be sure that the test result file has actual results before uploading (#9253) -- Clean up static analysis config (#9113) (Thanks @RDIL!) -- Create `codecoverage` and test packages for non-Windows (#9373) -- Create test package for macOS on release builds (#9344) -- Disable Homebrew analytics in macOS Azure DevOps builds (#9130) (Thanks @RDIL!) -- Enable building of `MSIX` package (#9289) -- Enable building on Kali Linux (#9471) -- Fix artifact Download issue in release build (#9095) -- Fix build order in `windows-daily` build (#9275) -- Fix dependencies of NuGet build to wait on `DEB` uploads to finish (#9118) -- Fix `MSI` Upgrade failure for preview builds (#9013) -- Fix publishing daily `nupkg` to MyGet (#9269) -- Fix the failed test and update `Publish-TestResults` to make Azure DevOps fail the task when any tests failed (#9457) -- Fix variable name in `windows-daily.yml` (#9274) -- Fixed Dockerfile syntax highlighting (#8991) (Thanks @RDIL!) -- Make `CodeCoverage` configuration build portable symbol files (#9346) -- Make Linux CI parallel (#9209) -- Move artifacts to artifact staging directory before uploading (#9273) -- Performance improvements for release build (#9179) -- Preserve user shortcuts pinned to TaskBar during MSI upgrade (#9305) (Thanks @bergmeister!) -- Publish global tool packages to `pwshtool` blob and bug fixes (#9163) -- Publish test package on release builds (#9063) -- Publish windows daily build to MyGet (#9288) -- Remove appveyor references from packaging tools (#9117) (Thanks @RDIL!) -- Remove code from `CI.psm1` to optionally run Feature tests (#9212) (Thanks @RDIL!) -- Remove duplicate `PoliCheck` task and pin to specific version (#9297) -- Run `Start-PSBootStrap` in Code Coverage build to install .NET SDK (#9690) -- Switch from `BMP` to `PNG` for graphical `MSI` installer assets (#9606) -- Translate Skipped the test results into something Azure DevOps does NOT understand (#9124) -- Update Markdown test dependencies (#9075) (Thanks @RDIL!) -- Update UML to represent SDK and Global tool builds (#8997) -- Use IL assemblies for NuGet packages to reduce size (#9171) +
+ +
    +
  • Put symbols in separate package (#12169)
  • +
  • Disable x86 PDB generation (#12167)
  • +
  • Bump NJsonSchema from 10.1.5 to 10.1.11 (#12050) (#12088) (#12166)
  • +
  • Create crossgen symbols for Windows x64 and x86 (#12157)
  • +
  • Move to .NET 5 preview.1 (#12140)
  • +
  • Bump Microsoft.CodeAnalysis.CSharp from 3.4.0 to 3.5.0 (#12136)
  • +
  • Move to standard internal pool for building (#12119)
  • +
  • Fix package syncing to private Module Feed (#11841)
  • +
  • Add Ubuntu SSH remoting tests CI (#12033)
  • +
  • Bump Markdig.Signed from 0.18.1 to 0.18.3 (#12078)
  • +
  • Fix MSIX packaging to determine if a Preview release by inspecting the semantic version string (#11991)
  • +
  • Ignore last exit code in the build step as dotnet may return error when SDK is not installed (#11972)
  • +
  • Fix daily package build (#11882)
  • +
  • Fix package sorting for syncing to private Module Feed (#11838)
  • +
  • Set StrictMode version 3.0 (#11563) (Thanks @xtqqczze!)
  • +
  • Bump .devcontainer version to dotnet 3.1.101 (#11707) (Thanks @Jawz84!)
  • +
  • Move to version 3 of AzFileCopy (#11697)
  • +
  • Update README.md and metadata.json for next release (#11664)
  • +
  • Code Cleanup for environment data gathering in build.psm1 (#11572) (Thanks @xtqqczze!)
  • +
  • Update Debian Install Script To Support Debian 10 (#11540) (Thanks @RandomNoun7!)
  • +
  • Update ADOPTERS.md (#11261) (Thanks @edyoung!)
  • +
  • Change back to use powershell.exe in 'SetVersionVariables.yml' to unblock daily build (#11207)
  • +
  • Change to use pwsh to have consistent JSON conversion for DateTime (#11126)
  • +
+ +
### Documentation and Help Content -- Add checkbox to PR checklist for experimental feature use (#9619) (Thanks @KirkMunro!) -- Updating committee membership (#9577) (Thanks @HemantMahawar!) -- Update `CODEOWNERS` file to reduce noise (#9547) -- add download link to `raspbian64` to readme (#9520) -- Update `Support_Question.md` (#9218) (Thanks @vexx32!) -- Fix version of `PowerShellGet` in changelog (#9335) -- Update release process template to clarify that most tasks are coordinated by the release pipeline (#9238) -- Fix several problems in `WritingPesterTests` guideline (#9078) (Thanks @ThreeFive-O!) -- Update `ChangeLog` for `6.2.0` (#9245) -- Update docs for `v6.2.0` (#9229) -- Update `feature-request` issue template to move instructions into comments. (#9187) (Thanks @mklement0!) -- Update link to Contributing guide to new `PowerShell-Doc` repo (#9090) (Thanks @iSazonov!) -- Correct punctuation in `README.md` (#9045) (Thanks @yashrajbharti!) -- Update Docker `README.md` (#9010) (Thanks @RDIL!) -- Update release process issue template (#9051) (Thanks @RDIL!) -- Documentation Cleanup (#8851) (Thanks @RDIL!) -- Update docs for `6.2.0-rc.1` release (#9022) -- Update release template (#8996) - -[7.0.0-rc.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-rc.1...v7.0.0-rc.2 -[7.0.0-rc.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.6...v7.0.0-rc.1 -[7.0.0-preview.6]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.5...v7.0.0-preview.6 -[7.0.0-preview.5]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.4...v7.0.0-preview.5 -[7.0.0-preview.4]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.3...v7.0.0-preview.4 -[7.0.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.2...v7.0.0-preview.3 -[7.0.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.1...v7.0.0-preview.2 -[7.0.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v6.2.0-rc.1...v7.0.0-preview.1 +- Replace `VSCode` link in `CONTRIBUTING.md` (#11475) (Thanks @stevend811!) +- Remove the version number of PowerShell from LICENSE (#12019) +- Add the 7.0 change log link to `CHANGELOG/README.md` (#12062) (Thanks @LabhanshAgrawal!) +- Improvements to the contribution guide (#12086) (Thanks @ShaydeNofziger!) +- Update the doc about debugging dotnet core in VSCode (#11969) +- Update `README.md` and `metadata.json` for the next release (#11918) (#11992) +- Update `Adopters.md` to include info on Azure Pipelines and GitHub Actions (#11888) (Thanks @alepauly!) +- Add information about how Amazon AWS uses PowerShell. (#11365) (Thanks @bpayette!) +- Add link to .NET CLI version in build documentation (#11725) (Thanks @joeltankam!) +- Added info about `DeploymentScripts` in `ADOPTERS.md` (#11703) +- Update `CHANGELOG.md` for `6.2.4` release (#11699) +- Update `README.md` and `metadata.json` for next release (#11597) +- Update the breaking change definition (#11516) +- Adding System Frontier to the PowerShell Core adopters list `ADOPTERS.md` (#11480) (Thanks @OneScripter!) +- Update `ChangeLog`, `README.md` and `metadata.json` for `7.0.0-rc.1` release (#11363) +- Add `AzFunctions` to `ADOPTERS.md` (#11311) (Thanks @Francisco-Gamino!) +- Add `Universal Dashboard` to `ADOPTERS.md` (#11283) (Thanks @adamdriscoll!) +- Add `config.yml` for `ISSUE_TEMPLATE` so that Doc, Security, Support, and Windows PowerShell issues go to URLs (#11153) +- Add `Adopters.md` file (#11256) +- Update `Readme.md` for `preview.6` release (#11108) +- Update `SUPPORT.md` (#11101) (Thanks @mklement0!) +- Update `README.md` (#11100) (Thanks @mklement0!) + +[7.1.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.2...v7.1.0-preview.3 +[7.1.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.1.0-preview.1...v7.1.0-preview.2 +[7.1.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.0.0-preview.6...v7.1.0-preview.1 + diff --git a/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json new file mode 100644 index 00000000000..0ec74b1f32b --- /dev/null +++ b/DotnetRuntimeMetadata.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "channel": "release/5.0.1xx-preview6", + "packageVersionPattern": "5.0.0-preview.6", + "nextChannel": "net5/preview6" + } +} diff --git a/LICENSE.txt b/LICENSE.txt index f8b2ee43481..b2f52a2bad4 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,11 +1,9 @@ -PowerShell 6.0 - -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the ""Software""), to deal +of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 05ad339f565..c2ee2dbf2a2 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -56,12 +56,12 @@ $(PSCoreFormattedVersion) $(PSCoreBuildVersion) + ..\..\assets\Powershell_av_colors.ico ..\..\assets\Powershell_black.ico @@ -93,10 +93,11 @@ PowerShell Microsoft Corporation - (c) Microsoft Corporation. All rights reserved. + (c) Microsoft Corporation. - netcoreapp3.1 + net5.0 8.0 + true true true diff --git a/README.md b/README.md index 840ebff097a..729655ed91c 100644 --- a/README.md +++ b/README.md @@ -26,21 +26,21 @@ If you are new to PowerShell and would like to learn more, we recommend reviewin You can download and install a PowerShell package for any of the following platforms. -| Supported Platform | Downloads (stable) | Downloads (preview) | How to Install | -| -------------------------------------------| ------------------------| ----------------------| ------------------------------| -| [Windows (x64)][corefx-win] | [.msi][rl-windows-64] | [.msi][pv-windows-64] | [Instructions][in-windows] | -| [Windows (x86)][corefx-win] | [.msi][rl-windows-86] | [.msi][pv-windows-86] | [Instructions][in-windows] | -| [Ubuntu 18.04][corefx-linux] | [.deb][rl-ubuntu18] | [.deb][pv-ubuntu18] | [Instructions][in-ubuntu18] | -| [Ubuntu 16.04][corefx-linux] | [.deb][rl-ubuntu16] | [.deb][pv-ubuntu16] | [Instructions][in-ubuntu16] | -| [Debian 9][corefx-linux] | [.deb][rl-debian9] | [.deb][pv-debian9] | [Instructions][in-deb9] | -| [Debian 10][corefx-linux] | | [.deb][pv-debian10] | | -| [CentOS 7][corefx-linux] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-centos] | -| [CentOS 8][corefx-linux] | | [.rpm][pv-centos8] | | -| [Red Hat Enterprise Linux 7][corefx-linux] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-rhel7] | -| [openSUSE 42.3][corefx-linux] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-opensuse] | -| [Fedora 28][corefx-linux] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-fedora] | -| [macOS 10.13+][corefx-macos] | [.pkg][rl-macos] | [.pkg][pv-macos] | [Instructions][in-macos] | -| Docker | | | [Instructions][in-docker] | +| Supported Platform | Download (LTS) | Downloads (stable) | Downloads (preview) | How to Install | +| -------------------------------------------| ------------------------| ------------------------| ----------------------| ------------------------------| +| [Windows (x64)][corefx-win] | [.msi][rl-windows-64] | [.msi][rl-windows-64] | [.msi][pv-windows-64] | [Instructions][in-windows] | +| [Windows (x86)][corefx-win] | [.msi][rl-windows-86] | [.msi][rl-windows-86] | [.msi][pv-windows-86] | [Instructions][in-windows] | +| [Ubuntu 18.04][corefx-linux] | [.deb][lts-ubuntu18] | [.deb][rl-ubuntu18] | [.deb][pv-ubuntu18] | [Instructions][in-ubuntu18] | +| [Ubuntu 16.04][corefx-linux] | [.deb][lts-ubuntu16] | [.deb][rl-ubuntu16] | [.deb][pv-ubuntu16] | [Instructions][in-ubuntu16] | +| [Debian 9][corefx-linux] | [.deb][lts-debian9] | [.deb][rl-debian9] | [.deb][pv-debian9] | [Instructions][in-deb9] | +| [Debian 10][corefx-linux] | [.deb][lts-debian10] | [.deb][rl-debian10] | [.deb][pv-debian10] | | +| [CentOS 7][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-centos] | +| [CentOS 8][corefx-linux] | [.rpm][lts-centos8] | [.rpm][rl-centos8] | [.rpm][pv-centos8] | | +| [Red Hat Enterprise Linux 7][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-rhel7] | +| [openSUSE 42.3][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-opensuse] | +| [Fedora 30][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-fedora] | +| [macOS 10.13+][corefx-macos] | [.pkg][lts-macos] | [.pkg][rl-macos] | [.pkg][pv-macos] | [Instructions][in-macos] | +| Docker | | | | [Instructions][in-docker] | You can download and install a PowerShell package for any of the following platforms, **which are supported by the community.** @@ -52,68 +52,77 @@ You can download and install a PowerShell package for any of the following platf You can also download the PowerShell binary archives for Windows, macOS and Linux. -| Platform | Downloads (stable) | Downloads (preview) | How to Install | -| ------------------------------------| ------------------------------------------------ | ------------------------------------------------| -----------------------------------------------| -| Windows | [32-bit][rl-winx86-zip]/[64-bit][rl-winx64-zip] | [32-bit][pv-winx86-zip]/[64-bit][pv-winx64-zip] | [Instructions][in-windows-zip] | -| macOS | [64-bit][rl-macos-tar] | [64-bit][pv-macos-tar] | [Instructions][in-tar-macos] | -| Linux | [64-bit][rl-linux-tar] | [64-bit][pv-linux-tar] | [Instructions][in-tar-linux] | -| Windows (arm) **Experimental** | [32-bit][rl-winarm]/[64-bit][rl-winarm64] | [32-bit][pv-winarm]/[64-bit][pv-winarm64] | [Instructions][in-arm] | -| Raspbian (Stretch) **Experimental** | [32-bit][rl-raspbian]/[64-bit][rl-raspbian64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/PowerShell-6.2.4-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/PowerShell-6.2.4-win-x86.msi -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell_6.2.4-1.ubuntu.18.04_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell_6.2.4-1.ubuntu.16.04_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell_6.2.4-1.debian.9_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell-6.2.4-1.rhel.7.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell-6.2.4-osx-x64.pkg -[rl-winarm]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/PowerShell-6.2.4-win-arm32.zip -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/PowerShell-6.2.4-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/PowerShell-6.2.4-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/PowerShell-6.2.4-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell-6.2.4-osx-x64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell-6.2.4-linux-x64.tar.gz -[rl-raspbian]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell-6.2.4-linux-arm32.tar.gz -[rl-raspbian64]: https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell-6.2.4-linux-arm64.tar.gz +| Platform | Downloads (stable) | Downloads (preview) | How to Install | +| ---------------| --------------------------------------------------- | ------------------------------------------------| -----------------------------------------------| +| Windows | [32-bit][rl-winx86-zip]/[64-bit][rl-winx64-zip] | [32-bit][pv-winx86-zip]/[64-bit][pv-winx64-zip] | [Instructions][in-windows-zip] | +| macOS | [64-bit][rl-macos-tar] | [64-bit][pv-macos-tar] | [Instructions][in-tar-macos] | +| Linux | [64-bit][rl-linux-tar] | [64-bit][pv-linux-tar] | [Instructions][in-tar-linux] | +| Windows (Arm) | [32-bit][rl-winarm]/[64-bit][rl-winarm64] (preview) | [32-bit][pv-winarm]/[64-bit][pv-winarm64] | [Instructions][in-arm] | +| Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | + +[lts-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts_7.0.2-1.ubuntu.18.04_amd64.deb +[lts-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts_7.0.2-1.ubuntu.16.04_amd64.deb +[lts-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts_7.0.2-1.debian.9_amd64.deb +[lts-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts_7.0.2-1.debian.10_amd64.deb +[lts-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts-7.0.2-1.rhel.7.x86_64.rpm +[lts-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts-7.0.2-1.centos.8.x86_64.rpm +[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-lts-7.0.2-osx-x64.pkg + +[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/PowerShell-7.0.2-win-x64.msi +[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/PowerShell-7.0.2-win-x86.msi +[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell_7.0.2-1.ubuntu.18.04_amd64.deb +[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell_7.0.2-1.ubuntu.16.04_amd64.deb +[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell_7.0.2-1.debian.9_amd64.deb +[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell_7.0.2-1.debian.10_amd64.deb +[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-1.rhel.7.x86_64.rpm +[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-1.centos.8.x86_64.rpm +[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-osx-x64.pkg +[rl-winarm]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/PowerShell-7.0.2-win-arm32.zip +[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/PowerShell-7.0.2-win-arm64.zip +[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/PowerShell-7.0.2-win-x86.zip +[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/PowerShell-7.0.2-win-x64.zip +[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-osx-x64.tar.gz +[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-linux-x64.tar.gz +[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-linux-arm32.tar.gz +[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.2/powershell-7.0.2-linux-arm64.tar.gz [rl-snap]: https://snapcraft.io/powershell -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/PowerShell-7.0.0-rc.2-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/PowerShell-7.0.0-rc.2-win-x86.msi -[pv-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-preview_7.0.0-rc.2-1.ubuntu.18.04_amd64.deb -[pv-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-preview_7.0.0-rc.2-1.ubuntu.16.04_amd64.deb -[pv-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-preview_7.0.0-rc.2-1.debian.9_amd64.deb -[pv-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-preview_7.0.0-rc.2-1.debian.10_amd64.deb -[pv-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-preview-7.0.0_rc.2-1.rhel.7.x86_64.rpm -[pv-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-preview-7.0.0_rc.2-1.centos.8.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-7.0.0-rc.2-osx-x64.pkg -[pv-winarm]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/PowerShell-7.0.0-rc.2-win-arm32.zip -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/PowerShell-7.0.0-rc.2-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/PowerShell-7.0.0-rc.2-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/PowerShell-7.0.0-rc.2-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-7.0.0-rc.2-osx-x64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-7.0.0-rc.2-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-7.0.0-rc.2-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.0-rc.2/powershell-7.0.0-rc.2-linux-arm64.tar.gz +[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/PowerShell-7.1.0-preview.3-win-x64.msi +[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/PowerShell-7.1.0-preview.3-win-x86.msi +[pv-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-preview_7.1.0-preview.3-1.ubuntu.18.04_amd64.deb +[pv-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-preview_7.1.0-preview.3-1.ubuntu.16.04_amd64.deb +[pv-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-preview_7.1.0-preview.3-1.debian.9_amd64.deb +[pv-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-preview_7.1.0-preview.3-1.debian.10_amd64.deb +[pv-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-preview-7.1.0_preview.3-1.rhel.7.x86_64.rpm +[pv-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-preview-7.1.0_preview.3-1.centos.8.x86_64.rpm +[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-7.1.0-preview.3-osx-x64.pkg +[pv-winarm]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/PowerShell-7.1.0-preview.3-win-arm32.zip +[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/PowerShell-7.1.0-preview.3-win-arm64.zip +[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/PowerShell-7.1.0-preview.3-win-x86.zip +[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/PowerShell-7.1.0-preview.3-win-x64.zip +[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-7.1.0-preview.3-osx-x64.tar.gz +[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-7.1.0-preview.3-linux-x64.tar.gz +[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-7.1.0-preview.3-linux-arm32.tar.gz +[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.0-preview.3/powershell-7.1.0-preview.3-linux-arm64.tar.gz [pv-snap]: https://snapcraft.io/powershell-preview -[in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6 -[in-ubuntu14]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#ubuntu-1404 -[in-ubuntu16]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#ubuntu-1604 -[in-ubuntu18]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#ubuntu-1804 -[in-deb9]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#debian-9 -[in-centos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#centos-7 -[in-rhel7]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#red-hat-enterprise-linux-rhel-7 -[in-opensuse]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#opensuse -[in-fedora]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#fedora -[in-archlinux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#arch-linux -[in-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos?view=powershell-6 +[in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows +[in-ubuntu16]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1604 +[in-ubuntu18]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1804 +[in-deb9]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-9 +[in-centos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#centos-7 +[in-rhel7]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#red-hat-enterprise-linux-rhel-7 +[in-opensuse]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#opensuse +[in-fedora]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#fedora +[in-archlinux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#arch-linux +[in-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos [in-docker]: https://github.com/PowerShell/PowerShell-Docker -[in-kali]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#kali -[in-windows-zip]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6#zip -[in-tar-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#binary-archives -[in-tar-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos?view=powershell-6#binary-archives -[in-raspbian]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#raspbian -[in-arm]: https://docs.microsoft.com/powershell/scripting/install/powershell-core-on-arm?view=powershell-6 +[in-kali]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#kali +[in-windows-zip]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows#zip +[in-tar-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#binary-archives +[in-tar-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos#binary-archives +[in-raspbian]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#raspbian +[in-arm]: https://docs.microsoft.com/powershell/scripting/install/powershell-core-on-arm [corefx-win]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#windows [corefx-linux]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#linux [corefx-macos]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#macos @@ -124,9 +133,9 @@ To install a specific version, visit [releases](https://github.com/PowerShell/Po [Dashboard](https://aka.ms/psgithubbi) with visualizations for community contributions and project status using PowerShell, Azure, and PowerBI. -For more information on how and why we built this dashboard, check out this [blog post](https://blogs.msdn.microsoft.com/powershell/2017/01/31/powershell-open-source-community-dashboard/). +For more information on how and why we built this dashboard, check out this [blog post](https://devblogs.microsoft.com/powershell/powershell-open-source-community-dashboard/). -## Chat Room +## Chat Want to chat with other members of the PowerShell community? @@ -134,9 +143,10 @@ We have a Gitter Room which you can join below. [![Join the chat](https://img.shields.io/static/v1.svg?label=chat&message=on%20gitter&color=informational&logo=gitter)](https://gitter.im/PowerShell/PowerShell?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -There is also the community driven PowerShell Slack Team which you can sign up for at [Slack]. +There is also the community driven PowerShell Virtual User Group, which you can join on: -[Slack]: http://slack.poshcode.org +* [Slack](https://aka.ms/psslack) +* [Discord](https://aka.ms/psdiscord) ## Add-ons and libraries @@ -162,15 +172,7 @@ If you have any problems building, please consult the developer [FAQ][]. [FAQ]: https://github.com/PowerShell/PowerShell/tree/master/docs/FAQ.md -[az-windows-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-windows?branchName=master -[az-windows-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=19 -[az-linux-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-linux?branchName=master -[az-linux-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=17 -[az-macos-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-macos?branchName=master -[az-macos-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=14 -[az-spell-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-static-analysis?branchName=master -[az-spell-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=22 -[windows-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build/latest?definitionId=32 +[windows-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=32 [linux-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=23 [macos-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=24 [windows-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-Windows-daily diff --git a/Settings.StyleCop b/Settings.StyleCop index eae7b627566..7fa179ee02e 100644 --- a/Settings.StyleCop +++ b/Settings.StyleCop @@ -126,6 +126,11 @@ False + + + False + + diff --git a/assets/AppxManifest.xml b/assets/AppxManifest.xml index 8b245a3b25d..83df8c31b41 100644 --- a/assets/AppxManifest.xml +++ b/assets/AppxManifest.xml @@ -9,7 +9,7 @@ xmlns:desktop6="http://schemas.microsoft.com/appx/manifest/desktop/windows10/6" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"> - + $DISPLAYNAME$ diff --git a/assets/Product.wxs b/assets/Product.wxs index 6056a07ec20..699bffb5006 100644 --- a/assets/Product.wxs +++ b/assets/Product.wxs @@ -5,28 +5,36 @@ - - + + + + + + + - + + + + + + + - - - - + @@ -55,7 +63,7 @@ + Value=""[VersionFolder]pwsh.exe" -NoProfile -ExecutionPolicy Bypass -File "[VersionFolder]RegisterManifest.ps1"" /> + Value=""[VersionFolder]pwsh.exe" -NoProfile -ExecutionPolicy Bypass -Command "Enable-PSRemoting"" /> - - + + @@ -158,78 +166,83 @@ - - - - + + - + - + + + - + + - + ADD_PATH=1 - + + + + + - + ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL - - + + - + - + - + - + - + - + - + - + @@ -238,13 +251,12 @@ - + + Target="[VersionFolder]pwsh.exe" + Arguments="-WorkingDirectory ~" /> diff --git a/assets/files.wxs b/assets/files.wxs index ebf22a299a0..2420352c008 100644 --- a/assets/files.wxs +++ b/assets/files.wxs @@ -1,1939 +1,1929 @@ - - - + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + @@ -1941,1143 +1931,1182 @@ - + - + - + - + - + - - - - - - - - - - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + + + + + + + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + + + + + + + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + + + + + + + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - - - - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - + + + + + + + + + + + + + + + + + + + + - + @@ -3119,7 +3148,6 @@ - @@ -3212,7 +3240,6 @@ - @@ -3471,7 +3498,6 @@ - @@ -3671,7 +3697,6 @@ - @@ -3705,10 +3730,6 @@ - - - - @@ -3722,7 +3743,6 @@ - @@ -3742,14 +3762,12 @@ - - @@ -3782,7 +3800,6 @@ - @@ -3790,7 +3807,6 @@ - @@ -3817,7 +3833,6 @@ - @@ -3834,7 +3849,6 @@ - @@ -3859,13 +3873,11 @@ - - @@ -3886,7 +3898,6 @@ - @@ -3906,7 +3917,6 @@ - @@ -3933,7 +3943,6 @@ - @@ -3946,7 +3955,6 @@ - @@ -4013,7 +4021,6 @@ - @@ -4023,7 +4030,6 @@ - @@ -4063,7 +4069,40 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/license.rtf b/assets/license.rtf deleted file mode 100644 index 0129ec54408..00000000000 --- a/assets/license.rtf +++ /dev/null @@ -1,389 +0,0 @@ -{\rtf1\adeflang1025\ansi\ansicpg1252\uc1\adeff0\deff0\stshfdbch0\stshfloch31506\stshfhich31506\stshfbi31506\deflang1033\deflangfe1033\themelang1033\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f2\fbidi \fmodern\fcharset0\fprq1{\*\panose 02070309020205020404}Courier New;} -{\f3\fbidi \fdecor\fcharset2\fprq2{\*\panose 05050102010706020507}Symbol;}{\f10\fbidi \fdecor\fcharset2\fprq2{\*\panose 05000000000000000000}Wingdings;}{\f11\fbidi \fmodern\fcharset128\fprq1{\*\panose 02020609040205080304}MS Mincho{\*\falt ?l?r ??fc};} -{\f34\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria Math;}{\f37\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f42\fbidi \fswiss\fcharset0\fprq2{\*\panose 00000000000000000000}Tahoma;} -{\f43\fbidi \fswiss\fcharset0\fprq2{\*\panose 020b0603020202020204}Trebuchet MS;}{\f44\fbidi \fmodern\fcharset128\fprq1{\*\panose 02020609040205080304}@MS Mincho;} -{\flomajor\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fdbmajor\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;} -{\fhimajor\f31502\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0302020204030204}Calibri Light;}{\fbimajor\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;} -{\flominor\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fdbminor\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;} -{\fhiminor\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\fbiminor\f31507\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f45\fbidi \froman\fcharset238\fprq2 Times New Roman CE;} -{\f46\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\f48\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f49\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f50\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);} -{\f51\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\f52\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f53\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f65\fbidi \fmodern\fcharset238\fprq1 Courier New CE;} -{\f66\fbidi \fmodern\fcharset204\fprq1 Courier New Cyr;}{\f68\fbidi \fmodern\fcharset161\fprq1 Courier New Greek;}{\f69\fbidi \fmodern\fcharset162\fprq1 Courier New Tur;}{\f70\fbidi \fmodern\fcharset177\fprq1 Courier New (Hebrew);} -{\f71\fbidi \fmodern\fcharset178\fprq1 Courier New (Arabic);}{\f72\fbidi \fmodern\fcharset186\fprq1 Courier New Baltic;}{\f73\fbidi \fmodern\fcharset163\fprq1 Courier New (Vietnamese);} -{\f157\fbidi \fmodern\fcharset0\fprq1 MS Mincho Western{\*\falt ?l?r ??fc};}{\f155\fbidi \fmodern\fcharset238\fprq1 MS Mincho CE{\*\falt ?l?r ??fc};}{\f156\fbidi \fmodern\fcharset204\fprq1 MS Mincho Cyr{\*\falt ?l?r ??fc};} -{\f158\fbidi \fmodern\fcharset161\fprq1 MS Mincho Greek{\*\falt ?l?r ??fc};}{\f159\fbidi \fmodern\fcharset162\fprq1 MS Mincho Tur{\*\falt ?l?r ??fc};}{\f162\fbidi \fmodern\fcharset186\fprq1 MS Mincho Baltic{\*\falt ?l?r ??fc};} -{\f385\fbidi \froman\fcharset238\fprq2 Cambria Math CE;}{\f386\fbidi \froman\fcharset204\fprq2 Cambria Math Cyr;}{\f388\fbidi \froman\fcharset161\fprq2 Cambria Math Greek;}{\f389\fbidi \froman\fcharset162\fprq2 Cambria Math Tur;} -{\f392\fbidi \froman\fcharset186\fprq2 Cambria Math Baltic;}{\f393\fbidi \froman\fcharset163\fprq2 Cambria Math (Vietnamese);}{\f415\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\f416\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;} -{\f418\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\f419\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\f420\fbidi \fswiss\fcharset177\fprq2 Calibri (Hebrew);}{\f421\fbidi \fswiss\fcharset178\fprq2 Calibri (Arabic);} -{\f422\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\f423\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\f465\fbidi \fswiss\fcharset238\fprq2 Tahoma CE;}{\f466\fbidi \fswiss\fcharset204\fprq2 Tahoma Cyr;} -{\f468\fbidi \fswiss\fcharset161\fprq2 Tahoma Greek;}{\f469\fbidi \fswiss\fcharset162\fprq2 Tahoma Tur;}{\f470\fbidi \fswiss\fcharset177\fprq2 Tahoma (Hebrew);}{\f471\fbidi \fswiss\fcharset178\fprq2 Tahoma (Arabic);} -{\f472\fbidi \fswiss\fcharset186\fprq2 Tahoma Baltic;}{\f473\fbidi \fswiss\fcharset163\fprq2 Tahoma (Vietnamese);}{\f474\fbidi \fswiss\fcharset222\fprq2 Tahoma (Thai);}{\f475\fbidi \fswiss\fcharset238\fprq2 Trebuchet MS CE;} -{\f476\fbidi \fswiss\fcharset204\fprq2 Trebuchet MS Cyr;}{\f478\fbidi \fswiss\fcharset161\fprq2 Trebuchet MS Greek;}{\f479\fbidi \fswiss\fcharset162\fprq2 Trebuchet MS Tur;}{\f482\fbidi \fswiss\fcharset186\fprq2 Trebuchet MS Baltic;} -{\f487\fbidi \fmodern\fcharset0\fprq1 @MS Mincho Western;}{\f485\fbidi \fmodern\fcharset238\fprq1 @MS Mincho CE;}{\f486\fbidi \fmodern\fcharset204\fprq1 @MS Mincho Cyr;}{\f488\fbidi \fmodern\fcharset161\fprq1 @MS Mincho Greek;} -{\f489\fbidi \fmodern\fcharset162\fprq1 @MS Mincho Tur;}{\f492\fbidi \fmodern\fcharset186\fprq1 @MS Mincho Baltic;}{\flomajor\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;} -{\flomajor\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flomajor\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flomajor\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;} -{\flomajor\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flomajor\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flomajor\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;} -{\flomajor\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbmajor\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbmajor\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;} -{\fdbmajor\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbmajor\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbmajor\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);} -{\fdbmajor\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbmajor\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbmajor\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);} -{\fhimajor\f31528\fbidi \fswiss\fcharset238\fprq2 Calibri Light CE;}{\fhimajor\f31529\fbidi \fswiss\fcharset204\fprq2 Calibri Light Cyr;}{\fhimajor\f31531\fbidi \fswiss\fcharset161\fprq2 Calibri Light Greek;} -{\fhimajor\f31532\fbidi \fswiss\fcharset162\fprq2 Calibri Light Tur;}{\fhimajor\f31533\fbidi \fswiss\fcharset177\fprq2 Calibri Light (Hebrew);}{\fhimajor\f31534\fbidi \fswiss\fcharset178\fprq2 Calibri Light (Arabic);} -{\fhimajor\f31535\fbidi \fswiss\fcharset186\fprq2 Calibri Light Baltic;}{\fhimajor\f31536\fbidi \fswiss\fcharset163\fprq2 Calibri Light (Vietnamese);}{\fbimajor\f31538\fbidi \froman\fcharset238\fprq2 Times New Roman CE;} -{\fbimajor\f31539\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fbimajor\f31541\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbimajor\f31542\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;} -{\fbimajor\f31543\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fbimajor\f31544\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbimajor\f31545\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;} -{\fbimajor\f31546\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\flominor\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flominor\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;} -{\flominor\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flominor\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flominor\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);} -{\flominor\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flominor\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flominor\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);} -{\fdbminor\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbminor\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbminor\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;} -{\fdbminor\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbminor\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbminor\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);} -{\fdbminor\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbminor\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhiminor\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;} -{\fhiminor\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\fhiminor\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\fhiminor\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;} -{\fhiminor\f31573\fbidi \fswiss\fcharset177\fprq2 Calibri (Hebrew);}{\fhiminor\f31574\fbidi \fswiss\fcharset178\fprq2 Calibri (Arabic);}{\fhiminor\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;} -{\fhiminor\f31576\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\fbiminor\f31578\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fbiminor\f31579\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;} -{\fbiminor\f31581\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fbiminor\f31582\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fbiminor\f31583\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);} -{\fbiminor\f31584\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fbiminor\f31585\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fbiminor\f31586\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}} -{\colortbl;\red0\green0\blue0;\red0\green0\blue255;\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0; -\red128\green0\blue128;\red128\green0\blue0;\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;\red0\green0\blue0;\red0\green0\blue0;\red51\green51\blue51;}{\*\defchp \f31506\fs22 }{\*\defpap \ql \li0\ri0\sa160\sl259\slmult1 -\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\sa160\sl259\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs22\alang1025 \ltrch\fcs0 -\f31506\fs22\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \snext0 \sqformat \spriority0 Normal;}{\s1\ql \li0\ri0\sb120\sa120\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel0\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \ab\af42\afs19\alang1025 -\ltrch\fcs0 \fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext1 \slink15 \sqformat \styrsid7813854 heading 1;}{ -\s2\ql \li0\ri0\sb120\sa120\widctlpar\wrapdefault\aspalpha\aspnum\faauto\outlinelevel1\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \ab\af42\afs19\alang1025 \ltrch\fcs0 \fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 -\sbasedon0 \snext2 \slink16 \sqformat \styrsid7813854 heading 2;}{\s3\ql \fi-357\li1077\ri0\sb120\sa120\widctlpar\tx1077\jclisttab\tx1440\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl2\outlinelevel2\adjustright\rin0\lin1077\itap0 \rtlch\fcs1 -\af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext3 \slink17 \sqformat \styrsid7813854 heading 3;}{\s4\ql \fi-358\li1435\ri0\sb120\sa120\widctlpar -\jclisttab\tx1437\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl3\outlinelevel3\adjustright\rin0\lin1435\itap0 \rtlch\fcs1 \af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 -\sbasedon0 \snext4 \slink18 \sqformat \styrsid7813854 heading 4;}{\s5\ql \fi-357\li1792\ri0\sb120\sa120\widctlpar\tx1792\jclisttab\tx2155\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl4\outlinelevel4\adjustright\rin0\lin1792\itap0 \rtlch\fcs1 -\af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext5 \slink19 \sqformat \styrsid7813854 heading 5;}{\s6\ql \fi-357\li2149\ri0\sb120\sa120\widctlpar -\jclisttab\tx2152\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl5\outlinelevel5\adjustright\rin0\lin2149\itap0 \rtlch\fcs1 \af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 -\sbasedon0 \snext6 \slink20 \sqformat \styrsid7813854 heading 6;}{\s7\ql \fi-357\li2506\ri0\sb120\sa120\widctlpar\jclisttab\tx2509\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl6\outlinelevel6\adjustright\rin0\lin2506\itap0 \rtlch\fcs1 -\af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext7 \slink21 \sqformat \styrsid7813854 heading 7;}{\s8\ql \fi-357\li2863\ri0\sb120\sa120\widctlpar -\jclisttab\tx2866\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl7\outlinelevel7\adjustright\rin0\lin2863\itap0 \rtlch\fcs1 \af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 -\sbasedon0 \snext8 \slink22 \sqformat \styrsid7813854 heading 8;}{\s9\ql \fi-358\li3221\ri0\sb120\sa120\widctlpar\jclisttab\tx3223\wrapdefault\aspalpha\aspnum\faauto\ls12\ilvl8\outlinelevel8\adjustright\rin0\lin3221\itap0 \rtlch\fcs1 -\af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext9 \slink23 \sqformat \styrsid7813854 heading 9;}{\*\cs10 \additive \ssemihidden \sunhideused \spriority1 -Default Paragraph Font;}{\*\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\trcbpat1\trcfpat1\tblind0\tblindtype3\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv -\ql \li0\ri0\sa160\sl259\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31506\afs22\alang1025 \ltrch\fcs0 \f31506\fs22\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \snext11 \ssemihidden \sunhideused -Normal Table;}{\*\cs15 \additive \rtlch\fcs1 \ab\af42\afs19 \ltrch\fcs0 \fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink1 \slocked \styrsid7813854 Heading 1 Char;}{\*\cs16 \additive \rtlch\fcs1 \ab\af42\afs19 \ltrch\fcs0 -\fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink2 \slocked \styrsid7813854 Heading 2 Char;}{\*\cs17 \additive \rtlch\fcs1 \af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink3 \slocked \styrsid7813854 Heading 3 Char;}{\* -\cs18 \additive \rtlch\fcs1 \af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink4 \slocked \styrsid7813854 Heading 4 Char;}{\*\cs19 \additive \rtlch\fcs1 \af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 -\sbasedon10 \slink5 \slocked \styrsid7813854 Heading 5 Char;}{\*\cs20 \additive \rtlch\fcs1 \af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink6 \slocked \styrsid7813854 Heading 6 Char;}{\*\cs21 \additive \rtlch\fcs1 -\af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink7 \slocked \styrsid7813854 Heading 7 Char;}{\*\cs22 \additive \rtlch\fcs1 \af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 -\sbasedon10 \slink8 \slocked \styrsid7813854 Heading 8 Char;}{\*\cs23 \additive \rtlch\fcs1 \af42\afs19 \ltrch\fcs0 \b\fs19\loch\f42\hich\af42\dbch\af11 \sbasedon10 \slink9 \slocked \styrsid7813854 Heading 9 Char;}{ -\s24\ql \li0\ri0\sb100\sa100\sbauto1\saauto1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 \fs24\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 -\sbasedon0 \snext24 \sunhideused \styrsid3804850 Normal (Web);}{\s25\ql \li720\ri0\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin720\itap0 \rtlch\fcs1 \af37\afs22\alang1025 \ltrch\fcs0 -\f37\fs22\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext25 \sqformat \spriority34 \styrsid6173475 List Paragraph;}{\s26\ql \li0\ri0\widctlpar -\tx916\tx1832\tx2748\tx3664\tx4580\tx5496\tx6412\tx7328\tx8244\tx9160\tx10076\tx10992\tx11908\tx12824\tx13740\tx14656\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af2\afs20\alang1025 \ltrch\fcs0 -\f2\fs20\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext26 \slink27 \ssemihidden \sunhideused \styrsid6573559 HTML Preformatted;}{\*\cs27 \additive \rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \f2\fs20 -\sbasedon10 \slink26 \slocked \ssemihidden \styrsid6573559 HTML Preformatted Char;}{\*\cs28 \additive \rtlch\fcs1 \af0 \ltrch\fcs0 \ul\cf1 \sbasedon10 \sunhideused \styrsid7092439 Hyperlink;}{\*\cs29 \additive \rtlch\fcs1 \af0 \ltrch\fcs0 -\sbasedon10 \spriority0 \styrsid7092439 spelle;}{\*\cs30 \additive \rtlch\fcs1 \af0 \ltrch\fcs0 \sbasedon10 \spriority0 \styrsid7092439 grame;}{\s31\ql \li0\ri0\sb120\sa120\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 -\rtlch\fcs1 \af42\afs19\alang1025 \ltrch\fcs0 \b\fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext31 \styrsid7813854 Body 1;}{ -\s32\ql \li0\ri0\sb120\sa120\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \ab\af42\afs28\alang1025 \ltrch\fcs0 \fs28\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 -\sbasedon0 \snext0 \styrsid7813854 Heading EULA;}{\s33\ql \li0\ri0\sb120\sa120\widctlpar\brdrb\brdrs\brdrw10\brsp20 \wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \ab\af42\afs28\alang1025 \ltrch\fcs0 -\fs28\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext0 \styrsid7813854 Heading Software Title;}{\s34\ql \li0\ri0\sb120\sa120\widctlpar\brdrt\brdrs\brdrw10\brsp20 -\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \ab\af42\afs19\alang1025 \ltrch\fcs0 \fs19\lang1033\langfe1033\loch\f42\hich\af42\dbch\af11\cgrid\langnp1033\langfenp1033 \sbasedon0 \snext34 \styrsid7813854 -Preamble Border Above;}}{\*\listtable{\list\listtemplateid412752146\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;} -\f3\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 -\fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 -\fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 } -{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel -\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23 -\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid256596791}{\list\listtemplateid-234466468 -\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23 -\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0 -\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0 -\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative -\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0 -\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0 -{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid268852893}{\list\listtemplateid2071779370\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0 -\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative -\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0 -{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689 -\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers -;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid472724034}{\list\listtemplateid837583652\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext -\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689 -\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers -;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;} -\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 -\fi-360\li6480\lin6480 }{\listname ;}\listid678236712}{\list\listtemplateid468190476\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;} -\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;} -\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 -\fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 -\fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 } -{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname -;}\listid696808916}{\list\listtemplateid256027766\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 -\fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 -\fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 } -{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel -\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23 -\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid833446968}{\list\listtemplateid812297174 -{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \b\hres0\chhres0 \fi-360\li717\lin717 }{\listlevel\levelnfc4\levelnfcn4\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1077\lin1077 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1 -\levelspace0\levelindent0{\leveltext\'02\'02);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1437\lin1437 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext -\'03(\'03);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1797\lin1797 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'04);}{\levelnumbers\'02;} -\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2157\lin2157 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'05);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 -\hres0\chhres0 \fi-360\li2517\lin2517 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2877\lin2877 } -{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3237\lin3237 }{\listlevel\levelnfc2\levelnfcn2\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3597\lin3597 }{\listname ;}\listid888110291}{\list\listtemplateid812297174{\listlevel\levelnfc4 -\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \b\hres0\chhres0 \fi-360\li717\lin717 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0 -\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1077\lin1077 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0 -\levelindent0{\leveltext\'02\'02);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1437\lin1437 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext -\'03(\'03);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1797\lin1797 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'04);}{\levelnumbers\'02;} -\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2157\lin2157 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'05);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 -\hres0\chhres0 \fi-360\li2517\lin2517 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2877\lin2877 } -{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3237\lin3237 }{\listlevel\levelnfc2\levelnfcn2\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3597\lin3597 }{\listname ;}\listid1282881056}{\list\listtemplateid827650700\listhybrid{\listlevel -\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0 -\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1 -\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative -\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0 -{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid1470391773}{\list\listtemplateid-1331279738\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0 -\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext -\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;} -\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 } -{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23 -\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0 -\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid1543639483}{\list\listtemplateid812297174{\listlevel\levelnfc4\levelnfcn4 -\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \b\hres0\chhres0 \fi-360\li717\lin717 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0 -\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1077\lin1077 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0 -{\leveltext\'02\'02);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1437\lin1437 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'03);}{\levelnumbers -\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1797\lin1797 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'04);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 -\hres0\chhres0 \fi-360\li2157\lin2157 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'05);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2517\lin2517 } -{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2877\lin2877 }{\listlevel\levelnfc4\levelnfcn4\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3237\lin3237 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1 -\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3597\lin3597 }{\listname ;}\listid1670060985}{\list\listtemplateid-1676387632{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0 -\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00.;}{\levelnumbers\'01;}\rtlch\fcs1 \ab\ai0\af42\afs20 \ltrch\fcs0 \b\i0\f42\fs20\fbias0\hres0\chhres0 \fi-357\li357\jclisttab\tx360\lin357 }{\listlevel\levelnfc23\levelnfcn23\leveljc0 -\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'01\u-3913 _;}{\levelnumbers;}\b\i0\f3\fs20\fbias0\hres0\chhres0 \fi-363\li720\jclisttab\tx720\lin720 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1 -\levelspace0\levelindent0{\leveltext\'02\'02.;}{\levelnumbers\'01;}\rtlch\fcs1 \ab\ai0\af42\afs20 \ltrch\fcs0 \b\i0\f42\fs20\fbias0\hres0\chhres0 \s3\fi-357\li1077\jclisttab\tx1440\lin1077 }{\listlevel\levelnfc3\levelnfcn3\leveljc0\leveljcn0\levelfollow0 -\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'03.;}{\levelnumbers\'01;}\rtlch\fcs1 \ab0\ai0\af43\afs20 \ltrch\fcs0 \b0\i0\strike0\f43\fs20\ulnone\fbias0\hres0\chhres0 \s4\fi-358\li1435\jclisttab\tx1437\lin1435 }{\listlevel\levelnfc1\levelnfcn1 -\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'04.;}{\levelnumbers\'01;}\rtlch\fcs1 \ab0\ai0\af43\afs20 \ltrch\fcs0 \b0\i0\strike0\f43\fs20\ulnone\fbias0\hres0\chhres0 \s5\fi-357\li1792\jclisttab\tx2155\lin1792 } -{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'05.;}{\levelnumbers\'01;}\rtlch\fcs1 \ab0\ai0\af43\afs20 \ltrch\fcs0 \b0\i0\f43\fs20\fbias0\hres0\chhres0 \s6\fi-357\li2149 -\jclisttab\tx2152\lin2149 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;}\rtlch\fcs1 \ab0\ai0\af43\afs20 \ltrch\fcs0 \b0\i0\f43\fs20\fbias0\hres0\chhres0 -\s7\fi-357\li2506\jclisttab\tx2509\lin2506 }{\listlevel\levelnfc255\levelnfcn255\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02i.;}{\levelnumbers;}\rtlch\fcs1 \ab0\ai0\af43\afs20 \ltrch\fcs0 -\b0\i0\f43\fs20\fbias0\hres0\chhres0 \s8\fi-357\li2863\jclisttab\tx2866\lin2863 }{\listlevel\levelnfc255\levelnfcn255\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02A.;}{\levelnumbers;}\rtlch\fcs1 \ab0\ai0\af43\afs20 -\ltrch\fcs0 \b0\i0\f43\fs20\fbias0\hres0\chhres0 \s9\fi-358\li3221\jclisttab\tx3223\lin3221 }{\listname ;}\listid1743720866}{\list\listtemplateid-646571904\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1 -\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0 -\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689 -\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers -;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname ;}\listid2003921709}{\list\listtemplateid1067461628\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext -\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext -\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689 -\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers -;}\f2\fbias0\hres0\chhres0 \fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;} -\f3\fbias0\hres0\chhres0 \fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li5760\lin5760 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 -\fi-360\li6480\lin6480 }{\listname ;}\listid2022782249}{\list\listtemplateid1736062262\listhybrid{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\leveltemplateid67698693 -\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li720\lin720 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;} -\f2\fbias0\hres0\chhres0 \fi-360\li1440\lin1440 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;} -\f10\fbias0\hres0\chhres0 \fi-360\li2160\lin2160 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;} -\f3\fbias0\hres0\chhres0 \fi-360\li2880\lin2880 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 -\fi-360\li3600\lin3600 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 -\fi-360\li4320\lin4320 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698689\'01\u-3913 _;}{\levelnumbers;}\f3\fbias0\hres0\chhres0 -\fi-360\li5040\lin5040 }{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698691\'01o;}{\levelnumbers;}\f2\fbias0\hres0\chhres0 \fi-360\li5760\lin5760 } -{\listlevel\levelnfc23\levelnfcn23\leveljc0\leveljcn0\levelfollow0\levelstartat1\lvltentative\levelspace0\levelindent0{\leveltext\leveltemplateid67698693\'01\u-3929 _;}{\levelnumbers;}\f10\fbias0\hres0\chhres0 \fi-360\li6480\lin6480 }{\listname -;}\listid2055036124}{\list\listtemplateid812297174{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'00);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \b\hres0\chhres0 -\fi-360\li717\lin717 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'01);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1077\lin1077 }{\listlevel -\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'02);}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1437\lin1437 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0 -\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'03(\'03);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li1797\lin1797 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0 -\levelindent0{\leveltext\'03(\'04);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2157\lin2157 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext -\'03(\'05);}{\levelnumbers\'02;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2517\lin2517 }{\listlevel\levelnfc0\levelnfcn0\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'06.;}{\levelnumbers\'01;} -\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li2877\lin2877 }{\listlevel\levelnfc4\levelnfcn4\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'07.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 -\hres0\chhres0 \fi-360\li3237\lin3237 }{\listlevel\levelnfc2\levelnfcn2\leveljc0\leveljcn0\levelfollow0\levelstartat1\levelspace0\levelindent0{\leveltext\'02\'08.;}{\levelnumbers\'01;}\rtlch\fcs1 \af0 \ltrch\fcs0 \hres0\chhres0 \fi-360\li3597\lin3597 } -{\listname ;}\listid2106000387}}{\*\listoverridetable{\listoverride\listid256596791\listoverridecount0\ls1}{\listoverride\listid1543639483\listoverridecount0\ls2}{\listoverride\listid268852893\listoverridecount0\ls3}{\listoverride\listid678236712 -\listoverridecount0\ls4}{\listoverride\listid2022782249\listoverridecount0\ls5}{\listoverride\listid472724034\listoverridecount0\ls6}{\listoverride\listid1470391773\listoverridecount0\ls7}{\listoverride\listid2003921709\listoverridecount0\ls8} -{\listoverride\listid2055036124\listoverridecount0\ls9}{\listoverride\listid696808916\listoverridecount0\ls10}{\listoverride\listid833446968\listoverridecount0\ls11}{\listoverride\listid1743720866\listoverridecount0\ls12}{\listoverride\listid1670060985 -\listoverridecount0\ls13}{\listoverride\listid1282881056\listoverridecount0\ls14}{\listoverride\listid888110291\listoverridecount0\ls15}{\listoverride\listid2106000387\listoverridecount0\ls16}}{\*\pgptbl {\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0 -\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp10\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li300\ri300\sb300\sa300}{\pgp\ipgp0\itap0\li0\ri0 -\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}{\pgp\ipgp0\itap0\li0\ri0\sb0\sa0}}{\*\rsidtbl \rsid93983\rsid217518\rsid1376282\rsid1984289\rsid2438441\rsid3364025\rsid3804850\rsid5786794\rsid5845909\rsid6112664\rsid6173475 -\rsid6573559\rsid6758551\rsid6843334\rsid7092439\rsid7813854\rsid8005660\rsid8394862\rsid10169937\rsid10363382\rsid10624128\rsid10625519\rsid11493340\rsid13960513\rsid14557619\rsid16084641\rsid16459130}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0 -\msmallFrac0\mdispDef1\mlMargin0\mrMargin0\mdefJc1\mwrapIndent1440\mintLim0\mnaryLim1}{\info{\author Duane Okamoto (CELA)}{\operator Travis Plunk}{\creatim\yr2016\mo8\dy12\hr14\min30}{\revtim\yr2019\mo1\dy10\hr14\min49}{\version8}{\edmins14}{\nofpages1} -{\nofwords165}{\nofchars947}{\*\company Microsoft IT}{\nofcharsws1110}{\vern2819}}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}\paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\gutter0\ltrsect -\widowctrl\ftnbj\aenddoc\trackmoves0\trackformatting1\donotembedsysfont1\relyonvml0\donotembedlingdata0\grfdocevents0\validatexml1\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors1\noxlattoyen -\expshrtn\noultrlspc\dntblnsbdb\nospaceforul\formshade\horzdoc\dgmargin\dghspace180\dgvspace180\dghorigin1440\dgvorigin1440\dghshow1\dgvshow1 -\jexpand\viewkind1\viewscale232\pgbrdrhead\pgbrdrfoot\splytwnine\ftnlytwnine\htmautsp\nolnhtadjtbl\useltbaln\alntblind\lytcalctblwd\lyttblrtgr\lnbrkrule\nobrkwrptbl\snaptogridincell\allowfieldendsel\wrppunct -\asianbrkrule\rsidroot3804850\newtblstyruls\nogrowautofit\usenormstyforlist\noindnmbrts\felnbrelev\nocxsptable\indrlsweleven\noafcnsttbl\afelev\utinl\hwelev\spltpgpar\notcvasp\notbrkcnstfrctbl\notvatxbx\krnprsnet\cachedcolbal \nouicompat \fet0 -{\*\wgrffmtfilter 2450}\nofeaturethrottle1\ilfomacatclnup0\ltrpar \sectd \ltrsect\linex0\endnhere\sectlinegrid360\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang -{\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang -{\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}} -\pard\plain \ltrpar\s24\ql \li0\ri0\sb100\sa100\sbauto1\saauto1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0\pararsid3364025\contextualspace \rtlch\fcs1 \af0\afs24\alang1025 \ltrch\fcs0 -\fs24\lang1033\langfe1033\cgrid\langnp1033\langfenp1033 {\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \b\f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid2438441 PowerShell 6}{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \b\f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3804850 - -\par }{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \b\f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3364025\charrsid93983 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850\charrsid93983 Copyright (c) Microsoft Corporation}{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850 -\par }{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3364025\charrsid93983 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850\charrsid93983 All rights reserved.\~}{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850 -\par }{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3364025\charrsid93983 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850\charrsid93983 MIT License}{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850 -\par }{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3364025\charrsid93983 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850\charrsid93983 Permission is h -ereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:}{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850 - -\par }{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3364025\charrsid93983 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850\charrsid93983 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.}{\rtlch\fcs1 -\af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850 -\par }{\rtlch\fcs1 \af2\afs20 \ltrch\fcs0 \f2\fs20\cf19\lang9\langfe1033\langnp9\insrsid3364025\charrsid93983 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850\charrsid93983 -THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL T -HE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.}{\rtlch\fcs1 -\af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid3804850 -\par }{\rtlch\fcs1 \af2\afs18 \ltrch\fcs0 \f2\fs18\cf19\lang9\langfe1033\langnp9\insrsid6173475 -\par }{\*\themedata 504b030414000600080000002100e9de0fbfff0000001c020000130000005b436f6e74656e745f54797065735d2e786d6cac91cb4ec3301045f748fc83e52d4a -9cb2400825e982c78ec7a27cc0c8992416c9d8b2a755fbf74cd25442a820166c2cd933f79e3be372bd1f07b5c3989ca74aaff2422b24eb1b475da5df374fd9ad -5689811a183c61a50f98f4babebc2837878049899a52a57be670674cb23d8e90721f90a4d2fa3802cb35762680fd800ecd7551dc18eb899138e3c943d7e503b6 -b01d583deee5f99824e290b4ba3f364eac4a430883b3c092d4eca8f946c916422ecab927f52ea42b89a1cd59c254f919b0e85e6535d135a8de20f20b8c12c3b0 -0c895fcf6720192de6bf3b9e89ecdbd6596cbcdd8eb28e7c365ecc4ec1ff1460f53fe813d3cc7f5b7f020000ffff0300504b030414000600080000002100a5d6 -a7e7c0000000360100000b0000005f72656c732f2e72656c73848fcf6ac3300c87ef85bd83d17d51d2c31825762fa590432fa37d00e1287f68221bdb1bebdb4f -c7060abb0884a4eff7a93dfeae8bf9e194e720169aaa06c3e2433fcb68e1763dbf7f82c985a4a725085b787086a37bdbb55fbc50d1a33ccd311ba548b6309512 -0f88d94fbc52ae4264d1c910d24a45db3462247fa791715fd71f989e19e0364cd3f51652d73760ae8fa8c9ffb3c330cc9e4fc17faf2ce545046e37944c69e462 -a1a82fe353bd90a865aad41ed0b5b8f9d6fd010000ffff0300504b0304140006000800000021006b799616830000008a0000001c0000007468656d652f746865 -6d652f7468656d654d616e616765722e786d6c0ccc4d0ac3201040e17da17790d93763bb284562b2cbaebbf600439c1a41c7a0d29fdbd7e5e38337cedf14d59b -4b0d592c9c070d8a65cd2e88b7f07c2ca71ba8da481cc52c6ce1c715e6e97818c9b48d13df49c873517d23d59085adb5dd20d6b52bd521ef2cdd5eb9246a3d8b -4757e8d3f729e245eb2b260a0238fd010000ffff0300504b03041400060008000000210007b740aaca0600008f1a0000160000007468656d652f7468656d652f -7468656d65312e786d6cec595b8bdb46147e2ff43f08bd3bbe49be2cf1065bb69336bb49889d943cceda636bb2238dd18c776342a0244f7d2914d2d28706fad6 -87521a68a0a12ffd310b1bdaf447f4cc489667ec71f6420aa1640d8b34face996fce39face48ba7aed51449d239c70c2e2965bbe52721d1c8fd898c4d3967b6f -d82f345c870b148f1165316eb90bccdd6bbb9f7e7215ed881047d801fb98efa0961b0a31db2916f9088611bfc26638866b13964448c069322d8e13740c7e235a -ac944ab5628448ec3a318ac0ededc9848cb033942edddda5f31e85d358703930a2c940bac68685c28e0fcb12c1173ca089738468cb8579c6ec78881f09d7a188 -0bb8d0724beacf2dee5e2da29dcc888a2db69a5d5ffd657699c1f8b0a2e64ca607f9a49ee77bb576ee5f01a8d8c4f5eabd5aaf96fb5300341ac14a532eba4fbf -d3ec74fd0cab81d2438bef6ebd5b2d1b78cd7f758373db973f03af40a97f6f03dfef07104503af4029dedfc07b5ebd1278065e81527c6d035f2fb5bb5eddc02b -5048497cb8812ef9b56ab05c6d0e99307ac30a6ffa5ebf5ec99caf50500d7975c929262c16db6a2d420f59d2078004522448ec88c50c4fd008aa3840941c24c4 -d923d3100a6f8662c661b85429f54b55f82f7f9e3a5211413b1869d6921730e11b43928fc34709998996fb39787535c8e9ebd7274f5f9d3cfdfde4d9b393a7bf -66732b5786dd0d144f75bbb73f7df3cf8b2f9dbf7ffbf1edf36fd3a9d7f15cc7bff9e5ab377ffcf92ef7b0e255284ebf7bf9e6d5cbd3efbffeebe7e716efed04 -1de8f0218930776ee163e72e8b608116fef820b998c5304444b768c7538e622467b1f8ef89d040df5a208a2cb80e36e3783f01a9b101afcf1f1a8407613217c4 -e2f1661819c07dc6688725d628dc947369611ecee3a97df264aee3ee2274649b3b40b191e5de7c061a4b6c2e83101b34ef50140b34c531168ebcc60e31b6acee -0121465cf7c928619c4d84f380381d44ac21199203a39a56463748047959d80842be8dd8ecdf773a8cda56ddc5472612ee0d442de487981a61bc8ee602453697 -4314513de07b48843692834532d2713d2e20d3534c99d31b63ce6d36b71358af96f49b2033f6b4efd345642213410e6d3ef710633ab2cb0e831045331b7640e2 -50c77ec60fa144917387091b7c9f9977883c873ca0786bbaef136ca4fb6c35b8070aab535a1588bc324f2cb9bc8e9951bf83059d20aca4061a80a1eb1189cf14 -f93579f7ff3b7907113dfde1856545ef47d2ed8e8d7c5c50ccdb09b1de4d37d6247c1b6e5db803968cc987afdb5d348fef60b855369bd747d9fe28dbeeff5eb6 -b7ddcfef5fac57fa0cd22db7ade9765d6ddea3ad7bf709a174201614ef71b57de7d095c67d189476eab915e7cf72b3100ee59d0c1318b86982948d9330f10511 -e1204433d8e3975de964ca33d753eecc1887adbf1ab6fa96783a8ff6d9387d642d97e5e3692a1e1c89d578c9cfc7e17143a4e85a7df51896bb576ca7ea717949 -40da5e8484369949a26a21515f0eca20a98773089a85845ad97b61d1b4b06848f7cb546db0006a795660dbe4c066abe5fa1e9880113c55218ac7324f69aa97d9 -55c97c9f99de164ca302600fb1ac8055a69b92ebd6e5c9d5a5a5768e4c1b24b4723349a8c8a81ec64334c65975cad1f3d0b868ae9bab941af46428d47c505a2b -1af5c6bb585c36d760b7ae0d34d69582c6ce71cbad557d2899119ab5dc093cfac3613483dae172bb8be814de9f8d4492def097519659c24517f1300db8129d54 -0d222270e25012b55cb9fc3c0d34561aa2b8952b20081f2cb926c8ca87460e926e26194f267824f4b46b2332d2e929287caa15d6abcafcf26069c9e690ee4138 -3e760ee83cb98ba0c4fc7a5906704c38bc012aa7d11c1378a5990bd9aafed61a5326bbfa3b455543e938a2b310651d4517f314aea43ca7a3cef2186867d99a21 -a05a48b2467830950d560faad14df3ae9172d8da75cf369291d34473d5330d55915dd3ae62c60ccb36b016cbcb35798dd532c4a0697a874fa57b5d729b4bad5b -db27e45d02029ec7cfd275cfd110346aabc90c6a92f1a60c4bcdce46cddeb15ce019d4ced32434d5af2dddaec52def11d6e960f0529d1fecd6ab168626cb7da5 -8ab4faf6a17f9e60070f413cbaf022784e0557a9848f0f09820dd140ed4952d9805be491c86e0d3872e60969b98f4b7edb0b2a7e502835fc5ec1ab7aa542c36f -570b6ddfaf967b7eb9d4ed549e4063116154f6d3ef2e7d780d4517d9d71735bef105265abe69bb32625191a92f2c45455c7d812957b67f81710888cee35aa5df -ac363bb542b3daee17bc6ea7516806b54ea15b0beadd7e37f01bcdfe13d7395260af5d0dbc5aaf51a89583a0e0d54a927ea359a87b954adbabb71b3daffd24db -c6c0ca53f9c86201e155bc76ff050000ffff0300504b0304140006000800000021000dd1909fb60000001b010000270000007468656d652f7468656d652f5f72 -656c732f7468656d654d616e616765722e786d6c2e72656c73848f4d0ac2301484f78277086f6fd3ba109126dd88d0add40384e4350d363f2451eced0dae2c08 -2e8761be9969bb979dc9136332de3168aa1a083ae995719ac16db8ec8e4052164e89d93b64b060828e6f37ed1567914b284d262452282e3198720e274a939cd0 -8a54f980ae38a38f56e422a3a641c8bbd048f7757da0f19b017cc524bd62107bd5001996509affb3fd381a89672f1f165dfe514173d9850528a2c6cce0239baa -4c04ca5bbabac4df000000ffff0300504b01022d0014000600080000002100e9de0fbfff0000001c0200001300000000000000000000000000000000005b436f -6e74656e745f54797065735d2e786d6c504b01022d0014000600080000002100a5d6a7e7c0000000360100000b00000000000000000000000000300100005f72 -656c732f2e72656c73504b01022d00140006000800000021006b799616830000008a0000001c00000000000000000000000000190200007468656d652f746865 -6d652f7468656d654d616e616765722e786d6c504b01022d001400060008000000210007b740aaca0600008f1a00001600000000000000000000000000d60200 -007468656d652f7468656d652f7468656d65312e786d6c504b01022d00140006000800000021000dd1909fb60000001b01000027000000000000000000000000 -00d40900007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73504b050600000000050005005d010000cf0a00000000} -{\*\colorschememapping 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d3822207374616e64616c6f6e653d22796573223f3e0d0a3c613a636c724d -617020786d6c6e733a613d22687474703a2f2f736368656d61732e6f70656e786d6c666f726d6174732e6f72672f64726177696e676d6c2f323030362f6d6169 -6e22206267313d226c743122207478313d22646b3122206267323d226c743222207478323d22646b322220616363656e74313d22616363656e74312220616363 -656e74323d22616363656e74322220616363656e74333d22616363656e74332220616363656e74343d22616363656e74342220616363656e74353d22616363656e74352220616363656e74363d22616363656e74362220686c696e6b3d22686c696e6b2220666f6c486c696e6b3d22666f6c486c696e6b222f3e} -{\*\latentstyles\lsdstimax375\lsdlockeddef0\lsdsemihiddendef0\lsdunhideuseddef0\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;\lsdqformat1 \lsdlocked0 heading 1; -\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 2;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 3;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 4; -\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 5;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 6;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 7; -\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 8;\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdlocked0 heading 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 2; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 6; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 7;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 8;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index 9;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 1; -\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 2;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 3;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 4; -\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 5;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 6;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 7; -\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 8;\lsdsemihidden1 \lsdunhideused1 \lsdpriority39 \lsdlocked0 toc 9;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal Indent;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote text; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 header;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footer;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 index heading; -\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of figures;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope address; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 envelope return;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 footnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 line number; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 page number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote reference;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 endnote text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 table of authorities; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 macro;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 toa heading;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 4; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 4; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Bullet 5;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 4; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Number 5;\lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Closing;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Signature; -\lsdsemihidden1 \lsdunhideused1 \lsdpriority1 \lsdlocked0 Default Paragraph Font;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 4;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 List Continue 5; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Message Header;\lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Salutation;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Date; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text First Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Note Heading;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 2; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 2;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Body Text Indent 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Block Text; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 FollowedHyperlink;\lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;\lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Document Map;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Plain Text;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 E-mail Signature;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Top of Form; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Bottom of Form;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Normal (Web);\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Acronym;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Address; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Cite;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Code;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Definition;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Keyboard; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Preformatted;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Sample;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Typewriter;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 HTML Variable; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 annotation subject;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 No List;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 1;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 2; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Outline List 3;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Balloon Text;\lsdpriority39 \lsdlocked0 Table Grid;\lsdsemihidden1 \lsdlocked0 Placeholder Text;\lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing; -\lsdpriority60 \lsdlocked0 Light Shading;\lsdpriority61 \lsdlocked0 Light List;\lsdpriority62 \lsdlocked0 Light Grid;\lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdpriority64 \lsdlocked0 Medium Shading 2;\lsdpriority65 \lsdlocked0 Medium List 1; -\lsdpriority66 \lsdlocked0 Medium List 2;\lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdpriority68 \lsdlocked0 Medium Grid 2;\lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdpriority70 \lsdlocked0 Dark List;\lsdpriority71 \lsdlocked0 Colorful Shading; -\lsdpriority72 \lsdlocked0 Colorful List;\lsdpriority73 \lsdlocked0 Colorful Grid;\lsdpriority60 \lsdlocked0 Light Shading Accent 1;\lsdpriority61 \lsdlocked0 Light List Accent 1;\lsdpriority62 \lsdlocked0 Light Grid Accent 1; -\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;\lsdsemihidden1 \lsdlocked0 Revision;\lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph; -\lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1; -\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;\lsdpriority72 \lsdlocked0 Colorful List Accent 1;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 1; -\lsdpriority60 \lsdlocked0 Light Shading Accent 2;\lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdpriority62 \lsdlocked0 Light Grid Accent 2;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2; -\lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2; -\lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;\lsdpriority72 \lsdlocked0 Colorful List Accent 2;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;\lsdpriority60 \lsdlocked0 Light Shading Accent 3; -\lsdpriority61 \lsdlocked0 Light List Accent 3;\lsdpriority62 \lsdlocked0 Light Grid Accent 3;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 3; -\lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;\lsdpriority70 \lsdlocked0 Dark List Accent 3; -\lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;\lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;\lsdpriority60 \lsdlocked0 Light Shading Accent 4;\lsdpriority61 \lsdlocked0 Light List Accent 4; -\lsdpriority62 \lsdlocked0 Light Grid Accent 4;\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 4; -\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdpriority70 \lsdlocked0 Dark List Accent 4;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 4; -\lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdpriority60 \lsdlocked0 Light Shading Accent 5;\lsdpriority61 \lsdlocked0 Light List Accent 5;\lsdpriority62 \lsdlocked0 Light Grid Accent 5; -\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 5; -\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;\lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 5; -\lsdpriority72 \lsdlocked0 Colorful List Accent 5;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdpriority61 \lsdlocked0 Light List Accent 6;\lsdpriority62 \lsdlocked0 Light Grid Accent 6; -\lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;\lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdpriority66 \lsdlocked0 Medium List 2 Accent 6; -\lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;\lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdpriority70 \lsdlocked0 Dark List Accent 6;\lsdpriority71 \lsdlocked0 Colorful Shading Accent 6; -\lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;\lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis; -\lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;\lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdsemihidden1 \lsdunhideused1 \lsdpriority37 \lsdlocked0 Bibliography; -\lsdsemihidden1 \lsdunhideused1 \lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;\lsdpriority41 \lsdlocked0 Plain Table 1;\lsdpriority42 \lsdlocked0 Plain Table 2;\lsdpriority43 \lsdlocked0 Plain Table 3;\lsdpriority44 \lsdlocked0 Plain Table 4; -\lsdpriority45 \lsdlocked0 Plain Table 5;\lsdpriority40 \lsdlocked0 Grid Table Light;\lsdpriority46 \lsdlocked0 Grid Table 1 Light;\lsdpriority47 \lsdlocked0 Grid Table 2;\lsdpriority48 \lsdlocked0 Grid Table 3;\lsdpriority49 \lsdlocked0 Grid Table 4; -\lsdpriority50 \lsdlocked0 Grid Table 5 Dark;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 1; -\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 1;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 1;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 1; -\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 1;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 2;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 2; -\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 2;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 2; -\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 3;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 3;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 3;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 3; -\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 3;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 4; -\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 4;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 4;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 4;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 4; -\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 4;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 5; -\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 5;\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 5;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 5; -\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 5;\lsdpriority46 \lsdlocked0 Grid Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 Grid Table 2 Accent 6;\lsdpriority48 \lsdlocked0 Grid Table 3 Accent 6; -\lsdpriority49 \lsdlocked0 Grid Table 4 Accent 6;\lsdpriority50 \lsdlocked0 Grid Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 Grid Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 Grid Table 7 Colorful Accent 6; -\lsdpriority46 \lsdlocked0 List Table 1 Light;\lsdpriority47 \lsdlocked0 List Table 2;\lsdpriority48 \lsdlocked0 List Table 3;\lsdpriority49 \lsdlocked0 List Table 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark; -\lsdpriority51 \lsdlocked0 List Table 6 Colorful;\lsdpriority52 \lsdlocked0 List Table 7 Colorful;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 1;\lsdpriority47 \lsdlocked0 List Table 2 Accent 1;\lsdpriority48 \lsdlocked0 List Table 3 Accent 1; -\lsdpriority49 \lsdlocked0 List Table 4 Accent 1;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 1;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 1;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 1; -\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 2;\lsdpriority47 \lsdlocked0 List Table 2 Accent 2;\lsdpriority48 \lsdlocked0 List Table 3 Accent 2;\lsdpriority49 \lsdlocked0 List Table 4 Accent 2; -\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 2;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 2;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 2;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 3; -\lsdpriority47 \lsdlocked0 List Table 2 Accent 3;\lsdpriority48 \lsdlocked0 List Table 3 Accent 3;\lsdpriority49 \lsdlocked0 List Table 4 Accent 3;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 3; -\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 3;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 3;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 4;\lsdpriority47 \lsdlocked0 List Table 2 Accent 4; -\lsdpriority48 \lsdlocked0 List Table 3 Accent 4;\lsdpriority49 \lsdlocked0 List Table 4 Accent 4;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 4;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 4; -\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 4;\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 5;\lsdpriority47 \lsdlocked0 List Table 2 Accent 5;\lsdpriority48 \lsdlocked0 List Table 3 Accent 5; -\lsdpriority49 \lsdlocked0 List Table 4 Accent 5;\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 5;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 5;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 5; -\lsdpriority46 \lsdlocked0 List Table 1 Light Accent 6;\lsdpriority47 \lsdlocked0 List Table 2 Accent 6;\lsdpriority48 \lsdlocked0 List Table 3 Accent 6;\lsdpriority49 \lsdlocked0 List Table 4 Accent 6; -\lsdpriority50 \lsdlocked0 List Table 5 Dark Accent 6;\lsdpriority51 \lsdlocked0 List Table 6 Colorful Accent 6;\lsdpriority52 \lsdlocked0 List Table 7 Colorful Accent 6;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Mention; -\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Smart Hyperlink;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Hashtag;\lsdsemihidden1 \lsdunhideused1 \lsdlocked0 Unresolved Mention;}}{\*\datastore }} diff --git a/assets/pwsh.1.ronn b/assets/pwsh.1.ronn index 01e57148be0..bcc38f7b8b0 100644 --- a/assets/pwsh.1.ronn +++ b/assets/pwsh.1.ronn @@ -120,4 +120,3 @@ These are automatically defined PowerShell-language variables. ## COPYRIGHT Copyright (c) Microsoft Corporation. -All rights reserved. diff --git a/build.psm1 b/build.psm1 index bdc98a191f6..37c54470e20 100644 --- a/build.psm1 +++ b/build.psm1 @@ -1,6 +1,11 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +param( + # Skips a check that prevents building PowerShell on unsupported Linux distributions + [parameter(Mandatory = $false)][switch]$SkipLinuxDistroCheck = $false +) + Set-StrictMode -Version 3.0 # On Unix paths is separated by colon @@ -8,7 +13,7 @@ Set-StrictMode -Version 3.0 $script:TestModulePathSeparator = [System.IO.Path]::PathSeparator $script:Options = $null -$dotnetCLIChannel = 'release' +$dotnetCLIChannel = $(Get-Content $PSScriptRoot/DotnetRuntimeMetadata.json | ConvertFrom-Json).Sdk.Channel $dotnetCLIRequiredVersion = $(Get-Content $PSScriptRoot/global.json | ConvertFrom-Json).Sdk.Version # Track if tags have been sync'ed @@ -178,7 +183,11 @@ function Get-EnvironmentInformation $environment.IsSUSEFamily -or $environment.IsAlpine) ) { - throw "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell." + if ($SkipLinuxDistroCheck) { + Write-Warning "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell." + } else { + throw "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell. Import this module with '-ArgumentList `$true' to bypass this check." + } } } @@ -205,9 +214,16 @@ function Test-IsPreview param( [parameter(Mandatory)] [string] - $Version + $Version, + + [switch]$IsLTS ) + if ($IsLTS.IsPresent) { + ## If we are building a LTS package, then never consider it preview. + return $false + } + return $Version -like '*-*' } @@ -314,7 +330,7 @@ function Start-PSBuild { } if ($Clean) { - Write-Log "Cleaning your working directory. You can also do it with 'git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3'" + Write-Log -message "Cleaning your working directory. You can also do it with 'git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3'" Push-Location $PSScriptRoot try { # Excluded sqlite3 folder is due to this Roslyn issue: https://github.com/dotnet/roslyn/issues/23060 @@ -335,7 +351,7 @@ function Start-PSBuild { } # Verify if the dotnet in-use is the required version - $dotnetCLIInstalledVersion = (dotnet --version) + $dotnetCLIInstalledVersion = Start-NativeExecution -sb { dotnet --version } -IgnoreExitcode If ($dotnetCLIInstalledVersion -ne $dotnetCLIRequiredVersion) { Write-Warning @" The currently installed .NET Command Line Tools is not the required version. @@ -384,6 +400,13 @@ Fix steps: $Arguments += "/property:IsWindows=false" } + # Framework Dependent builds do not support ReadyToRun as it needs a specific runtime to optimize for. + # The property is set in Powershell.Common.props file. + # We override the property through the build command line. + if($Options.Runtime -like 'fxdependent*') { + $Arguments += "/property:PublishReadyToRun=false" + } + $Arguments += "--configuration", $Options.Configuration $Arguments += "--framework", $Options.Framework @@ -408,7 +431,7 @@ Fix steps: # handle ResGen # Heuristic to run ResGen on the fresh machine if ($ResGen -or -not (Test-Path "$PSScriptRoot/src/Microsoft.PowerShell.ConsoleHost/gen")) { - Write-Log "Run ResGen (generating C# bindings for resx files)" + Write-Log -message "Run ResGen (generating C# bindings for resx files)" Start-ResGen } @@ -416,7 +439,7 @@ Fix steps: # .inc file name must be different for Windows and Linux to allow build on Windows and WSL. $incFileName = "powershell_$($Options.Runtime).inc" if ($TypeGen -or -not (Test-Path "$PSScriptRoot/src/TypeCatalogGen/$incFileName")) { - Write-Log "Run TypeGen (generating CorePsTypeCatalog.cs)" + Write-Log -message "Run TypeGen (generating CorePsTypeCatalog.cs)" Start-TypeGen -IncFileName $incFileName } @@ -439,14 +462,14 @@ Fix steps: $Arguments += "/property:SDKToUse=Microsoft.NET.Sdk.WindowsDesktop" } - Write-Log "Run dotnet $Arguments from $PWD" + Write-Log -message "Run dotnet $Arguments from $PWD" Start-NativeExecution { dotnet $Arguments } - Write-Log "PowerShell output: $($Options.Output)" + Write-Log -message "PowerShell output: $($Options.Output)" if ($CrossGen) { ## fxdependent package cannot be CrossGen'ed Start-CrossGen -PublishPath $publishPath -Runtime $script:Options.Runtime - Write-Log "pwsh.exe with ngen binaries is available at: $($Options.Output)" + Write-Log -message "pwsh.exe with ngen binaries is available at: $($Options.Output)" } } else { $globalToolSrcFolder = Resolve-Path (Join-Path $Options.Top "../Microsoft.PowerShell.GlobalTool.Shim") | Select-Object -ExpandProperty Path @@ -457,14 +480,14 @@ Fix steps: $Arguments += "/property:SDKToUse=Microsoft.NET.Sdk.WindowsDesktop" } - Write-Log "Run dotnet $Arguments from $PWD" + Write-Log -message "Run dotnet $Arguments from $PWD" Start-NativeExecution { dotnet $Arguments } - Write-Log "PowerShell output: $($Options.Output)" + Write-Log -message "PowerShell output: $($Options.Output)" try { Push-Location $globalToolSrcFolder $Arguments += "--output", $publishPath - Write-Log "Run dotnet $Arguments from $PWD to build global tool entry point" + Write-Log -message "Run dotnet $Arguments from $PWD to build global tool entry point" Start-NativeExecution { dotnet $Arguments } } finally { @@ -524,10 +547,10 @@ Fix steps: $cryptoTarget = "/lib64/libcrypto.so.10" } - if ( ! (test-path "$publishPath/libssl.so.1.0.0")) { + if ( ! (Test-Path "$publishPath/libssl.so.1.0.0")) { $null = New-Item -Force -ItemType SymbolicLink -Target $sslTarget -Path "$publishPath/libssl.so.1.0.0" -ErrorAction Stop } - if ( ! (test-path "$publishPath/libcrypto.so.1.0.0")) { + if ( ! (Test-Path "$publishPath/libcrypto.so.1.0.0")) { $null = New-Item -Force -ItemType SymbolicLink -Target $cryptoTarget -Path "$publishPath/libcrypto.so.1.0.0" -ErrorAction Stop } } @@ -633,7 +656,7 @@ function Restore-PSPackage $ProjectDirs | ForEach-Object { $project = $_ - Write-Log "Run dotnet restore $project $RestoreArguments" + Write-Log -message "Run dotnet restore $project $RestoreArguments" $retryCount = 0 $maxTries = 5 while($retryCount -lt $maxTries) @@ -644,7 +667,7 @@ function Restore-PSPackage } catch { - Write-Log "Failed to restore $project, retrying..." + Write-Log -message "Failed to restore $project, retrying..." $retryCount++ if($retryCount -ge $maxTries) { @@ -653,7 +676,7 @@ function Restore-PSPackage continue } - Write-Log "Done restoring $project" + Write-Log -message "Done restoring $project" break } } @@ -668,7 +691,7 @@ function Restore-PSModuleToBuild $PublishPath ) - Write-Log "Restore PowerShell modules to $publishPath" + Write-Log -message "Restore PowerShell modules to $publishPath" $modulesDir = Join-Path -Path $publishPath -ChildPath "Modules" Copy-PSGalleryModules -Destination $modulesDir -CsProjPath "$PSScriptRoot\src\Modules\PSGalleryModules.csproj" @@ -682,7 +705,7 @@ function Restore-PSPester [ValidateNotNullOrEmpty()] [string] $Destination = ([IO.Path]::Combine((Split-Path (Get-PSOptions -DefaultToNew).Output), "Modules")) ) - Save-Module -Name Pester -Path $Destination -Repository PSGallery -RequiredVersion "4.8.0" + Save-Module -Name Pester -Path $Destination -Repository PSGallery -MaximumVersion 4.99 } function Compress-TestContent { @@ -705,8 +728,8 @@ function New-PSOptions { [ValidateSet("Debug", "Release", "CodeCoverage", '')] [string]$Configuration, - [ValidateSet("netcoreapp3.1")] - [string]$Framework = "netcoreapp3.1", + [ValidateSet("net5.0")] + [string]$Framework = "net5.0", # These are duplicated from Start-PSBuild # We do not use ValidateScript since we want tab completion @@ -781,11 +804,6 @@ function New-PSOptions { $Top = [IO.Path]::Combine($PSScriptRoot, "src", $PowerShellDir) Write-Verbose "Top project directory is $Top" - if (-not $Framework) { - $Framework = "netcoreapp2.1" - Write-Verbose "Using framework '$Framework'" - } - $Executable = if ($Runtime -like 'fxdependent*') { "pwsh.dll" } elseif ($environment.IsLinux -or $environment.IsMacOS) { @@ -879,7 +897,7 @@ function Get-PesterTag { $alltags = @{} $warnings = @() - get-childitem -Recurse $testbase -File | Where-Object {$_.name -match "tests.ps1"}| ForEach-Object { + Get-ChildItem -Recurse $testbase -File | Where-Object {$_.name -match "tests.ps1"}| ForEach-Object { $fullname = $_.fullname $tok = $err = $null $ast = [System.Management.Automation.Language.Parser]::ParseFile($FullName, [ref]$tok,[ref]$err) @@ -1267,7 +1285,7 @@ function Start-PSPester { break } - $count = ($lines | measure-object).Count + $count = ($lines | Measure-Object).Count if ($count -eq 0) { Start-Sleep -Seconds 1 @@ -1357,7 +1375,12 @@ function Publish-TestResults if($env:TF_BUILD) { $fileName = Split-Path -Leaf -Path $Path - $tempFilePath = Join-Path ([system.io.path]::GetTempPath()) -ChildPath $fileName + $tempPath = $env:BUILD_ARTIFACTSTAGINGDIRECTORY + if (! $tempPath) + { + $tempPath = [system.io.path]::GetTempPath() + } + $tempFilePath = Join-Path -Path $tempPath -ChildPath $fileName # NUnit allowed values are: Passed, Failed, Inconclusive or Ignored (the spec says Skipped but it doesn' work with Azure DevOps) # https://github.com/nunit/docs/wiki/Test-Result-XML-Format @@ -1424,12 +1447,12 @@ function Show-PSPesterError throw 'Unknown Show-PSPester parameter set' } - Write-Log -Error ("Description: " + $description) - Write-Log -Error ("Name: " + $name) - Write-Log -Error "message:" - Write-Log -Error $message - Write-Log -Error "stack-trace:" - Write-Log -Error $StackTrace + Write-Log -isError -message ("Description: " + $description) + Write-Log -isError -message ("Name: " + $name) + Write-Log -isError -message "message:" + Write-Log -isError -message $message + Write-Log -isError -message "stack-trace:" + Write-Log -isError -message $StackTrace } @@ -1455,7 +1478,7 @@ function Test-XUnitTestResults throw "Cannot convert $TestResultsFile to xml : $($_.message)" } - $failedTests = $results.assemblies.assembly.collection | Where-Object failed -gt 0 + $failedTests = $results.assemblies.assembly.collection | Where-Object failed -GT 0 if(-not $failedTests) { @@ -1469,12 +1492,12 @@ function Test-XUnitTestResults $message = $failure.test.failure.message.'#cdata-section' $StackTrace = $failure.test.failure.'stack-trace'.'#cdata-section' - Write-Log -Error ("Description: " + $description) - Write-Log -Error ("Name: " + $name) - Write-Log -Error "message:" - Write-Log -Error $message - Write-Log -Error "stack-trace:" - Write-Log -Error $StackTrace + Write-Log -isError -message ("Description: " + $description) + Write-Log -isError -message ("Name: " + $name) + Write-Log -isError -message "message:" + Write-Log -isError -message $message + Write-Log -isError -message "stack-trace:" + Write-Log -isError -message $StackTrace } throw "$($failedTests.failed) tests failed" @@ -1507,10 +1530,10 @@ function Test-PSPesterResults throw "Test result file '$testResultsFile' not found for $TestArea." } - $x = [xml](Get-Content -raw $testResultsFile) + $x = [xml](Get-Content -Raw $testResultsFile) if ([int]$x.'test-results'.failures -gt 0) { - Write-Log -Error "TEST FAILURES" + Write-Log -isError -message "TEST FAILURES" # switch between methods, SelectNode is not available on dotnet core if ( "System.Xml.XmlDocumentXPathExtensions" -as [Type] ) { @@ -1535,7 +1558,7 @@ function Test-PSPesterResults } elseif ($ResultObject.FailedCount -gt 0) { - Write-Log -Error 'TEST FAILURES' + Write-Log -isError -message 'TEST FAILURES' $ResultObject.TestResult | Where-Object {$_.Passed -eq $false} | ForEach-Object { Show-PSPesterError -testFailureObject $_ @@ -1614,7 +1637,8 @@ function Install-Dotnet { param( [string]$Channel = $dotnetCLIChannel, [string]$Version = $dotnetCLIRequiredVersion, - [switch]$NoSudo + [switch]$NoSudo, + [string]$InstallDir ) # This allows sudo install to be optional; needed when running in containers / as root @@ -1648,7 +1672,12 @@ function Install-Dotnet { $installScript = "dotnet-install.sh" Start-NativeExecution { & $curl -sO $installObtainUrl/$installScript - bash ./$installScript -c $Channel -v $Version + + if (-not $InstallDir) { + bash ./$installScript -c $Channel -v $Version + } else { + bash ./$installScript -c $Channel -v $Version -i $InstallDir + } } } elseif ($environment.IsWindows) { Remove-Item -ErrorAction SilentlyContinue -Recurse -Force ~\AppData\Local\Microsoft\dotnet @@ -1656,12 +1685,22 @@ function Install-Dotnet { Invoke-WebRequest -Uri $installObtainUrl/$installScript -OutFile $installScript if (-not $environment.IsCoreCLR) { - & ./$installScript -Channel $Channel -Version $Version + if (-not $InstallDir) { + & ./$installScript -Channel $Channel -Version $Version + } else { + & ./$installScript -Channel $Channel -Version $Version -InstallDir $InstallDir + } } else { # dotnet-install.ps1 uses APIs that are not supported in .NET Core, so we run it with Windows PowerShell $fullPSPath = Join-Path -Path $env:windir -ChildPath "System32\WindowsPowerShell\v1.0\powershell.exe" $fullDotnetInstallPath = Join-Path -Path $PWD.Path -ChildPath $installScript - Start-NativeExecution { & $fullPSPath -NoLogo -NoProfile -File $fullDotnetInstallPath -Channel $Channel -Version $Version } + Start-NativeExecution { + if (-not $InstallDir) { + & $fullPSPath -NoLogo -NoProfile -File $fullDotnetInstallPath -Channel $Channel -Version $Version + } else { + & $fullPSPath -NoLogo -NoProfile -File $fullDotnetInstallPath -Channel $Channel -Version $Version -InstallDir $InstallDir + } + } } } } @@ -1691,7 +1730,7 @@ function Start-PSBootstrap { [switch]$Force ) - Write-Log "Installing PowerShell build dependencies" + Write-Log -message "Installing PowerShell build dependencies" Push-Location $PSScriptRoot/tools @@ -1815,6 +1854,7 @@ function Start-PSBootstrap { if($environment.IsMacOS -or $env:TF_BUILD) { $gemsudo = $sudo } + Start-NativeExecution ([ScriptBlock]::Create("$gemsudo gem install ffi -v 1.12.0 --no-document")) Start-NativeExecution ([ScriptBlock]::Create("$gemsudo gem install fpm -v 1.11.0 --no-document")) Start-NativeExecution ([ScriptBlock]::Create("$gemsudo gem install ronn -v 0.7.3 --no-document")) } catch { @@ -1830,25 +1870,25 @@ function Start-PSBootstrap { $dotNetExists = precheck 'dotnet' $null $dotNetVersion = [string]::Empty if($dotNetExists) { - $dotNetVersion = (dotnet --version) + $dotNetVersion = Start-NativeExecution -sb { dotnet --version } -IgnoreExitcode } if(!$dotNetExists -or $dotNetVersion -ne $dotnetCLIRequiredVersion -or $Force.IsPresent) { if($Force.IsPresent) { - Write-Log "Installing dotnet due to -Force." + Write-Log -message "Installing dotnet due to -Force." } elseif(!$dotNetExists) { - Write-Log "dotnet not present. Installing dotnet." + Write-Log -message "dotnet not present. Installing dotnet." } else { - Write-Log "dotnet out of date ($dotNetVersion). Updating dotnet." + Write-Log "dotnet version $dotNetVersion does not match required version. Installing dotnet." } $DotnetArguments = @{ Channel=$Channel; Version=$Version; NoSudo=$NoSudo } Install-Dotnet @DotnetArguments } else { - Write-Log "dotnet is already installed. Skipping installation." + Write-Log -message "dotnet is already installed. Skipping installation." } # Install Windows dependencies if `-Package` or `-BuildWindowsNative` is specified @@ -1856,7 +1896,7 @@ function Start-PSBootstrap { ## The VSCode build task requires 'pwsh.exe' to be found in Path if (-not (Get-Command -Name pwsh.exe -CommandType Application -ErrorAction Ignore)) { - Write-Log "pwsh.exe not found. Install latest PowerShell release and add it to Path" + Write-Log -message "pwsh.exe not found. Install latest PowerShell release and add it to Path" $psInstallFile = [System.IO.Path]::Combine($PSScriptRoot, "tools", "install-powershell.ps1") & $psInstallFile -AddToPath } @@ -2010,7 +2050,7 @@ function Find-Dotnet() { if (precheck dotnet) { # Must run from within repo to ensure global.json can specify the required SDK version Push-Location $PSScriptRoot - $dotnetCLIInstalledVersion = (dotnet --version) + $dotnetCLIInstalledVersion = Start-NativeExecution -sb { dotnet --version } -IgnoreExitcode Pop-Location if ($dotnetCLIInstalledVersion -ne $dotnetCLIRequiredVersion) { Write-Warning "The 'dotnet' in the current path can't find SDK version ${dotnetCLIRequiredVersion}, prepending $dotnetPath to PATH." @@ -2063,7 +2103,7 @@ function script:Use-MSBuild { # msbuild v14 and msbuild v4 behaviors are different for XAML generation $frameworkMsBuildLocation = "${env:SystemRoot}\Microsoft.Net\Framework\v4.0.30319\msbuild" - $msbuild = get-command msbuild -ErrorAction Ignore + $msbuild = Get-Command msbuild -ErrorAction Ignore if ($msbuild) { # all good, nothing to do return @@ -2202,16 +2242,55 @@ function Start-CrossGen { # Generate the ngen assembly Write-Verbose "Generating assembly $niAssemblyName" Start-NativeExecution { - & $CrossgenPath /MissingDependenciesOK /in $AssemblyPath /out $outputAssembly /Platform_Assemblies_Paths $platformAssembliesPath + & $CrossgenPath /ReadyToRun /MissingDependenciesOK /in $AssemblyPath /out $outputAssembly /Platform_Assemblies_Paths $platformAssembliesPath } | Write-Verbose + } finally { + Pop-Location + } + } - <# - # TODO: Generate the pdb for the ngen binary - currently, there is a hard dependency on diasymreader.dll, which is available at %windir%\Microsoft.NET\Framework\v4.0.30319. - # However, we still need to figure out the prerequisites on Linux. - Start-NativeExecution { - & $CrossgenPath /Platform_Assemblies_Paths $platformAssembliesPath /CreatePDB $platformAssembliesPath /lines $platformAssembliesPath $niAssemblyName - } | Write-Verbose - #> + function New-CrossGenSymbol { + param ( + [Parameter(Mandatory= $true)] + [ValidateNotNullOrEmpty()] + [String] + $AssemblyPath, + [Parameter(Mandatory= $true)] + [ValidateNotNullOrEmpty()] + [String] + $CrossgenPath + ) + + + $platformAssembliesPath = Split-Path $AssemblyPath -Parent + $crossgenFolder = Split-Path $CrossgenPath + + try { + Push-Location $crossgenFolder + + $symbolsPath = [System.IO.Path]::ChangeExtension($assemblyPath, ".pdb") + + $createSymbolOptionName = $null + if($Environment.IsWindows) + { + $createSymbolOptionName = '-CreatePDB' + + } + elseif ($Environment.IsLinux) + { + $createSymbolOptionName = '-CreatePerfMap' + } + + if($createSymbolOptionName) + { + Start-NativeExecution { + & $CrossgenPath -readytorun -platform_assemblies_paths $platformAssembliesPath $createSymbolOptionName $platformAssembliesPath $AssemblyPath + } | Write-Verbose + } + + # Rename the corresponding ni.dll assembly to be the same as the IL assembly + $niSymbolsPath = [System.IO.Path]::ChangeExtension($symbolsPath, "ni.pdb") + Rename-Item $niSymbolsPath $symbolsPath -Force -ErrorAction Stop } finally { Pop-Location } @@ -2223,6 +2302,7 @@ function Start-CrossGen { # Get the path to crossgen $crossGenExe = if ($environment.IsWindows) { "crossgen.exe" } else { "crossgen" } + $generateSymbols = $false # The crossgen tool is only published for these particular runtimes $crossGenRuntime = if ($environment.IsWindows) { @@ -2230,11 +2310,15 @@ function Start-CrossGen { "win-x86" } elseif ($Runtime -match "-x64") { "win-x64" + $generateSymbols = $true } elseif (!($env:PROCESSOR_ARCHITECTURE -match "arm")) { throw "crossgen for 'win-arm' and 'win-arm64' must be run on that platform" } } elseif ($Runtime -eq "linux-arm") { throw "crossgen is not available for 'linux-arm'" + } elseif ($Runtime -eq "linux-x64") { + $Runtime + # We should set $generateSymbols = $true, but the code needs to be adjusted for different extension on Linux } else { $Runtime } @@ -2243,7 +2327,7 @@ function Start-CrossGen { throw "crossgen is not available for this platform" } - $dotnetRuntimeVersion = $script:Options.Framework -replace 'netcoreapp' + $dotnetRuntimeVersion = $script:Options.Framework -replace 'net' # Get the CrossGen.exe for the correct runtime with the latest version $crossGenPath = Get-ChildItem $script:Environment.nugetPackagesRoot $crossGenExe -Recurse | ` @@ -2306,29 +2390,7 @@ function Start-CrossGen { "Microsoft.ApplicationInsights.dll" ) - # Common PowerShell libraries to crossgen - $psCoreAssemblyList = @( - "pwsh.dll", - "Microsoft.PowerShell.Commands.Utility.dll", - "Microsoft.PowerShell.Commands.Management.dll", - "Microsoft.PowerShell.Security.dll", - "Microsoft.PowerShell.ConsoleHost.dll", - "System.Management.Automation.dll" - ) - - # Add Windows specific libraries - if ($environment.IsWindows) { - $psCoreAssemblyList += @( - "Microsoft.PowerShell.CoreCLR.Eventing.dll", - "Microsoft.WSMan.Management.dll", - "Microsoft.WSMan.Runtime.dll", - "Microsoft.PowerShell.Commands.Diagnostics.dll", - "Microsoft.PowerShell.GraphicalHost.dll", - "Microsoft.Management.Infrastructure.CimCmdlets.dll" - ) - } - - $fullAssemblyList = $commonAssembliesForAddType + $psCoreAssemblyList + $fullAssemblyList = $commonAssembliesForAddType foreach ($assemblyName in $fullAssemblyList) { $assemblyPath = Join-Path $PublishPath $assemblyName @@ -2350,15 +2412,21 @@ function Start-CrossGen { Remove-Item $assemblyPath -Force -ErrorAction Stop + # Rename the corresponding ni.dll assembly to be the same as the IL assembly + $niAssemblyPath = [System.IO.Path]::ChangeExtension($assemblyPath, "ni.dll") + Rename-Item $niAssemblyPath $assemblyPath -Force -ErrorAction Stop + # No symbols are available for Microsoft.CodeAnalysis.CSharp.dll, Microsoft.CodeAnalysis.dll, # Microsoft.CodeAnalysis.VisualBasic.dll, and Microsoft.CSharp.dll. if ($commonAssembliesForAddType -notcontains $assemblyName) { Remove-Item $symbolsPath -Force -ErrorAction Stop - } - # Rename the corresponding ni.dll assembly to be the same as the IL assembly - $niAssemblyPath = [System.IO.Path]::ChangeExtension($assemblyPath, "ni.dll") - Rename-Item $niAssemblyPath $assemblyPath -Force -ErrorAction Stop + if($generateSymbols) + { + Write-Verbose "Generating Symbols for $assemblyPath" + New-CrossGenSymbol -CrossgenPath $crossGenPath -AssemblyPath $assemblyPath + } + } } } @@ -2398,7 +2466,7 @@ function Copy-PSGalleryModules Restore-PSPackage -ProjectDirs (Split-Path $CsProjPath) -Force:$Force.IsPresent $cache = dotnet nuget locals global-packages -l - if ($cache -match "info : global-packages: (.*)") { + if ($cache -match "global-packages: (.*)") { $nugetCache = $Matches[1] } else { @@ -2410,7 +2478,7 @@ function Copy-PSGalleryModules foreach ($m in $psGalleryProj.Project.ItemGroup.PackageReference) { $name = $m.Include $version = $m.Version - Write-Log "Name='$Name', Version='$version', Destination='$Destination'" + Write-Log -message "Name='$Name', Version='$version', Destination='$Destination'" # Remove the build revision from the src (nuget drops it). $srcVer = if ($version -match "(\d+.\d+.\d+).0") { @@ -2815,17 +2883,17 @@ assembly PROCESS { #### MAIN #### foreach ( $log in $Logfile ) { - foreach ( $logpath in (resolve-path $log).path ) { - write-progress "converting file $logpath" + foreach ( $logpath in (Resolve-Path $log).path ) { + Write-Progress "converting file $logpath" if ( ! $logpath) { throw "Cannot resolve $Logfile" } - $x = [xml](get-content -raw -readcount 0 $logpath) + $x = [xml](Get-Content -Raw -ReadCount 0 $logpath) if ( $x.psobject.properties['test-results'] ) { $Logs += convert-pesterlog $x $logpath -includeempty:$includeempty } elseif ( $x.psobject.properties['assemblies'] ) { $Logs += convert-xunitlog $x $logpath -includeEmpty:$includeEmpty } else { - write-error "Cannot determine log type" + Write-Error "Cannot determine log type" } } } @@ -3105,7 +3173,7 @@ function New-TestPackage else { $null = New-Item -Path $Destination -ItemType Directory -Force - Write-Verbose -Message "Creating destination folder: $Destination" + Write-Verbose -message "Creating destination folder: $Destination" } $rootFolder = $env:TEMP @@ -3126,12 +3194,12 @@ function New-TestPackage $null = Publish-PSTestTools -runtime $Runtime $powerShellTestRoot = Join-Path $PSScriptRoot 'test' Copy-Item $powerShellTestRoot -Recurse -Destination $packageRoot -Force - Write-Verbose -Message "Copied test directory" + Write-Verbose -message "Copied test directory" # Copy assests folder to package root for wix related tests. $assetsPath = Join-Path $PSScriptRoot 'assets' Copy-Item $assetsPath -Recurse -Destination $packageRoot -Force - Write-Verbose -Message "Copied assests directory" + Write-Verbose -message "Copied assests directory" # Create expected folder structure for resx files in package root. $srcRootForResx = New-Item -Path "$packageRoot/src" -Force -ItemType Directory @@ -3147,7 +3215,7 @@ function New-TestPackage $assemblyPart = $assemblyPart.TrimStart([io.path]::DirectorySeparatorChar) $resxDestPath = Join-Path $srcRootForResx $assemblyPart $null = New-Item -Path $resxDestPath -Force -ItemType Directory - Write-Verbose -Message "Created resx directory : $resxDestPath" + Write-Verbose -message "Created resx directory : $resxDestPath" Copy-Item -Path "$directoryFullName\*" -Recurse $resxDestPath -Force } diff --git a/demos/Apache/Apache/Apache.psm1 b/demos/Apache/Apache/Apache.psm1 index 489502a6d39..5f980f26bae 100644 --- a/demos/Apache/Apache/Apache.psm1 +++ b/demos/Apache/Apache/Apache.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. #Region utility functions diff --git a/demos/Apache/apache-demo.ps1 b/demos/Apache/apache-demo.ps1 index 1f5d60587d7..299ce0cc0de 100644 --- a/demos/Apache/apache-demo.ps1 +++ b/demos/Apache/apache-demo.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Import-Module $PSScriptRoot/Apache/Apache.psm1 @@ -8,12 +8,12 @@ Write-Host -Foreground Blue "Get installed Apache Modules like *proxy* and Sort Get-ApacheModule | Where-Object {$_.ModuleName -like "*proxy*"} | Sort-Object ModuleName | Out-Host #Graceful restart of Apache -Write-host -Foreground Blue "Restart Apache Server gracefully" +Write-Host -Foreground Blue "Restart Apache Server gracefully" Restart-ApacheHTTPServer -Graceful | Out-Host #Enumerate current virtual hosts (web sites) Write-Host -Foreground Blue "Enumerate configured Apache Virtual Hosts" -Get-ApacheVHost |out-host +Get-ApacheVHost |Out-Host #Add a new virtual host Write-Host -Foreground Yellow "Create a new Apache Virtual Host" @@ -21,7 +21,7 @@ New-ApacheVHost -ServerName "mytestserver" -DocumentRoot /var/www/html/mytestser #Enumerate new set of virtual hosts Write-Host -Foreground Blue "Enumerate Apache Virtual Hosts Again" -Get-ApacheVHost |out-host +Get-ApacheVHost |Out-Host #Cleanup Write-Host -Foreground Blue "Remove demo virtual host" diff --git a/demos/Azure/Azure-Demo.ps1 b/demos/Azure/Azure-Demo.ps1 index f75aa3e2d02..22b316686a7 100644 --- a/demos/Azure/Azure-Demo.ps1 +++ b/demos/Azure/Azure-Demo.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ### The techniques used in this demo are documented at diff --git a/demos/DSC/dsc-demo.ps1 b/demos/DSC/dsc-demo.ps1 index f393916408b..3abd642a3b4 100644 --- a/demos/DSC/dsc-demo.ps1 +++ b/demos/DSC/dsc-demo.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. #Get Distro type and set distro-specific variables diff --git a/demos/DSC/readme.md b/demos/DSC/readme.md index 8b134473eb4..0ce83fb3efa 100644 --- a/demos/DSC/readme.md +++ b/demos/DSC/readme.md @@ -1,6 +1,6 @@ # DSC MOF Compilation Demo -[PowerShell Desired State Configuration](https://docs.microsoft.com/powershell/scripting/dsc/overview/overview?view=powershell-6) is a declarative configuration platform for Windows and Linux. +[PowerShell Desired State Configuration](https://docs.microsoft.com/powershell/scripting/dsc/overview/overview) is a declarative configuration platform for Windows and Linux. DSC configurations can be authored in PowerShell and compiled into the resultant MOF document. This demo shows use of PowerShell to author a DSC configuration to set the configuration of an Apache web server. PowerShell scripting is used to assess distribution and version-specific properties, diff --git a/demos/Docker-PowerShell/Docker-PowerShell.ps1 b/demos/Docker-PowerShell/Docker-PowerShell.ps1 index 4639f7ee1d0..18eb844fd32 100644 --- a/demos/Docker-PowerShell/Docker-PowerShell.ps1 +++ b/demos/Docker-PowerShell/Docker-PowerShell.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # This is a short example of the Docker-PowerShell module. The same cmdlets may be used to manage both local & remote machines, including both Windows & Linux hosts @@ -20,10 +20,10 @@ Run-ContainerImage hello-world # Linux cls # List all containers that have exited -Get-Container | Where-Object State -eq "exited" +Get-Container | Where-Object State -EQ "exited" # That found the right one, so go ahead and remove it -Get-Container | Where-Object State -eq "exited" | Remove-Container +Get-Container | Where-Object State -EQ "exited" | Remove-Container # Now remove the container image Remove-ContainerImage hello-world diff --git a/demos/SystemD/SystemD/SystemD.psm1 b/demos/SystemD/SystemD/SystemD.psm1 index b127a2e5169..d1bf0d8e890 100644 --- a/demos/SystemD/SystemD/SystemD.psm1 +++ b/demos/SystemD/SystemD/SystemD.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Function Get-SystemDJournal { @@ -11,7 +11,7 @@ Function Get-SystemDJournal { $Result = & $sudocmd $cmd $journalctlParameters -o json --no-pager Try { - $JSONResult = $Result|ConvertFrom-JSON + $JSONResult = $Result|ConvertFrom-Json $JSONResult } Catch diff --git a/demos/SystemD/journalctl-demo.ps1 b/demos/SystemD/journalctl-demo.ps1 index c979a97467b..2597bdc3b66 100644 --- a/demos/SystemD/journalctl-demo.ps1 +++ b/demos/SystemD/journalctl-demo.ps1 @@ -1,12 +1,12 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Import-Module $PSScriptRoot/SystemD/SystemD.psm1 #list recent journal events -Write-host -Foreground Blue "Get recent SystemD journal messages" +Write-Host -Foreground Blue "Get recent SystemD journal messages" Get-SystemDJournal -args "-xe" |Out-Host #Drill into SystemD unit messages -Write-host -Foreground Blue "Get recent SystemD journal messages for services and return Unit, Message" -Get-SystemDJournal -args "-xe" | Where-Object {$_._SYSTEMD_UNIT -like "*.service"} | Format-Table _SYSTEMD_UNIT, MESSAGE | Select-Object -first 10 | Out-Host +Write-Host -Foreground Blue "Get recent SystemD journal messages for services and return Unit, Message" +Get-SystemDJournal -args "-xe" | Where-Object {$_._SYSTEMD_UNIT -like "*.service"} | Format-Table _SYSTEMD_UNIT, MESSAGE | Select-Object -First 10 | Out-Host diff --git a/demos/WindowsPowerShellModules/README.md b/demos/WindowsPowerShellModules/README.md index b8e23cffb40..3cf63bd947e 100644 --- a/demos/WindowsPowerShellModules/README.md +++ b/demos/WindowsPowerShellModules/README.md @@ -3,7 +3,7 @@ ## Windows PowerShell vs PowerShell Core Existing Windows PowerShell users are familiar with the large number of modules available, however, they are not necessarily compatible with PowerShell Core. -More information regarding compatibility is in a [blog post](https://blogs.msdn.microsoft.com/powershell/2017/07/14/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). +More information regarding compatibility is in a [blog post](https://devblogs.microsoft.com/powershell/powershell-6-0-roadmap-coreclr-backwards-compatibility-and-more/). Windows PowerShell 5.1 is based on .Net Framework 4.6.1, while PowerShell Core is based on .Net Core 2.x. Although both adhere to .Net Standard 2.0 and can be compatible, some modules may be using APIs or cmdlets not supported on CoreCLR or using APIs from Windows PowerShell that have been deprecated and removed from PowerShell Core (for example, PSSnapins). diff --git a/demos/crontab/CronTab/CronTab.psd1 b/demos/crontab/CronTab/CronTab.psd1 index df7d8149420..aabc48e572e 100755 --- a/demos/crontab/CronTab/CronTab.psd1 +++ b/demos/crontab/CronTab/CronTab.psd1 @@ -19,7 +19,7 @@ Author = 'PowerShell' CompanyName = 'Microsoft Corporation' # Copyright statement for this module -Copyright = 'Copyright (c) Microsoft Corporation. All rights reserved.' +Copyright = 'Copyright (c) Microsoft Corporation.' # Description of the functionality provided by this module Description = 'Sample module for managing CronTab' diff --git a/demos/crontab/CronTab/CronTab.psm1 b/demos/crontab/CronTab/CronTab.psm1 index 1b5bcfb2b79..d354419c9bf 100644 --- a/demos/crontab/CronTab/CronTab.psm1 +++ b/demos/crontab/CronTab/CronTab.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. using namespace System.Collections.Generic diff --git a/demos/crontab/crontab.ps1 b/demos/crontab/crontab.ps1 index 72cc084d41e..3d0ee0741ea 100644 --- a/demos/crontab/crontab.ps1 +++ b/demos/crontab/crontab.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Import-Module $PSScriptRoot/CronTab/CronTab.psd1 diff --git a/demos/dsc.ps1 b/demos/dsc.ps1 index 8f93dd507c3..c59be643edc 100644 --- a/demos/dsc.ps1 +++ b/demos/dsc.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # DSC MOF Compilation diff --git a/demos/powershellget/PowerShellGet.ps1 b/demos/powershellget/PowerShellGet.ps1 index 0dc33f85c46..e93216851da 100644 --- a/demos/powershellget/PowerShellGet.ps1 +++ b/demos/powershellget/PowerShellGet.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. #region find, install, update, uninstall the PowerShell scripts from an online repository. diff --git a/demos/python/class1.ps1 b/demos/python/class1.ps1 index 291677fd948..b74c0c8d5d6 100644 --- a/demos/python/class1.ps1 +++ b/demos/python/class1.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # @@ -10,5 +10,5 @@ # picking up the Python script from the same directory # -& $PSScriptRoot/class1.py | ConvertFrom-JSON +& $PSScriptRoot/class1.py | ConvertFrom-Json diff --git a/demos/python/demo_script.ps1 b/demos/python/demo_script.ps1 index 586e14a2085..af2067642a1 100644 --- a/demos/python/demo_script.ps1 +++ b/demos/python/demo_script.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # @@ -20,7 +20,7 @@ $data @" #!/usr/bin/python3 print('Hi!') -"@ | out-file -encoding ascii hi +"@ | Out-File -Encoding ascii hi # Make it executable chmod +x hi @@ -35,7 +35,7 @@ cat class1.py ./class1.py # Capture the data as structured objects (arrays and hashtables) -$data = ./class1.py | ConvertFrom-JSON +$data = ./class1.py | ConvertFrom-Json # look at the first element of the returned array $data[0] diff --git a/demos/python/inline_python.ps1 b/demos/python/inline_python.ps1 index fdad32a8601..71b65215f74 100644 --- a/demos/python/inline_python.ps1 +++ b/demos/python/inline_python.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # diff --git a/demos/rest/rest.ps1 b/demos/rest/rest.ps1 index 3f2364f9507..f40b49b6538 100644 --- a/demos/rest/rest.ps1 +++ b/demos/rest/rest.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. #----------------- diff --git a/docker/tests/containerTestCommon.psm1 b/docker/tests/containerTestCommon.psm1 index b34f097b95c..c6b540abd77 100644 --- a/docker/tests/containerTestCommon.psm1 +++ b/docker/tests/containerTestCommon.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. $script:forcePull = $true diff --git a/docs/FAQ.md b/docs/FAQ.md index e24c05728c0..2de12360485 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -3,7 +3,7 @@ ## Where can I learn PowerShell's syntax? [SS64.com](https://ss64.com/ps/syntax.html) is a good resource. -[Microsoft Docs](https://docs.microsoft.com/powershell/scripting/overview?view=powershell-6) is another excellent resource. +[Microsoft Docs](https://docs.microsoft.com/powershell/scripting/overview) is another excellent resource. ## What are the best practices and style? diff --git a/docs/building/linux.md b/docs/building/linux.md index 351f02cef4c..5feef641676 100644 --- a/docs/building/linux.md +++ b/docs/building/linux.md @@ -24,7 +24,7 @@ and [CMake][] to build the native components. Installing the toolchain is as easy as running `Start-PSBootstrap` in PowerShell. Of course, this requires a self-hosted copy of PowerShell on Linux. -Fortunately, this is as easy as [downloading and installing the package](https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6#binary-archives). +Fortunately, this is as easy as [downloading and installing the package](https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#binary-archives). The `./tools/install-powershell.sh` script will also install the PowerShell package. In Bash: @@ -71,7 +71,7 @@ Start-PSBuild Congratulations! If everything went right, PowerShell is now built. The `Start-PSBuild` script will output the location of the executable: -`./src/powershell-unix/bin/Debug/netcoreapp3.0/linux-x64/publish/pwsh`. +`./src/powershell-unix/bin/Debug/net5.0/linux-x64/publish/pwsh`. You should now be running the PowerShell Core that you just built, if your run the above executable. You can run our cross-platform Pester tests with `Start-PSPester`, and our xUnit tests with `Start-PSxUnit`. diff --git a/docs/building/macos.md b/docs/building/macos.md index d969753e636..e398451e8da 100644 --- a/docs/building/macos.md +++ b/docs/building/macos.md @@ -36,4 +36,4 @@ We cannot do this for you in the build module due to #[847][]. Start a PowerShell session by running `pwsh`, and then use `Start-PSBuild` from the module. -After building, PowerShell will be at `./src/powershell-unix/bin/Debug/netcoreapp3.0/osx-x64/publish/pwsh`. +After building, PowerShell will be at `./src/powershell-unix/bin/Debug/net5.0/osx-x64/publish/pwsh`. diff --git a/docs/building/windows-core.md b/docs/building/windows-core.md index 207f38f0855..0e67e38a4e6 100644 --- a/docs/building/windows-core.md +++ b/docs/building/windows-core.md @@ -18,8 +18,7 @@ This guide assumes that you have recursively cloned the PowerShell repository an ### Visual Studio -You will need to install an edition of Visual Studio 2015 (Community, Enterprise, or Professional) with the optional feature 'Common Tools for Visual C++' installed. -The free Community edition of Visual Studio 2015 can be downloaded [here](https://www.visualstudio.com/visual-studio-community-vs/). +This repository requires at least Visual Studio 2019 16.6 Preview 2. The free Community edition of Visual Studio can be downloaded from [Microsoft](https://visualstudio.microsoft.com/downloads/). ### Visual Studio Code @@ -58,11 +57,11 @@ Import-Module ./build.psm1 Start-PSBuild ``` -Congratulations! If everything went right, PowerShell is now built and executable as `./src/powershell-win-core/bin/Debug/netcoreapp3.0/win7-x64/publish/pwsh.exe`. +Congratulations! If everything went right, PowerShell is now built and executable as `./src/powershell-win-core/bin/Debug/net5.0/win7-x64/publish/pwsh.exe`. This location is of the form `./[project]/bin/[configuration]/[framework]/[rid]/publish/[binary name]`, and our project is `powershell`, configuration is `Debug` by default, -framework is `netcoreapp3.0`, runtime identifier is `win7-x64` by default, +framework is `net5.0`, runtime identifier is `win7-x64` by default, and binary name is `pwsh`. The function `Get-PSOutput` will return the path to the executable; thus you can execute the development copy via `& (Get-PSOutput)`. diff --git a/docs/cmdlet-example/command-line-simple-example.md b/docs/cmdlet-example/command-line-simple-example.md index 1af04f4f261..ae4693a10d7 100644 --- a/docs/cmdlet-example/command-line-simple-example.md +++ b/docs/cmdlet-example/command-line-simple-example.md @@ -220,7 +220,7 @@ and macOS as well as Windows using the .NET Core 2.x SDK command-line tools. For more information on .NET Standard, check out the [documentation][net-std-docs] and the [.NET Standard YouTube channel][net-std-chan]. -[dotnet-cli]: https://docs.microsoft.com/dotnet/core/tools/?tabs=netcore2x +[dotnet-cli]: https://docs.microsoft.com/dotnet/core/tools/ [net-core-sdk]: https://www.microsoft.com/net/download/core [net-std-docs]: https://docs.microsoft.com/dotnet/standard/net-standard [net-std-chan]: https://www.youtube.com/playlist?list=PLRAdsfhKI4OWx321A_pr-7HhRNk7wOLLY diff --git a/docs/community/governance.md b/docs/community/governance.md index 4d7307b675b..5b93ddeec51 100644 --- a/docs/community/governance.md +++ b/docs/community/governance.md @@ -17,7 +17,7 @@ This veto power will be used with restraint since it is intended that the community drive the project. The Corporate Maintainer is determined by the Corporation both initially and in continuation. The initial Corporate Maintainer for PowerShell is Jeffrey Snover ([jpsnover](https://github.com/jpsnover)). -* [**RFC process**][RFC-repo]: The "review-for-comment" (RFC) process whereby design decisions get made. +* [**RFC process**][RFC-repo]: The "request-for-comments" (RFC) process whereby design decisions get made. ## PowerShell Committee @@ -133,7 +133,6 @@ See our [Pull Request Process][pull-request-process] [RFC-repo]: https://github.com/PowerShell/PowerShell-RFC [pester]: ../testing-guidelines/WritingPesterTests.md -[ci-system]: ../testing-guidelines/testing-guidelines.md#ci-system [breaking-changes]: ../dev-process/breaking-change-contract.md [issue-process]: ../maintainers/issue-management.md [pull-request-process]: ../../.github/CONTRIBUTING.md#lifecycle-of-a-pull-request diff --git a/docs/debugging/README.md b/docs/debugging/README.md index e5f3b4b30d2..1b13924b854 100644 --- a/docs/debugging/README.md +++ b/docs/debugging/README.md @@ -1,10 +1,9 @@ # Visual Studio Code -[Experimental .NET Core Debugging in VS Code][core-debug] enables -cross-platform debugging with the [Visual Studio Code][vscode] editor. +The [Visual Studio Code][vscode] editor supports cross-platform debugging. This is made possible by the [OmniSharp][] extension for VS Code. -Please review their [detailed instructions][vscclrdebugger]. In +Please review their [detailed instructions][core-debug]. In addition to being able to build PowerShell, you need: - C# Extension for VS Code installed @@ -42,10 +41,9 @@ process named `powershell`, and will attach to it. If you need more fine-grained control, replace `processName` with `processId` and provide a PID. (Please be careful not to commit such a change.) -[core-debug]: https://devblogs.microsoft.com/devops/experimental-net-core-debugging-in-vs-code/ +[core-debug]: https://docs.microsoft.com/dotnet/core/tutorials/with-visual-studio-code#debug [vscode]: https://code.visualstudio.com/ [OmniSharp]: https://github.com/OmniSharp/omnisharp-vscode -[vscclrdebugger]: https://aka.ms/vscclrdebugger ## PowerShell diff --git a/docs/host-powershell/sample/MyApp/Program.cs b/docs/host-powershell/sample/MyApp/Program.cs index 1bd9f883ca3..fc54fa2d709 100644 --- a/docs/host-powershell/sample/MyApp/Program.cs +++ b/docs/host-powershell/sample/MyApp/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/docs/learning-powershell/README.md b/docs/learning-powershell/README.md index dcf202ba82c..6ce2c8832ff 100644 --- a/docs/learning-powershell/README.md +++ b/docs/learning-powershell/README.md @@ -24,11 +24,12 @@ At the end of this exercise, you should be able to launch the PowerShell session You can launch PowerShell console by pressing Windows key, typing PowerShell, and clicking on Windows PowerShell. However if you want to try out the latest PowerShell, follow the [PowerShell on Windows][inst-win]. -- Alternatively you can get the PowerShell by [building it](../../README.md#building-powershell) +- Alternatively you can get the PowerShell by [building it][build-powershell] -[inst-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-6 -[inst-win]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6 -[inst-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos?view=powershell-6 +[build-powershell]:../../README.md#building-the-repository +[inst-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux +[inst-win]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows +[inst-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos ## Getting Started with PowerShell @@ -47,20 +48,17 @@ You can use your favorite editor to write scripts. We use Visual Studio Code (VS Code) which works on Windows, Linux, and macOS. Click on the following link to create your first PowerShell script. -- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/components/vscode/using-vscode?view=powershell-6) +- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode) ### PowerShell Debugger Debugging can help you find bugs and fix problems in your PowerShell scripts. Click on the link below to learn more about debugging: -- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/components/vscode/using-vscode?view=powershell-6#debugging-with-visual-studio-code) +- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode#debugging-with-visual-studio-code) - [PowerShell Command-line Debugging][cli-debugging] -[use-vscode-editor]:./using-vscode.md#editing-with-vs-code [cli-debugging]:./debugging-from-commandline.md -[get-powershell]:../../README.md#get-powershell -[build-powershell]:../../README.md#building-the-repository ### PowerShell Testing @@ -121,10 +119,9 @@ Note that all bash commands should continue working on PowerShell session. [getstarted-with-powershell]: https://channel9.msdn.com/Series/GetStartedPowerShell3 [why-learn-powershell]: https://blogs.technet.microsoft.com/heyscriptingguy/2014/10/18/weekend-scripter-why-learn-powershell/ -[Using Windows PowerShell for Administration]: https://docs.microsoft.com/powershell/scripting/samples/sample-scripts-for-administration?view=powershell-6 [ebook-from-Idera]:https://www.idera.com/resourcecentral/whitepapers/powershell-ebook [channel9-learn-powershell]: https://channel9.msdn.com/Search?term=powershell#ch9Search [idera-learn-powershell]: https://community.idera.com/database-tools/powershell/video_library/ [quick-reference]: https://www.powershellmagazine.com/2014/04/24/windows-powershell-4-0-and-other-quick-reference-guides/ [script-guy-how-to]:https://blogs.technet.microsoft.com/tommypatterson/2015/09/04/ed-wilsons-powershell5-videos-now-on-channel9-2/ -[basic-cookbooks]:https://docs.microsoft.com/powershell/scripting/samples/sample-scripts-for-administration?view=powershell-6 +[basic-cookbooks]:https://docs.microsoft.com/powershell/scripting/samples/sample-scripts-for-administration diff --git a/docs/learning-powershell/debugging-from-commandline.md b/docs/learning-powershell/debugging-from-commandline.md index cceb8e922a6..1aaab218256 100644 --- a/docs/learning-powershell/debugging-from-commandline.md +++ b/docs/learning-powershell/debugging-from-commandline.md @@ -1,6 +1,6 @@ # Debugging in PowerShell Command-line -As we know, we can debug PowerShell code via GUI tools like [Visual Studio Code](https://docs.microsoft.com/powershell/scripting/components/vscode/using-vscode?view=powershell-6#debugging-with-visual-studio-code). In addition, we can +As we know, we can debug PowerShell code via GUI tools like [Visual Studio Code](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode#debugging-with-visual-studio-code). In addition, we can directly perform debugging within the PowerShell command-line session by using the PowerShell debugger cmdlets. This document demonstrates how to use the cmdlets for the PowerShell command-line debugging. We will cover the following topics: setting a debug breakpoint on a line of code and on a variable. @@ -20,7 +20,7 @@ $result =[int](ConvertFahrenheitToCelsius($fahrenheit)) Write-Host "$result Celsius" ``` - 1. **Setting a Breakpoint on a Line** +## Setting a Breakpoint on a Line - Open a [PowerShell editor](README.md#powershell-editor) - Save the above code snippet to a file. For example, "test.ps1" @@ -103,7 +103,7 @@ PS /home/jen/debug> ``` -1. **Setting a Breakpoint on a Variable** +## Setting a Breakpoint on a Variable - Clear existing breakpoints if there are any ```powershell @@ -169,5 +169,5 @@ Now you know the basics of the PowerShell debugging from PowerShell command-line ## More Reading -- [about_Debuggers](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_debuggers?view=powershell-6) +- [about_Debuggers](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_debuggers) - [PowerShell Debugging](https://blogs.technet.microsoft.com/heyscriptingguy/tag/debugging/) diff --git a/docs/learning-powershell/powershell-beginners-guide.md b/docs/learning-powershell/powershell-beginners-guide.md index 13ab9be2526..ce49a4b9bfe 100644 --- a/docs/learning-powershell/powershell-beginners-guide.md +++ b/docs/learning-powershell/powershell-beginners-guide.md @@ -26,205 +26,205 @@ It is shown as `PS C:\>` on Windows. 1. `Get-Process`: Gets the processes that are running on the local computer or a remote computer. -By default, you will get data back similar to the following: + By default, you will get data back similar to the following: -```powershell -PS /> Get-Process + ```powershell + PS /> Get-Process -Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName -------- ------ ----- ----- ------ -- ----------- - - - - 1 0.012 12 bash - - - - 21 20.220 449 powershell - - - - 11 61.630 8620 code - - - - 74 403.150 1209 firefox + Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName + ------- ------ ----- ----- ------ -- ----------- + - - - 1 0.012 12 bash + - - - 21 20.220 449 powershell + - - - 11 61.630 8620 code + - - - 74 403.150 1209 firefox -… -``` + … + ``` -Only interested in the instance of Firefox process that is running on your computer? + Only interested in the instance of Firefox process that is running on your computer? -Try this: + Try this: -```powershell -PS /> Get-Process -Name firefox + ```powershell + PS /> Get-Process -Name firefox -Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName -------- ------ ----- ----- ------ -- ----------- - - - - 74 403.150 1209 firefox + Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName + ------- ------ ----- ----- ------ -- ----------- + - - - 74 403.150 1209 firefox -``` + ``` -Want to get back more than one process? -Then just specify process names and separate them with commas. + Want to get back more than one process? + Then just specify process names and separate them with commas. -```powershell -PS /> Get-Process -Name firefox, powershell -Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName -------- ------ ----- ----- ------ -- ----------- - - - - 74 403.150 1209 firefox - - - - 21 20.220 449 powershell + ```powershell + PS /> Get-Process -Name firefox, powershell + Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName + ------- ------ ----- ----- ------ -- ----------- + - - - 74 403.150 1209 firefox + - - - 21 20.220 449 powershell -``` + ``` 1. `Clear-Host`: Clears the display in the host program. -```powershell -PS /> Get-Process -PS /> Clear-Host -``` + ```powershell + PS /> Get-Process + PS /> Clear-Host + ``` -Type too much just for clearing the screen? + Type too much just for clearing the screen? -Here is how the alias can help. + Here is how the alias can help. 1. `Get-Alias`: Gets the aliases for the current session. -```powershell -Get-Alias - -CommandType Name ------------ ---- -… - -Alias cd -> Set-Location -Alias cls -> Clear-Host -Alias clear -> Clear-Host -Alias copy -> Copy-Item -Alias dir -> Get-ChildItem -Alias gc -> Get-Content -Alias gmo -> Get-Module -Alias ri -> Remove-Item -Alias type -> Get-Content -… -``` + ```powershell + Get-Alias -As you can see `cls` or `clear` is an alias of `Clear-Host`. + CommandType Name + ----------- ---- + … -Now try it: + Alias cd -> Set-Location + Alias cls -> Clear-Host + Alias clear -> Clear-Host + Alias copy -> Copy-Item + Alias dir -> Get-ChildItem + Alias gc -> Get-Content + Alias gmo -> Get-Module + Alias ri -> Remove-Item + Alias type -> Get-Content + … + ``` -```powershell -PS /> Get-Process -PS /> cls -``` + As you can see `cls` or `clear` is an alias of `Clear-Host`. + + Now try it: + + ```powershell + PS /> Get-Process + PS /> cls + ``` 1. `cd -> Set-Location`: Sets the current working location to a specified location. -```powershell -PS /> Set-Location /home -PS /home> -``` + ```powershell + PS /> Set-Location /home + PS /home> + ``` 1. `dir -> Get-ChildItem`: Gets the items and child items in one or more specified locations. -```powershell -# Get all files under the current directory: -PS /> Get-ChildItem + ```powershell + # Get all files under the current directory: + PS /> Get-ChildItem -# Get all files under the current directory as well as its subdirectories: -PS /> cd $home -PS /home/jen> dir -Recurse + # Get all files under the current directory as well as its subdirectories: + PS /> cd $home + PS /home/jen> dir -Recurse -# List all files with "txt" file extension. -PS /> cd $home -PS /home/jen> dir –Path *.txt -Recurse -``` + # List all files with "txt" file extension. + PS /> cd $home + PS /home/jen> dir –Path *.txt -Recurse + ``` -*6. `New-Item`: Creates a new item. +1. `New-Item`: Creates a new item. -```powershell -# An empty file is created if you type the following: -PS /home/jen> New-Item -Path ./test.txt + ```powershell + # An empty file is created if you type the following: + PS /home/jen> New-Item -Path ./test.txt - Directory: /home/jen + Directory: /home/jen -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 7/7/2016 7:17 PM 0 test.txt -``` + Mode LastWriteTime Length Name + ---- ------------- ------ ---- + -a---- 7/7/2016 7:17 PM 0 test.txt + ``` -You can use the `-Value` parameter to add some data to your file. + You can use the `-Value` parameter to add some data to your file. -For example, the following command adds the phrase `Hello world!` as a file content to the `test.txt`. + For example, the following command adds the phrase `Hello world!` as a file content to the `test.txt`. -Because the test.txt file exists already, we use `-Force` parameter to replace the existing content. + Because the test.txt file exists already, we use `-Force` parameter to replace the existing content. -```powershell -PS /home/jen> New-Item -Path ./test.txt -Value "Hello world!" -Force + ```powershell + PS /home/jen> New-Item -Path ./test.txt -Value "Hello world!" -Force - Directory: /home/jen + Directory: /home/jen -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 7/7/2016 7:19 PM 24 test.txt + Mode LastWriteTime Length Name + ---- ------------- ------ ---- + -a---- 7/7/2016 7:19 PM 24 test.txt -``` + ``` -There are other ways to add some data to a file. + There are other ways to add some data to a file. -For example, you can use `Set-Content` to set the file contents: + For example, you can use `Set-Content` to set the file contents: -```powershell -PS /home/jen>Set-Content -Path ./test.txt -Value "Hello world again!" -``` + ```powershell + PS /home/jen>Set-Content -Path ./test.txt -Value "Hello world again!" + ``` -Or simply use `>` as below: + Or simply use `>` as below: -```powershell -# create an empty file -"" > test.txt + ```powershell + # create an empty file + "" > test.txt -# set "Hello world!" as content of test.txt file -"Hello world!!!" > test.txt + # set "Hello world!" as content of test.txt file + "Hello world!!!" > test.txt -``` + ``` -The pound sign `#` above is used for comments in PowerShell. + The pound sign `#` above is used for comments in PowerShell. 1. `type -> Get-Content`: Gets the content of the item at the specified location. -```powershell -PS /home/jen> Get-Content -Path ./test.txt -PS /home/jen> type -Path ./test.txt + ```powershell + PS /home/jen> Get-Content -Path ./test.txt + PS /home/jen> type -Path ./test.txt -Hello world again! -``` + Hello world again! + ``` 1. `del -> Remove-Item`: Deletes the specified items. -This cmdlet will delete the file `/home/jen/test.txt`: + This cmdlet will delete the file `/home/jen/test.txt`: -```powershell -PS /home/jen> Remove-Item ./test.txt -``` + ```powershell + PS /home/jen> Remove-Item ./test.txt + ``` 1. `$PSVersionTable`: Displays the version of PowerShell you are currently using. -Type `$PSVersionTable` in your PowerShell session, you will see something like below. -"PSVersion" indicates the PowerShell version that you are using. + Type `$PSVersionTable` in your PowerShell session, you will see something like below. + "PSVersion" indicates the PowerShell version that you are using. -```powershell -Name Value ----- ----- -PSVersion 6.0.0-alpha -PSEdition Core -PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} -BuildVersion 3.0.0.0 -GitCommitId v6.0.0-alpha.12 -CLRVersion -WSManStackVersion 3.0 -PSRemotingProtocolVersion 2.3 -SerializationVersion 1.1.0.1 + ```powershell + Name Value + ---- ----- + PSVersion 6.0.0-alpha + PSEdition Core + PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} + BuildVersion 3.0.0.0 + GitCommitId v6.0.0-alpha.12 + CLRVersion + WSManStackVersion 3.0 + PSRemotingProtocolVersion 2.3 + SerializationVersion 1.1.0.1 -``` + ``` 1. `Exit`: To exit the PowerShell session, type `exit`. -```powershell -exit -``` + ```powershell + exit + ``` ## Need Help? diff --git a/global.json b/global.json index c685cffc7ac..12a373c1e90 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "3.1.101" + "version": "5.0.100-preview.5.20279.10" } } diff --git a/nuget.config b/nuget.config index 5ec994d9118..f6b2acb7d0c 100644 --- a/nuget.config +++ b/nuget.config @@ -2,6 +2,7 @@ + diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs index 09297dcdc20..2e914a2299a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.CompilerServices; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index b7e418e05b6..1e21b781742 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -27,7 +27,7 @@ internal abstract class CimAsyncOperation : IDisposable #region Constructor /// - /// Constructor. + /// The constructor. /// public CimAsyncOperation() { @@ -126,7 +126,7 @@ protected void OperationDeletedHandler(object cimSession, OperationEventArgs act /// /// /// - /// wrapper of cmdlet, for details. + /// Wrapper of cmdlet, for details. /// public void ProcessActions(CmdletOperationBase cmdletOperation) { @@ -146,12 +146,12 @@ public void ProcessActions(CmdletOperationBase cmdletOperation) /// /// - /// process remaining actions until all operations are completed or + /// Process remaining actions until all operations are completed or /// current cmdlet is terminated by user. /// /// /// - /// wrapper of cmdlet, for details. + /// Wrapper of cmdlet, for details. /// public void ProcessRemainActions(CmdletOperationBase cmdletOperation) { @@ -202,7 +202,6 @@ protected bool GetActionAndRemove(out CimBaseAction action) /// Add temporary object to cache. /// /// - /// Computer name of the cimsession. /// Cimsession wrapper object. protected void AddCimSessionProxy(CimSessionProxy sessionproxy) { @@ -382,7 +381,7 @@ protected object GetBaseObject(object value) /// /// /// Output the cimtype of the value, either Reference or ReferenceArray. - /// + /// The object. protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { PSReference cimReference = value as PSReference; @@ -496,7 +495,7 @@ protected virtual void Dispose(bool disposing) /// /// - /// Clean up managed resources + /// Clean up managed resources. /// /// private void Cleanup() @@ -585,7 +584,7 @@ private void Cleanup() #region protected members /// /// Event to notify ps thread that either a ACK message sent back - /// or a error happened. Currently only used by class + /// or a error happened. Currently only used by /// . /// protected ManualResetEventSlim ackedEvent; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index c76fb819697..345b27bb48b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -69,7 +69,7 @@ protected XOperationContextBase Context internal class CimSyncAction : CimBaseAction, IDisposable { /// - /// Constructor. + /// The constructor. /// public CimSyncAction() { @@ -91,7 +91,7 @@ public virtual CimResponseType GetResponse() /// /// - /// Set response result + /// Set the response result. /// /// internal CimResponseType ResponseType @@ -102,7 +102,7 @@ internal CimResponseType ResponseType /// /// /// Call this method when the action is completed or - /// the operation is terminated + /// the operation is terminated. /// /// internal virtual void OnComplete() @@ -112,7 +112,7 @@ internal virtual void OnComplete() /// /// - /// block current thread. + /// Block current thread. /// /// protected virtual void Block() diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs deleted file mode 100644 index 7f9a1da4057..00000000000 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCmdletModuleInitialize.cs +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#region Using directives - -using System; -using System.Globalization; -using System.Management.Automation; -using System.Management.Automation.Runspaces; - -#endregion - -namespace Microsoft.Management.Infrastructure.CimCmdlets -{ - /// - /// - /// Initialize the cimcmdlets. - /// - /// - /// - /// Provide a hook to the engine for startup initialization - /// w.r.t compiled assembly loading. - /// - public sealed class CimCmdletsAssemblyInitializer : IModuleAssemblyInitializer - { - /// - /// - /// constructor - /// - /// - public CimCmdletsAssemblyInitializer() - { - } - - /// - /// PowerShell engine will call this method when the cimcmdlets module - /// is loaded. - /// - public void OnImport() - { - DebugHelper.WriteLogEx(); - using (System.Management.Automation.PowerShell invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) - { - foreach (CimCmdletAliasEntry alias in Aliases) - { - invoker.AddScript(string.Format(CultureInfo.CurrentUICulture, "Set-Alias -Name {0} -Value {1} -Option {2} -ErrorAction SilentlyContinue", alias.Name, alias.Value, alias.Options)); - DebugHelper.WriteLog(@"Add commands {0} of {1} with option {2} to current runspace.", 1, alias.Name, alias.Value, alias.Options); - } - - System.Collections.ObjectModel.Collection psObjects = invoker.Invoke(); - DebugHelper.WriteLog(@"Invoke results {0}.", 1, psObjects.Count); - } - } - - #region readonly string - - /// - /// - /// CimCmdlet alias entry - /// - /// - internal sealed class CimCmdletAliasEntry - { - /// - /// - /// Constructor - /// - /// - /// - /// - internal CimCmdletAliasEntry(string name, string value) - { - this._name = name; - this._value = value; - } - - /// - /// The string defining the name of this alias. - /// - internal string Name { get { return this._name; } } - - private string _name; - - /// - /// The string defining real cmdlet name. - /// - internal string Value { get { return this._value; } } - - private string _value = string.Empty; - - /// - /// The string defining real cmdlet name. - /// - internal ScopedItemOptions Options { get { return this._options; } } - - private ScopedItemOptions _options = ScopedItemOptions.AllScope | ScopedItemOptions.ReadOnly; - } - - /// - /// Returns a new array of alias entries everytime it's called. - /// - internal static CimCmdletAliasEntry[] Aliases = new CimCmdletAliasEntry[] { - new CimCmdletAliasEntry("gcim", "Get-CimInstance"), - new CimCmdletAliasEntry("scim", "Set-CimInstance"), - new CimCmdletAliasEntry("ncim", "New-CimInstance "), - new CimCmdletAliasEntry("rcim", "Remove-cimInstance"), - new CimCmdletAliasEntry("icim", "Invoke-CimMethod"), - new CimCmdletAliasEntry("gcai", "Get-CimAssociatedInstance"), - new CimCmdletAliasEntry("rcie", "Register-CimIndicationEvent"), - new CimCmdletAliasEntry("ncms", "New-CimSession"), - new CimCmdletAliasEntry("rcms", "Remove-cimSession"), - new CimCmdletAliasEntry("gcms", "Get-CimSession"), - new CimCmdletAliasEntry("ncso", "New-CimSessionOption"), - new CimCmdletAliasEntry("gcls", "Get-CimClass"), - }; - #endregion - } -} diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 9b8b69fe6e8..2488490c514 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -395,7 +395,7 @@ internal void SetParameter(string parameterName, bool isBeginProcess) if (nameset.Count == 0) { - throw new PSArgumentException(Strings.UnableToResolveParameterSetName); + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); } else { @@ -452,7 +452,7 @@ internal string GetParameterSet() { if (boundParameterSetName != null) { - throw new PSArgumentException(Strings.UnableToResolveParameterSetName); + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); } boundParameterSetName = parameterSetName; @@ -465,7 +465,7 @@ internal string GetParameterSet() // throw if there are > 1 parameter set if (noMandatoryParameterSet.Count > 1) { - throw new PSArgumentException(Strings.UnableToResolveParameterSetName); + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); } else if (noMandatoryParameterSet.Count == 1) { @@ -482,7 +482,7 @@ internal string GetParameterSet() // throw if still can not find the parameter set name if (boundParameterSetName == null) { - throw new PSArgumentException(Strings.UnableToResolveParameterSetName); + throw new PSArgumentException(CimCmdletStrings.UnableToResolveParameterSetName); } return boundParameterSetName; @@ -511,7 +511,6 @@ private void CloneParameterEntries( /// public class CimBaseCommand : Cmdlet, IDisposable { - #region resolve parameter set name /// /// @@ -703,6 +702,7 @@ protected virtual void DisposeInternal() /// Whether at begin process time, false means in processrecord. /// private bool atBeginProcess = true; + internal bool AtBeginProcess { get @@ -903,7 +903,7 @@ internal void ThrowInvalidAuthenticationTypeError( string parameterName, PasswordAuthenticationMechanism authentication) { - string message = string.Format(CultureInfo.CurrentUICulture, Strings.InvalidAuthenticationTypeWithNullCredential, + string message = string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidAuthenticationTypeWithNullCredential, authentication, ImpersonatedAuthenticationMechanism.None, ImpersonatedAuthenticationMechanism.Negotiate, @@ -926,7 +926,7 @@ internal void ThrowConflictParameterWasSet( string conflictParameterName) { string message = string.Format(CultureInfo.CurrentUICulture, - Strings.ConflictParameterWasSet, + CimCmdletStrings.ConflictParameterWasSet, parameterName, conflictParameterName); PSArgumentException exception = new PSArgumentException(message, parameterName); ThrowTerminatingError(exception, operationName); @@ -955,7 +955,7 @@ internal void ThrowInvalidProperty( propList.Append(property); } - string message = string.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindPropertyFromGivenClass, + string message = string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.CouldNotFindPropertyFromGivenClass, className, propList); PSArgumentOutOfRangeException exception = new PSArgumentOutOfRangeException( parameterName, actualValue, message); @@ -981,7 +981,6 @@ internal CimCredential CreateCimCredentials(PSCredential psCredentials, NetworkCredential networkCredential = psCredentials.GetNetworkCredential(); DebugHelper.WriteLog("Domain:{0}; UserName:{1}; Password:{2}.", 1, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); credentials = new CimCredential(passwordAuthentication, networkCredential.Domain, networkCredential.UserName, psCredentials.Password); - } else { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs index aee88fd57d6..b0b95d14c50 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetAssociatedInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index ef334a93c95..a3826487e24 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index 13fd5ffa66a..c462d5b9918 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index f77e8a04bba..fd44d922009 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs index bec0749dbd7..ba82ff9e432 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimInvokeCimMethod.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -392,7 +392,7 @@ private CimMethodParametersCollection CreateParametersCollection( if (declaration == null) { throw new ArgumentException(string.Format( - CultureInfo.CurrentUICulture, Strings.InvalidMethod, methodName, className)); + CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethod, methodName, className)); } } else if (cimInstance != null) @@ -407,7 +407,7 @@ private CimMethodParametersCollection CreateParametersCollection( if (paramDeclaration == null) { throw new ArgumentException(string.Format( - CultureInfo.CurrentUICulture, Strings.InvalidMethodParameter, parameterName, methodName, className)); + CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidMethodParameter, parameterName, methodName, className)); } parameter = CimMethodParameter.Create( diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index da3808459af..14c57c87888 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -79,7 +79,6 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) cmdlet.Key, cmdlet.Property, cmdlet); - } break; @@ -92,7 +91,6 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) cmdlet.Key, cmdlet.Property, cmdlet); - } break; @@ -103,7 +101,6 @@ public void NewCimInstance(NewCimInstanceCommand cmdlet) cimInstance = CreateCimInstance(cmdlet.CimClass, cmdlet.Property, cmdlet); - } break; @@ -313,7 +310,6 @@ private CimInstance CreateCimInstance( flag); cimInstance.CimInstanceProperties.Add(newProperty); } - } return cimInstance; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs index 2ebebfec1c6..4d4ff5d6ec5 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimPromptUser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index 20da97bbcc0..559c58b8a11 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -12,7 +12,6 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets { - /// /// /// Subscription result event args @@ -170,7 +169,7 @@ public void RegisterCimIndication( DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); if (cimSession == null) { - throw new ArgumentNullException(string.Format(CultureInfo.CurrentUICulture, Strings.NullArgument, @"cimSession")); + throw new ArgumentNullException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, @"cimSession")); } this.TargetComputerName = cimSession.ComputerName; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs index 3ed5511b802..3dbae04b726 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRemoveCimInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index 74ea55fa3b0..55cf540c0e8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 36c72ae697c..0dd85ea213c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -180,51 +180,51 @@ internal class CimSessionState : IDisposable /// where is the next available session number. /// For example, CimSession1, CimSession2, etc... /// - internal static string CimSessionClassName = "CimSession"; + internal static readonly string CimSessionClassName = "CimSession"; /// /// CimSession object name. /// - internal static string CimSessionObject = "{CimSession Object}"; + internal static readonly string CimSessionObject = "{CimSession Object}"; /// /// /// CimSession object path, which is identifying a cimsession object /// /// - internal static string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; + internal static readonly string SessionObjectPath = @"CimSession id = {0}, name = {2}, ComputerName = {3}, instance id = {1}"; /// /// Id property name of cimsession wrapper object. /// - internal static string idPropName = "Id"; + internal static readonly string idPropName = "Id"; /// /// Instanceid property name of cimsession wrapper object. /// - internal static string instanceidPropName = "InstanceId"; + internal static readonly string instanceidPropName = "InstanceId"; /// /// Name property name of cimsession wrapper object. /// - internal static string namePropName = "Name"; + internal static readonly string namePropName = "Name"; /// /// Computer name property name of cimsession object. /// - internal static string computernamePropName = "ComputerName"; + internal static readonly string computernamePropName = "ComputerName"; /// /// Protocol name property name of cimsession object. /// - internal static string protocolPropName = "Protocol"; + internal static readonly string protocolPropName = "Protocol"; /// /// - /// session counter bound to current runspace. + /// Session counter bound to current runspace. /// /// - private UInt32 sessionNameCounter; + private uint sessionNameCounter; /// /// @@ -252,7 +252,7 @@ internal class CimSessionState : IDisposable /// Dictionary used to holds all CimSessions in current runspace by session id. /// /// - private Dictionary curCimSessionsById; + private Dictionary curCimSessionsById; /// /// @@ -265,7 +265,7 @@ internal class CimSessionState : IDisposable /// /// - /// constructor + /// The constructor. /// /// internal CimSessionState() @@ -297,7 +297,7 @@ internal int GetSessionsCount() /// /// /// Unique session id under current runspace. - internal UInt32 GenerateSessionId() + internal uint GenerateSessionId() { return this.sessionNameCounter++; } @@ -305,7 +305,7 @@ internal UInt32 GenerateSessionId() /// /// - /// Indicates whether this object was disposed or not + /// Indicates whether this object was disposed or not. /// /// private bool _disposed; @@ -381,17 +381,19 @@ public void Cleanup() /// /// - /// Add new CimSession object to cache + /// Add new CimSession object to cache. /// /// /// /// /// /// + /// + /// /// internal PSObject AddObjectToCache( CimSession session, - UInt32 sessionId, + uint sessionId, Guid instanceId, string name, string computerName, @@ -434,11 +436,11 @@ internal string GetRemoveSessionObjectTarget(PSObject psObject) string message = string.Empty; if (psObject.BaseObject is CimSession) { - UInt32 id = 0x0; + uint id = 0x0; Guid instanceId = Guid.Empty; string name = string.Empty; string computerName = string.Empty; - if (psObject.Properties[idPropName].Value is UInt32) + if (psObject.Properties[idPropName].Value is uint) { id = Convert.ToUInt32(psObject.Properties[idPropName].Value, null); } @@ -466,7 +468,7 @@ internal string GetRemoveSessionObjectTarget(PSObject psObject) /// /// - /// Remove given object from cache + /// Remove given object from cache. /// /// /// @@ -482,7 +484,7 @@ internal void RemoveOneSessionObjectFromCache(PSObject psObject) /// /// - /// Remove given object from cache + /// Remove given object from cache. /// /// /// @@ -551,7 +553,7 @@ private void AddErrorRecord( { errRecords.Add( new ErrorRecord( - new CimException(string.Format(CultureInfo.CurrentUICulture, Strings.CouldNotFindCimsessionObject, propertyName, propertyValue)), + new CimException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.CouldNotFindCimsessionObject, propertyName, propertyValue)), string.Empty, ErrorCategory.ObjectNotFound, null)); @@ -562,7 +564,8 @@ private void AddErrorRecord( /// /// /// List of session wrapper objects. - internal IEnumerable QuerySession(IEnumerable ids, + internal IEnumerable QuerySession( + IEnumerable ids, out IEnumerable errorRecords) { HashSet sessions = new HashSet(); @@ -570,7 +573,7 @@ internal IEnumerable QuerySession(IEnumerable ids, List errRecords = new List(); errorRecords = errRecords; // NOTES: use template function to implement this will save duplicate code - foreach (UInt32 id in ids) + foreach (uint id in ids) { if (this.curCimSessionsById.ContainsKey(id)) { @@ -594,7 +597,8 @@ internal IEnumerable QuerySession(IEnumerable ids, /// /// /// List of session wrapper objects. - internal IEnumerable QuerySession(IEnumerable instanceIds, + internal IEnumerable QuerySession( + IEnumerable instanceIds, out IEnumerable errorRecords) { HashSet sessions = new HashSet(); @@ -781,7 +785,7 @@ internal class CimSessionBase #region constructor /// - /// Constructor. + /// The constructor. /// public CimSessionBase() { @@ -809,15 +813,15 @@ public CimSessionBase() /// can running parallelly under more than one runspace(s). /// /// - internal static ConcurrentDictionary cimSessions + internal static readonly ConcurrentDictionary cimSessions = new ConcurrentDictionary(); /// /// - /// Default runspace id + /// Default runspace Id. /// /// - internal static Guid defaultRunspaceId = Guid.Empty; + internal static readonly Guid defaultRunspaceId = Guid.Empty; /// /// @@ -855,7 +859,7 @@ public static CimSessionState GetCimSessionState() /// /// - /// clean up the dictionaries if the runspace is closed or broken. + /// Clean up the dictionaries if the runspace is closed or broken. /// /// /// Runspace. @@ -905,7 +909,7 @@ internal class CimTestCimSessionContext : XOperationContextBase { /// /// - /// Constructor + /// The constructor. /// /// /// @@ -920,7 +924,7 @@ internal CimTestCimSessionContext( } /// - /// namespace + /// Namespace /// internal CimSessionWrapper CimSessionWrapper { @@ -935,7 +939,7 @@ internal CimSessionWrapper CimSessionWrapper /// /// - /// constructor + /// The constructor. /// /// internal CimNewSession() : base() @@ -988,7 +992,7 @@ internal void NewCimSession(NewCimSessionCommand cmdlet, /// /// - /// Add session to global cache + /// Add session to global cache, /// /// /// @@ -999,7 +1003,7 @@ internal void AddSessionToCache(CimSession cimSession, XOperationContextBase con DebugHelper.WriteLogEx(); CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; - UInt32 sessionId = this.sessionState.GenerateSessionId(); + uint sessionId = this.sessionState.GenerateSessionId(); string originalSessionName = testCimSessionContext.CimSessionWrapper.Name; string sessionName = (originalSessionName != null) ? originalSessionName : string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); @@ -1017,11 +1021,11 @@ internal void AddSessionToCache(CimSession cimSession, XOperationContextBase con /// /// - /// process all actions in the action queue + /// Process all actions in the action queue. /// /// /// - /// wrapper of cmdlet, for details + /// Wrapper of cmdlet, for details. /// public void ProcessActions(CmdletOperationBase cmdletOperation) { @@ -1030,12 +1034,12 @@ public void ProcessActions(CmdletOperationBase cmdletOperation) /// /// - /// process remaining actions until all operations are completed or - /// current cmdlet is terminated by user + /// Process remaining actions until all operations are completed or + /// current cmdlet is terminated by user. /// /// /// - /// wrapper of cmdlet, for details + /// Wrapper of cmdlet, for details. /// public void ProcessRemainActions(CmdletOperationBase cmdletOperation) { @@ -1055,7 +1059,7 @@ public void ProcessRemainActions(CmdletOperationBase cmdletOperation) /// /// - /// Indicates whether this object was disposed or not + /// Indicates whether this object was disposed or not. /// /// protected bool Disposed @@ -1120,13 +1124,13 @@ protected virtual void Dispose(bool disposing) /// /// - /// Get CimSession based on given id/instanceid/computername/name + /// Get CimSession based on given id/instanceid/computername/name. /// /// internal class CimGetSession : CimSessionBase { /// - /// Constructor. + /// The constructor. /// public CimGetSession() : base() { @@ -1197,7 +1201,7 @@ public void GetCimSession(GetCimSessionCommand cmdlet) /// /// - /// Get CimSession based on given id/instanceid/computername/name + /// Get CimSession based on given id/instanceid/computername/name. /// /// internal class CimRemoveSession : CimSessionBase @@ -1205,7 +1209,7 @@ internal class CimRemoveSession : CimSessionBase /// /// Remove session action string. /// - internal static string RemoveCimSessionActionName = "Remove CimSession"; + internal static readonly string RemoveCimSessionActionName = "Remove CimSession"; /// /// Constructor. diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index 7e9bdb3d90e..084bad51d91 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -44,7 +44,7 @@ internal string Namespace /// /// - /// Session proxy + /// Session proxy. /// /// internal CimSessionProxy Proxy @@ -60,7 +60,7 @@ internal CimSessionProxy Proxy /// /// Class provides all information regarding the - /// current invocation to .net api. + /// current invocation to the .NET API. /// internal class InvocationContext { @@ -872,7 +872,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi } string operationStartMessage = string.Format(CultureInfo.CurrentUICulture, - Strings.CimOperationStart, + CimCmdletStrings.CimOperationStart, operation, (parameters.Length == 0) ? "null" : parameters.ToString()); WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationStartMessage); @@ -888,7 +888,7 @@ internal void WriteOperationCompleteMessage(string operation) { DebugHelper.WriteLogEx(); string operationCompleteMessage = string.Format(CultureInfo.CurrentUICulture, - Strings.CimOperationCompleted, + CimCmdletStrings.CimOperationCompleted, operation); WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationCompleteMessage); } @@ -1066,6 +1066,7 @@ private static void AddShowComputerNameMarker(object o) #if DEBUG private static bool isCliXmlTestabilityHookActive = GetIsCliXmlTestabilityHookActive(); + private static bool GetIsCliXmlTestabilityHookActive() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CDXML_CLIXML_TEST")); @@ -1103,7 +1104,7 @@ public void CreateInstanceAsync(string namespaceName, CimInstance instance) DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = instance; - this.operationName = Strings.CimOperationNameCreateInstance; + this.operationName = CimCmdletStrings.CimOperationNameCreateInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); @@ -1123,7 +1124,7 @@ public void DeleteInstanceAsync(string namespaceName, CimInstance instance) DebugHelper.WriteLogEx("namespace = {0}; classname = {1};", 0, namespaceName, instance.CimSystemProperties.ClassName); this.CheckAvailability(); this.targetCimInstance = instance; - this.operationName = Strings.CimOperationNameDeleteInstance; + this.operationName = CimCmdletStrings.CimOperationNameDeleteInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); @@ -1143,7 +1144,7 @@ public void GetInstanceAsync(string namespaceName, CimInstance instance) DebugHelper.WriteLogEx("namespace = {0}; classname = {1}; keyonly = {2}", 0, namespaceName, instance.CimSystemProperties.ClassName, this.options.KeysOnly); this.CheckAvailability(); this.targetCimInstance = instance; - this.operationName = Strings.CimOperationNameGetInstance; + this.operationName = CimCmdletStrings.CimOperationNameGetInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); @@ -1163,7 +1164,7 @@ public void ModifyInstanceAsync(string namespaceName, CimInstance instance) DebugHelper.WriteLogEx("namespace = {0}; classname = {1}", 0, namespaceName, instance.CimSystemProperties.ClassName); this.CheckAvailability(); this.targetCimInstance = instance; - this.operationName = Strings.CimOperationNameModifyInstance; + this.operationName = CimCmdletStrings.CimOperationNameModifyInstance; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); @@ -1194,7 +1195,7 @@ public void EnumerateAssociatedInstancesAsync( DebugHelper.WriteLogEx("Instance class {0}, association class {1}", 0, sourceInstance.CimSystemProperties.ClassName, associationClassName); this.CheckAvailability(); this.targetCimInstance = sourceInstance; - this.operationName = Strings.CimOperationNameEnumerateAssociatedInstances; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateAssociatedInstances; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"sourceInstance", sourceInstance); @@ -1217,7 +1218,7 @@ public void EnumerateInstancesAsync(string namespaceName, string className) DebugHelper.WriteLogEx("KeyOnly {0}", 0, this.options.KeysOnly); this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameEnumerateInstances; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateInstances; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); @@ -1262,7 +1263,7 @@ public void QueryInstancesAsync( DebugHelper.WriteLogEx("KeyOnly = {0}", 0, this.options.KeysOnly); this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameQueryInstances; + this.operationName = CimCmdletStrings.CimOperationNameQueryInstances; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"queryDialect", queryDialect); @@ -1282,7 +1283,7 @@ public void EnumerateClassesAsync(string namespaceName) DebugHelper.WriteLogEx("namespace {0}", 0, namespaceName); this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameEnumerateClasses; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateClasses; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.WriteOperationStartMessage(this.operationName, this.operationParameters); @@ -1299,7 +1300,7 @@ public void EnumerateClassesAsync(string namespaceName, string className) { this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameEnumerateClasses; + this.operationName = CimCmdletStrings.CimOperationNameEnumerateClasses; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); @@ -1319,7 +1320,7 @@ public void GetClassAsync(string namespaceName, string className) DebugHelper.WriteLogEx("namespace = {0}, className = {1}", 0, namespaceName, className); this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameGetClass; + this.operationName = CimCmdletStrings.CimOperationNameGetClass; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); @@ -1346,7 +1347,7 @@ public void InvokeMethodAsync( DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = instance; - this.operationName = Strings.CimOperationNameInvokeMethod; + this.operationName = CimCmdletStrings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"instance", instance); @@ -1372,7 +1373,7 @@ public void InvokeMethodAsync( DebugHelper.WriteLogEx("EnableMethodResultStreaming = {0}", 0, this.options.EnableMethodResultStreaming); this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameInvokeMethod; + this.operationName = CimCmdletStrings.CimOperationNameInvokeMethod; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"className", className); @@ -1399,7 +1400,7 @@ public void SubscribeAsync( DebugHelper.WriteLogEx("QueryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); this.CheckAvailability(); this.targetCimInstance = null; - this.operationName = Strings.CimOperationNameSubscribeIndication; + this.operationName = CimCmdletStrings.CimOperationNameSubscribeIndication; this.operationParameters.Clear(); this.operationParameters.Add(@"namespaceName", namespaceName); this.operationParameters.Add(@"queryDialect", queryDialect); @@ -1514,6 +1515,7 @@ internal CimInstance TargetCimInstance /// Flag controls whether session object should be closed or not. /// private bool isTemporaryCimSession; + internal bool IsTemporaryCimSession { get @@ -1902,7 +1904,7 @@ private void CheckAvailability() { if (!this.Completed) { - throw new InvalidOperationException(Strings.OperationInProgress); + throw new InvalidOperationException(CimCmdletStrings.OperationInProgress); } } @@ -2260,6 +2262,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) #region private members private CimNewCimInstance newCimInstance = null; + internal CimNewCimInstance NewCimInstanceOperation { get diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs index aa04d2d2aa7..fbe0830318d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSetCimInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -232,7 +232,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re { // can not modify ReadOnly property exception = new CimException(string.Format(CultureInfo.CurrentUICulture, - Strings.CouldNotModifyReadonlyProperty, key, cimInstance)); + CimCmdletStrings.CouldNotModifyReadonlyProperty, key, cimInstance)); return false; } // allow modify the key property value as long as it is not readonly, @@ -281,7 +281,7 @@ private bool SetProperty(IDictionary properties, ref CimInstance cimInstance, re if (e.NativeErrorCode == NativeErrorCode.Failed) { string errorMessage = string.Format(CultureInfo.CurrentUICulture, - Strings.UnableToAddPropertyToInstance, + CimCmdletStrings.UnableToAddPropertyToInstance, newProperty.Name, cimInstance); exception = new CimException(errorMessage, e); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index 2c27fe777f5..fbd780450ab 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs index ec8b1c6f867..b351813c4d4 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index 5bf1f535741..bd02c5dde42 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -48,7 +48,7 @@ public CimWriteProgress( this.currentOperation = theCurrentOperation; if (string.IsNullOrEmpty(theStatusDescription)) { - this.statusDescription = Strings.DefaultStatusDescription; + this.statusDescription = CimCmdletStrings.DefaultStatusDescription; } else { diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs index 57ce642c373..91f3d574a12 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteResultObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -50,5 +50,4 @@ internal object Result private object result; #endregion } - } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index bb58c6a0b84..648f6cfb327 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index 753487de760..36987d35bd9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -22,6 +22,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// Association parameter. /// /// + [Alias("gcai")] [Cmdlet(VerbsCommon.Get, GetCimAssociatedInstanceCommand.Noun, DefaultParameterSetName = CimBaseCommand.ComputerSetName, @@ -247,11 +248,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { base.CheckParameterSet(); - CimGetAssociatedInstance operation = this.GetOperationAgent(); - if (operation == null) - { - operation = this.CreateOperationAgent(); - } + CimGetAssociatedInstance operation = this.GetOperationAgent() ?? this.CreateOperationAgent(); operation.GetCimAssociatedInstance(this); operation.ProcessActions(this.CmdletOperation); @@ -277,7 +274,7 @@ protected override void EndProcessing() /// used to delegate all Get-CimAssociatedInstance operations. /// /// - CimGetAssociatedInstance GetOperationAgent() + private CimGetAssociatedInstance GetOperationAgent() { return this.AsyncOperation as CimGetAssociatedInstance; } @@ -289,7 +286,7 @@ CimGetAssociatedInstance GetOperationAgent() /// /// /// - CimGetAssociatedInstance CreateOperationAgent() + private CimGetAssociatedInstance CreateOperationAgent() { this.AsyncOperation = new CimGetAssociatedInstance(); return GetOperationAgent(); @@ -318,7 +315,7 @@ CimGetAssociatedInstance CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameComputerName, new HashSet { @@ -347,7 +344,7 @@ CimGetAssociatedInstance CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.SessionSetName, new ParameterSetEntry(2, false) }, { CimBaseCommand.ComputerSetName, new ParameterSetEntry(1, true) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index b3571dbccc6..a439e263f0d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -23,6 +23,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// Should the class remember what Session it came from? No. /// /// + [Alias("gcls")] [Cmdlet(VerbsCommon.Get, GetCimClassCommand.Noun, DefaultParameterSetName = ComputerSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227959")] [OutputType(typeof(CimClass))] public class GetCimClassCommand : CimBaseCommand @@ -219,11 +220,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { base.CheckParameterSet(); - CimGetCimClass cimGetCimClass = this.GetOperationAgent(); - if (cimGetCimClass == null) - { - cimGetCimClass = CreateOperationAgent(); - } + CimGetCimClass cimGetCimClass = this.GetOperationAgent() ?? CreateOperationAgent(); cimGetCimClass.GetCimClass(this); cimGetCimClass.ProcessActions(this.CmdletOperation); @@ -251,7 +248,7 @@ protected override void EndProcessing() /// used to delegate all New-CimInstance operations. /// /// - CimGetCimClass GetOperationAgent() + private CimGetCimClass GetOperationAgent() { return (this.AsyncOperation as CimGetCimClass); } @@ -263,7 +260,7 @@ CimGetCimClass GetOperationAgent() /// /// /// - CimGetCimClass CreateOperationAgent() + private CimGetCimClass CreateOperationAgent() { CimGetCimClass cimGetCimClass = new CimGetCimClass(); this.AsyncOperation = cimGetCimClass; @@ -291,7 +288,7 @@ CimGetCimClass CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -309,7 +306,7 @@ CimGetCimClass CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.SessionSetName, new ParameterSetEntry(1) }, { CimBaseCommand.ComputerSetName, new ParameterSetEntry(0, true) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index e9c29619488..9e38546793b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -18,6 +18,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// specified in the Property parameter, KeysOnly parameter or the Select clause /// of the Query parameter. /// + [Alias("gcim")] [Cmdlet(VerbsCommon.Get, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227961")] [OutputType(typeof(CimInstance))] public class GetCimInstanceCommand : CimBaseCommand @@ -459,11 +460,7 @@ protected override void ProcessRecord() { base.CheckParameterSet(); this.CheckArgument(); - CimGetInstance cimGetInstance = this.GetOperationAgent(); - if (cimGetInstance == null) - { - cimGetInstance = CreateOperationAgent(); - } + CimGetInstance cimGetInstance = this.GetOperationAgent() ?? CreateOperationAgent(); cimGetInstance.GetCimInstance(this); cimGetInstance.ProcessActions(this.CmdletOperation); @@ -492,7 +489,7 @@ protected override void EndProcessing() /// as enumerate instances, get instance, query instance. /// /// - CimGetInstance GetOperationAgent() + private CimGetInstance GetOperationAgent() { return (this.AsyncOperation as CimGetInstance); } @@ -505,7 +502,7 @@ CimGetInstance GetOperationAgent() /// /// /// - CimGetInstance CreateOperationAgent() + private CimGetInstance CreateOperationAgent() { CimGetInstance cimGetInstance = new CimGetInstance(); this.AsyncOperation = cimGetInstance; @@ -552,7 +549,7 @@ private void CheckArgument() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -622,7 +619,6 @@ private void CheckArgument() new ParameterDefinitionEntry(CimBaseCommand.QueryComputerSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameSessionSet, false), new ParameterDefinitionEntry(CimBaseCommand.ClassNameComputerSet, false), - } }, { @@ -656,7 +652,7 @@ private void CheckArgument() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1) }, { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs index c648807d833..34d10b1d204 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -14,7 +14,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// The command returns zero, one or more CimSession objects that represent /// connections with remote computers established from the current PS Session. /// - + [Alias("gcms")] [Cmdlet(VerbsCommon.Get, "CimSession", DefaultParameterSetName = ComputerNameSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227966")] [OutputType(typeof(CimSession))] public sealed class GetCimSessionCommand : CimBaseCommand @@ -173,7 +173,7 @@ protected override void ProcessRecord() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameComputerName, new HashSet { @@ -200,7 +200,7 @@ protected override void ProcessRecord() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(0, true) }, { CimBaseCommand.SessionIdSet, new ParameterSetEntry(1) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index 3585c464e8c..e777987a87b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -15,7 +15,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// This cmdlet enables the user to invoke a static method on a CIM class using /// the arguments passed as a list of name value pair dictionary. /// - + [Alias("icim")] [Cmdlet( "Invoke", "CimMethod", @@ -373,11 +373,7 @@ public UInt32 OperationTimeoutSec /// protected override void BeginProcessing() { - CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); - if (cimInvokeMethod == null) - { - cimInvokeMethod = CreateOperationAgent(); - } + CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent() ?? CreateOperationAgent(); this.CmdletOperation = new CmdletOperationInvokeCimMethod(this, cimInvokeMethod); this.AtBeginProcess = false; @@ -417,7 +413,7 @@ protected override void EndProcessing() /// used to delegate all Invoke-CimMethod operations. /// /// - CimInvokeCimMethod GetOperationAgent() + private CimInvokeCimMethod GetOperationAgent() { return this.AsyncOperation as CimInvokeCimMethod; } @@ -429,7 +425,7 @@ CimInvokeCimMethod GetOperationAgent() /// /// /// - CimInvokeCimMethod CreateOperationAgent() + private CimInvokeCimMethod CreateOperationAgent() { CimInvokeCimMethod cimInvokeMethod = new CimInvokeCimMethod(); this.AsyncOperation = cimInvokeMethod; @@ -473,7 +469,7 @@ private void CheckArgument() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameClassName, new HashSet { @@ -560,7 +556,7 @@ private void CheckArgument() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(2, true) }, { CimBaseCommand.ResourceUriSessionSet, new ParameterSetEntry(3) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index 44daaabed95..31b860777ea 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -21,6 +21,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// on the server, otherwise just create client in-memory instance /// /// + [Alias("ncim")] [Cmdlet(VerbsCommon.New, "CimInstance", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227963")] [OutputType(typeof(CimInstance))] public class NewCimInstanceCommand : CimBaseCommand @@ -354,11 +355,7 @@ protected override void ProcessRecord() } } - CimNewCimInstance cimNewCimInstance = this.GetOperationAgent(); - if (cimNewCimInstance == null) - { - cimNewCimInstance = CreateOperationAgent(); - } + CimNewCimInstance cimNewCimInstance = this.GetOperationAgent() ?? CreateOperationAgent(); cimNewCimInstance.NewCimInstance(this); cimNewCimInstance.ProcessActions(this.CmdletOperation); @@ -386,7 +383,7 @@ protected override void EndProcessing() /// used to delegate all New-CimInstance operations. /// /// - CimNewCimInstance GetOperationAgent() + private CimNewCimInstance GetOperationAgent() { return (this.AsyncOperation as CimNewCimInstance); } @@ -398,7 +395,7 @@ CimNewCimInstance GetOperationAgent() /// /// /// - CimNewCimInstance CreateOperationAgent() + private CimNewCimInstance CreateOperationAgent() { CimNewCimInstance cimNewCimInstance = new CimNewCimInstance(); this.AsyncOperation = cimNewCimInstance; @@ -440,7 +437,7 @@ private void CheckArgument() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameClassName, new HashSet { @@ -503,7 +500,7 @@ private void CheckArgument() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.ClassNameSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.ClassNameComputerSet, new ParameterSetEntry(1, true) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index ee83d12ff26..eeb4cba4c4d 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -18,6 +18,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// The CimSession object returned by the Cmdlet is used by all other CIM /// cmdlets. /// + [Alias("ncms")] [Cmdlet(VerbsCommon.New, "CimSession", DefaultParameterSetName = CredentialParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227967")] [OutputType(typeof(CimSession))] public sealed class NewCimSessionCommand : CimBaseCommand diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index f22cd2a8b53..aba99d9401c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -18,8 +18,10 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets public enum ProtocolType { Default, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] Dcom, + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] Wsman }; @@ -35,6 +37,7 @@ public enum ProtocolType /// DComSessionOptions or WSManSessionOptions, which derive from /// CimSessionOptions. /// + [Alias("ncso")] [Cmdlet(VerbsCommon.New, "CimSessionOption", DefaultParameterSetName = ProtocolNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227969")] [OutputType(typeof(CimSessionOptions))] public sealed class NewCimSessionOptionCommand : CimBaseCommand @@ -654,7 +657,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() catch (Exception ex) { DebugHelper.WriteLogEx(ex.ToString(), 1); - throw ex; + throw; } } } @@ -709,7 +712,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameNoEncryption, new HashSet { @@ -810,7 +813,7 @@ internal WSManSessionOptions CreateWSMANSessionOptions() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.ProtocolNameParameterSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.DcomParameterSet, new ParameterSetEntry(0) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index 17da1ae330a..de7bd63feae 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -19,6 +19,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// cancel the subscription /// Should we have the second parameter set with a -Query? /// + [Alias("rcie")] [Cmdlet(VerbsLifecycle.Register, "CimIndicationEvent", DefaultParameterSetName = CimBaseCommand.ClassNameComputerSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227960")] public class RegisterCimIndicationCommand : ObjectEventRegistrationBase { @@ -256,7 +257,7 @@ protected override void EndProcessing() if (newSubscriber != null) { DebugHelper.WriteLog("RegisterCimIndicationCommand::EndProcessing subscribe to Unsubscribed event", 4); - newSubscriber.Unsubscribed += new PSEventUnsubscribedEventHandler(newSubscriber_Unsubscribed); + newSubscriber.Unsubscribed += newSubscriber_Unsubscribed; } } @@ -319,7 +320,7 @@ private void SetParameter(object value, string parameterName) /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameClassName, new HashSet { @@ -356,7 +357,7 @@ private void SetParameter(object value, string parameterName) /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.QueryExpressionSessionSet, new ParameterSetEntry(2) }, { CimBaseCommand.QueryExpressionComputerSet, new ParameterSetEntry(1) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index 7c37b7c4610..60b152055b9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -15,6 +15,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// /// Enables the user to remove a CimInstance. /// + [Alias("rcim")] [Cmdlet( VerbsCommon.Remove, "CimInstance", @@ -243,11 +244,7 @@ public string QueryDialect /// protected override void BeginProcessing() { - CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent(); - if (cimRemoveInstance == null) - { - cimRemoveInstance = CreateOperationAgent(); - } + CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent() ?? CreateOperationAgent(); this.CmdletOperation = new CmdletOperationRemoveCimInstance(this, cimRemoveInstance); this.AtBeginProcess = false; @@ -286,7 +283,7 @@ protected override void EndProcessing() /// used to delegate all Remove-CimInstance operations. /// /// - CimRemoveCimInstance GetOperationAgent() + private CimRemoveCimInstance GetOperationAgent() { return (this.AsyncOperation as CimRemoveCimInstance); } @@ -298,7 +295,7 @@ CimRemoveCimInstance GetOperationAgent() /// /// /// - CimRemoveCimInstance CreateOperationAgent() + private CimRemoveCimInstance CreateOperationAgent() { CimRemoveCimInstance cimRemoveInstance = new CimRemoveCimInstance(); this.AsyncOperation = cimRemoveInstance; @@ -322,7 +319,7 @@ CimRemoveCimInstance CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -371,7 +368,7 @@ CimRemoveCimInstance CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.CimInstanceComputerSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.CimInstanceSessionSet, new ParameterSetEntry(2) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs index afbdf49343c..2fb4126a5b0 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -19,7 +19,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// /// This Cmdlet allows the to remove, or terminate, one or more CimSession(s). /// - + [Alias("rcms")] [Cmdlet(VerbsCommon.Remove, "CimSession", SupportsShouldProcess = true, DefaultParameterSetName = CimSessionSet, @@ -199,7 +199,7 @@ protected override void ProcessRecord() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -231,7 +231,7 @@ protected override void ProcessRecord() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.CimSessionSet, new ParameterSetEntry(1, true) }, { CimBaseCommand.ComputerNameSet, new ParameterSetEntry(1) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index abad4702e8b..7237352b61a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -17,6 +17,7 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets /// CimInstance must have values of all [KEY] properties. /// /// + [Alias("scim")] [Cmdlet( VerbsCommon.Set, "CimInstance", @@ -300,11 +301,7 @@ public SwitchParameter PassThru /// protected override void BeginProcessing() { - CimSetCimInstance cimSetCimInstance = this.GetOperationAgent(); - if (cimSetCimInstance == null) - { - cimSetCimInstance = CreateOperationAgent(); - } + CimSetCimInstance cimSetCimInstance = this.GetOperationAgent() ?? CreateOperationAgent(); this.CmdletOperation = new CmdletOperationSetCimInstance(this, cimSetCimInstance); this.AtBeginProcess = false; @@ -343,7 +340,7 @@ protected override void EndProcessing() /// used to delegate all Set-CimInstance operations. /// /// - CimSetCimInstance GetOperationAgent() + private CimSetCimInstance GetOperationAgent() { return (this.AsyncOperation as CimSetCimInstance); } @@ -355,7 +352,7 @@ CimSetCimInstance GetOperationAgent() /// /// /// - CimSetCimInstance CreateOperationAgent() + private CimSetCimInstance CreateOperationAgent() { CimSetCimInstance cimSetCimInstance = new CimSetCimInstance(); this.AsyncOperation = cimSetCimInstance; @@ -380,7 +377,7 @@ CimSetCimInstance CreateOperationAgent() /// /// Static parameter definition entries. /// - static Dictionary> parameters = new Dictionary> + private static Dictionary> parameters = new Dictionary> { { nameCimSession, new HashSet { @@ -437,7 +434,7 @@ CimSetCimInstance CreateOperationAgent() /// /// Static parameter set entries. /// - static Dictionary parameterSets = new Dictionary + private static Dictionary parameterSets = new Dictionary { { CimBaseCommand.QuerySessionSet, new ParameterSetEntry(3) }, { CimBaseCommand.QueryComputerSet, new ParameterSetEntry(2) }, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index 7dc5281bcc7..e1104e4514b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // #define LOGENABLE // uncomment this line to enable the log, @@ -27,47 +27,47 @@ internal static class ConstValue /// Default computername /// /// - internal static string[] DefaultSessionName = { @"*" }; + internal static readonly string[] DefaultSessionName = { @"*" }; /// /// /// Empty computername, which will create DCOM session /// /// - internal static string NullComputerName = null; + internal static readonly string NullComputerName = null; /// /// /// Empty computername array, which will create DCOM session /// /// - internal static string[] NullComputerNames = { NullComputerName }; + internal static readonly string[] NullComputerNames = { NullComputerName }; /// /// /// localhost computername, which will create WSMAN session /// /// - internal static string LocalhostComputerName = @"localhost"; + internal static readonly string LocalhostComputerName = @"localhost"; /// /// /// Default namespace /// /// - internal static string DefaultNameSpace = @"root\cimv2"; + internal static readonly string DefaultNameSpace = @"root\cimv2"; /// /// /// Default namespace /// /// - internal static string DefaultQueryDialect = @"WQL"; + internal static readonly string DefaultQueryDialect = @"WQL"; /// /// Name of the note property that controls if "PSComputerName" column is shown. /// - internal static string ShowComputerNameNoteProperty = "PSShowComputerName"; + internal static readonly string ShowComputerNameNoteProperty = "PSShowComputerName"; /// /// @@ -141,6 +141,7 @@ 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; } @@ -157,6 +158,7 @@ internal static bool GenerateLog /// Flag used to control generating message into powershell. /// private static bool generateVerboseMessage = true; + internal static bool GenerateVerboseMessage { get { return generateVerboseMessage; } @@ -167,17 +169,17 @@ internal static bool GenerateVerboseMessage /// /// Flag used to control generating message into powershell. /// - internal static string logFile = @"c:\temp\Cim.log"; + internal static readonly string logFile = @"c:\temp\Cim.log"; /// /// Indent space string. /// - internal static string space = @" "; + internal static readonly string space = @" "; /// /// Indent space strings array. /// - internal static string[] spaces = { + internal static readonly string[] spaces = { string.Empty, space, space + space, @@ -189,26 +191,26 @@ internal static bool GenerateVerboseMessage /// /// Lock the log file. /// - internal static object logLock = new object(); + internal static readonly object logLock = new object(); #endregion #region internal strings - internal static string runspaceStateChanged = "Runspace {0} state changed to {1}"; - internal static string classDumpInfo = @"Class type is {0}"; - internal static string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}"; - internal static string defaultPropertyType = @"It is a default property, default value is {0}"; - internal static string propertyValueSet = @"This property value is set by user {0}"; - internal static string addParameterSetName = @"Add parameter set {0} name to cache"; - internal static string removeParameterSetName = @"Remove parameter set {0} name from cache"; - internal static string currentParameterSetNameCount = @"Cache have {0} parameter set names"; - internal static string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}"; - internal static string currentnonMandatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}"; - internal static string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names"; - internal static string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}"; - internal static string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}"; - internal static string startToResolveParameterSet = @"------Resolve ParameterSet Name"; - internal static string reservedString = @"------"; + internal static readonly string runspaceStateChanged = "Runspace {0} state changed to {1}"; + internal static readonly string classDumpInfo = @"Class type is {0}"; + internal static readonly string propertyDumpInfo = @"Property name {0} of type {1}, its value is {2}"; + internal static readonly string defaultPropertyType = @"It is a default property, default value is {0}"; + internal static readonly string propertyValueSet = @"This property value is set by user {0}"; + internal static readonly string addParameterSetName = @"Add parameter set {0} name to cache"; + internal static readonly string removeParameterSetName = @"Remove parameter set {0} name from cache"; + internal static readonly string currentParameterSetNameCount = @"Cache have {0} parameter set names"; + internal static readonly string currentParameterSetNameInCache = @"Cache have parameter set {0} valid {1}"; + internal static readonly string currentnonMandatoryParameterSetInCache = @"Cache have optional parameter set {0} valid {1}"; + internal static readonly string optionalParameterSetNameCount = @"Cache have {0} optional parameter set names"; + internal static readonly string finalParameterSetName = @"------Final parameter set name of the cmdlet is {0}"; + internal static readonly string addToOptionalParameterSet = @"Add to optional ParameterSetNames {0}"; + internal static readonly string startToResolveParameterSet = @"------Resolve ParameterSet Name"; + internal static readonly string reservedString = @"------"; #endregion #region runtime methods @@ -369,7 +371,6 @@ private static void WriteLogInternal(string message, int indent, int depth) { writer.WriteLineAsync(spaces[indent] + sourceInformation + @" " + message); } - } } } @@ -433,7 +434,7 @@ public static string ValidateArgumentIsValidName(string parameterName, string va } DebugHelper.WriteLogEx("An invalid name: {0}={1}", 0, parameterName, value); - throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, Strings.InvalidParameterValue, value, parameterName)); + throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.InvalidParameterValue, value, parameterName)); } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/Microsoft.Management.Infrastructure.CimCmdlets.Strings.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx similarity index 100% rename from src/Microsoft.Management.Infrastructure.CimCmdlets/resources/Microsoft.Management.Infrastructure.CimCmdlets.Strings.resx rename to src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx diff --git a/src/Microsoft.Management.UI.Internal/CommonHelper.cs b/src/Microsoft.Management.UI.Internal/CommonHelper.cs index b9e1249f283..c9492c701d6 100644 --- a/src/Microsoft.Management.UI.Internal/CommonHelper.cs +++ b/src/Microsoft.Management.UI.Internal/CommonHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index ce1feafc422..8667afa3a62 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs index 4814f109890..7cbe4b0c74e 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -61,7 +61,7 @@ internal HelpViewModel(PSObject psObj, Paragraph documentParagraph) this.helpBuilder = new HelpParagraphBuilder(documentParagraph, psObj); this.helpBuilder.BuildParagraph(); this.searcher = new ParagraphSearcher(); - this.helpBuilder.PropertyChanged += new PropertyChangedEventHandler(this.HelpBuilder_PropertyChanged); + this.helpBuilder.PropertyChanged += this.HelpBuilder_PropertyChanged; this.helpTitle = string.Format( CultureInfo.CurrentCulture, HelpWindowResources.HelpTitleFormat, diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml index 15d3ed562c7..2b2a8fe60b1 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs index 8fb5a65ebb6..6793806503a 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindow.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; @@ -74,11 +74,11 @@ public HelpWindow(PSObject helpObject) this.ReadZoomUserSetting(); - this.viewModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(this.ViewModel_PropertyChanged); + this.viewModel.PropertyChanged += this.ViewModel_PropertyChanged; this.DataContext = this.viewModel; - this.Loaded += new RoutedEventHandler(this.HelpDialog_Loaded); - this.Closed += new System.EventHandler(this.HelpDialog_Closed); + this.Loaded += this.HelpDialog_Loaded; + this.Closed += this.HelpDialog_Closed; } /// @@ -222,9 +222,9 @@ private void HelpDialog_StateChanged(object sender, System.EventArgs e) /// Event arguments. private void HelpDialog_Loaded(object sender, RoutedEventArgs e) { - this.StateChanged += new System.EventHandler(this.HelpDialog_StateChanged); - this.LocationChanged += new System.EventHandler(this.HelpDialog_LocationChanged); - this.SizeChanged += new SizeChangedEventHandler(this.HelpDialog_SizeChanged); + this.StateChanged += this.HelpDialog_StateChanged; + this.LocationChanged += this.HelpDialog_LocationChanged; + this.SizeChanged += this.HelpDialog_SizeChanged; } /// diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs index 03f214dd60d..937429ebf09 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpWindowSettings.Designer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------ // diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 26005f6467f..822e4c05026 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs index 22094797073..e71a27bac8b 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics; diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml b/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml index 47877ddb78f..d99c86c2a6a 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs index 4687758b485..5d499d47f71 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/SettingsDialog.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs index dbfa42ed53c..40f3e9e15a9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs index d542ee0654f..1c0690a43c9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationImage.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs index 44fbd38dff4..50db1bb78c1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlock.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs index 79950b95b4e..6de73299abb 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/AutomationTextBlockAutomationPeer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs index f75bad7e982..92d50d5d007 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/BooleanBoxes.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs index 7316b3e50e9..c9c8606f899 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/CommandHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs index 49b1beb54fc..6b0db6d5f95 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/CustomTypeComparer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs index aefcb941741..cf65462c3b4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs index 9090f5764af..affbe8ca4ab 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DateTimeApproximationComparer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -56,8 +56,7 @@ private static void GetRoundedValues(DateTime value1, DateTime value2, out DateT private static bool HasTimeComponent(DateTime value) { - bool hasNoTimeComponent = true - && value.Hour == 0 + bool hasNoTimeComponent = value.Hour == 0 && value.Minute == 0 && value.Second == 0 && value.Millisecond == 0; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs index 1eb1d456389..76e3206f1f5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs index fa08b212e4a..582be1c7ecd 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs index 1670e7bbc6e..0f269df5b75 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ExtendedFrameworkElementAutomationPeer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs index 4798e8e5c90..a87266dd696 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IAsyncProgress.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs index cecccc6a7ee..e1539e76707 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IStateDescriptorFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs index caffb63b645..dff537f00bb 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs index c8f5f8e29e7..55b57d76a3f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs index d340839f5f9..83cd762198f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs index 21371fee76f..265e0266c53 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsNotNullConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs index 3de99caeb4f..90684f3f6cc 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs index fa30bc0c700..799cd260e12 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs index 67ad950fbc8..7f8a0f8bfc4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs index 44d77369723..e51172095a1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // // diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs index fad63be68e4..469ed5aec77 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -46,7 +46,7 @@ public void Select() { if (!this.IsLoaded) { - this.Loaded += new RoutedEventHandler(this.ListOrganizerItem_Loaded_SelectItem); + this.Loaded += this.ListOrganizerItem_Loaded_SelectItem; this.ApplyTemplate(); return; } @@ -189,7 +189,7 @@ private void UpdateTextContentBindings() { if (!this.IsLoaded) { - this.Loaded += new RoutedEventHandler(this.ListOrganizerItem_Loaded_UpdateTextContentBindings); + this.Loaded += this.ListOrganizerItem_Loaded_UpdateTextContentBindings; this.ApplyTemplate(); return; } @@ -230,13 +230,13 @@ partial void PostOnApplyTemplate() private void AttachToVisualTree() { this.editBox.IsVisibleChanged += new DependencyPropertyChangedEventHandler(this.EditBox_IsVisibleChanged); - this.editBox.KeyDown += new KeyEventHandler(this.EditBox_KeyDown); - this.editBox.LostFocus += new RoutedEventHandler(this.EditBox_LostFocus); + this.editBox.KeyDown += this.EditBox_KeyDown; + this.editBox.LostFocus += this.EditBox_LostFocus; this.templatedParent = this.TemplatedParent as FrameworkElement; if (this.templatedParent != null) { - this.templatedParent.KeyDown += new KeyEventHandler(this.TemplatedParent_OnKeyDown); + this.templatedParent.KeyDown += this.TemplatedParent_OnKeyDown; } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs index b764ed81355..e204886880a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.cs index 89a6288b03d..741d93a07d3 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/MessageTextBox.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs index 46065a9398f..f8b8bec0a5a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs index 5644faa91e0..bb4b6c61511 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PickerBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -47,7 +47,7 @@ private void ApplyDropDownButtonTemplate() if (!this.IsLoaded) { this.ApplyTemplate(); - this.Loaded += new RoutedEventHandler(this.PickerBase_Loaded_ApplyDropDownButtonTemplate); + this.Loaded += this.PickerBase_Loaded_ApplyDropDownButtonTemplate; return; } @@ -76,7 +76,7 @@ private void FocusDropDown() { if (!this.dropDown.IsLoaded) { - this.dropDown.Loaded += new RoutedEventHandler(this.DropDown_Loaded_FocusDropDown); + this.dropDown.Loaded += this.DropDown_Loaded_FocusDropDown; } if (this.dropDown.Child != null && !this.dropDown.IsAncestorOf((DependencyObject)Keyboard.FocusedElement)) @@ -116,8 +116,8 @@ partial void PreOnApplyTemplate() private void AttachToVisualTree() { - this.dropDown.Opened += new EventHandler(this.DropDown_Opened); - this.dropDown.Closed += new EventHandler(this.DropDown_Closed); + this.dropDown.Opened += this.DropDown_Opened; + this.dropDown.Closed += this.DropDown_Closed; } private void DetachFromVisualTree() diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs index 291a65373d1..c358ce69985 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.cs index 66cb1ef10e6..b02ea20e07a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PopupControlButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PropertyChangedEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PropertyChangedEventArgs.cs index 010c69f6a4e..7d601bf8e26 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/PropertyChangedEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/PropertyChangedEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs index 8e59ff89368..7734bc4903c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -34,8 +34,8 @@ public ReadOnlyObservableAsyncCollection(IList list) { this.asyncProgress = list as IAsyncProgress; - ((INotifyCollectionChanged)this.Items).CollectionChanged += new NotifyCollectionChangedEventHandler(this.HandleCollectionChanged); - ((INotifyPropertyChanged)this.Items).PropertyChanged += new PropertyChangedEventHandler(this.HandlePropertyChanged); + ((INotifyCollectionChanged)this.Items).CollectionChanged += this.HandleCollectionChanged; + ((INotifyPropertyChanged)this.Items).PropertyChanged += this.HandlePropertyChanged; } #endregion Constructors diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs index 319de2fed32..6d682160e49 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs index 2799ce6e1d0..b994bb1a29a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs index 5a4fb439c46..aaafd913976 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.cs index 1587c5feb5b..5f88400d63b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImageSource.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs index fedb4f97138..be8cc841757 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs index ec7e43a9003..a2e2b144ad6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.Generated.cs index 5a7523cf04e..9270c8f7914 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs index 79b36812065..888c03944a2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextBlockService.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -25,7 +25,7 @@ static partial void IsTextTrimmedMonitoringEnabledProperty_PropertyChangedImplem return; } - if ((bool)e.OldValue == true) + if ((bool)e.OldValue) { tb.SizeChanged -= OnTextBlockSizeChanged; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextTrimConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextTrimConverter.cs index cc81995074b..1ea4bf3b96f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextTrimConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/TextTrimConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs index 665c9b3c76c..f0308a8c2b7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs index 1d2776ce8e9..85a7d00a61f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs index 3f69908d5c9..cc18509092f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 01f96bfa1f7..23ff80d9974 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -65,7 +65,7 @@ public static bool RetryActionAfterLoaded(FrameworkElement element, RetryActi data.Enqueue(callback, parameter); - element.Loaded += new RoutedEventHandler(Element_Loaded); + element.Loaded += Element_Loaded; element.ApplyTemplate(); return true; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/AutomationGroup.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/AutomationGroup.cs index 90bcd753e9b..1341c12a25c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/AutomationGroup.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/AutomationGroup.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows.Automation.Peers; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.Generated.cs index 17988f4a8f5..2429db7b734 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs index e47ed8b4316..b641811444e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButton.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButtonAutomationPeer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButtonAutomationPeer.cs index db7ef0ed4ab..3f6f2a3888b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButtonAutomationPeer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ExpanderButtonAutomationPeer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs index 6a99d0fd132..5e2c18129e6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs index 6a7de4b6400..19c0671bf21 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/Resizer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs index 7b496a2f9a2..4cdf51f63f6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs index 0d8b7ab8257..7e60d4c6ffc 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs index 6ec505237bc..987a1170890 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/UIElementAdorner.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs index 7fc17d01ea2..bd5faf32d63 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -168,8 +168,7 @@ public override string GetErrorMessageForInvalidValue(string value, Type typeToP throw new ArgumentNullException("typeToParseTo"); } - bool isNumericType = false - || typeToParseTo == typeof(byte) + bool isNumericType = typeToParseTo == typeof(byte) || typeToParseTo == typeof(sbyte) || typeToParseTo == typeof(short) || typeToParseTo == typeof(ushort) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 14246932829..2b33153a983 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -151,7 +151,7 @@ public void AddFilterExpressionProvider(IFilterExpressionProvider provider) } this.filterExpressionProviders.Add(provider); - provider.FilterExpressionChanged += new EventHandler(this.FilterProvider_FilterExpressionChanged); + provider.FilterExpressionChanged += this.FilterProvider_FilterExpressionChanged; } /// @@ -168,7 +168,7 @@ public void RemoveFilterExpressionProvider(IFilterExpressionProvider provider) } this.filterExpressionProviders.Remove(provider); - provider.FilterExpressionChanged -= new EventHandler(this.FilterProvider_FilterExpressionChanged); + provider.FilterExpressionChanged -= this.FilterProvider_FilterExpressionChanged; } #region NotifyPropertyChanged diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs index f2694bd152f..b7a26757b21 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs index 24262acc43d..f255973dce8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs index f4a30df084d..e9e41b93f20 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs index fa021cb747d..f6bfd17377b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs index aa052436ff9..201316a433e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs index 6019d06e528..75019cdbf5d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs index 419c9c8987f..e75cd59f17a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs index 3263dfc77bd..ea74ee062f9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs index d119e0d8bcb..5f21f57292b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs index 2e21b412bf5..1c2fc523e86 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs index 19452a49656..cb0a79de775 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs index 6d73a582a3a..b54508157a6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -63,10 +63,10 @@ public IsBetweenFilterRule() this.DisplayName = UICultureResources.FilterRule_IsBetween; this.StartValue = new ValidatingValue(); - this.StartValue.PropertyChanged += new PropertyChangedEventHandler(this.Value_PropertyChanged); + this.StartValue.PropertyChanged += this.Value_PropertyChanged; this.EndValue = new ValidatingValue(); - this.EndValue.PropertyChanged += new PropertyChangedEventHandler(this.Value_PropertyChanged); + this.EndValue.PropertyChanged += this.Value_PropertyChanged; } #endregion Ctor @@ -111,8 +111,8 @@ private void Value_PropertyChanged(object sender, PropertyChangedEventArgs e) [OnDeserialized] private void Initialize(StreamingContext context) { - this.StartValue.PropertyChanged += new PropertyChangedEventHandler(this.Value_PropertyChanged); - this.EndValue.PropertyChanged += new PropertyChangedEventHandler(this.Value_PropertyChanged); + this.StartValue.PropertyChanged += this.Value_PropertyChanged; + this.EndValue.PropertyChanged += this.Value_PropertyChanged; } #endregion Value Change Handlers diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs index 311c8198bd8..8e8b91087ef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs index 0d4ae3f8a09..bd9af169e82 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs index 936d9380ca4..db3bc01f810 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs index 537713f420c..c9bfc7519a0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs index 8a4137051c8..924ffc02af8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs index 1530991ca15..c29715419ce 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -26,7 +26,7 @@ public class PropertiesTextContainsFilterRule : TextFilterRule public PropertiesTextContainsFilterRule() { this.PropertyNames = new List(); - this.EvaluationResultInvalidated += new EventHandler(this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated); + this.EvaluationResultInvalidated += this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated; } /// @@ -124,7 +124,7 @@ private void PropertiesTextContainsFilterRule_EvaluationResultInvalidated(object [OnDeserialized] private void Initialize(StreamingContext context) { - this.EvaluationResultInvalidated += new EventHandler(this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated); + this.EvaluationResultInvalidated += this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated; } } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index 4d8b4c77405..e8927c74826 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs index 6bb5c0a4634..c67b1c993e5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -45,7 +45,7 @@ public ValidatingSelectorValue AvailableRules public SelectorFilterRule() { this.AvailableRules = new ValidatingSelectorValue(); - this.AvailableRules.SelectedValueChanged += new EventHandler>(this.AvailableRules_SelectedValueChanged); + this.AvailableRules.SelectedValueChanged += this.AvailableRules_SelectedValueChanged; } #endregion Ctor @@ -86,8 +86,8 @@ protected void OnSelectedValueChanged(FilterRule oldValue, FilterRule newValue) FilterRuleCustomizationFactory.FactoryInstance.TransferValues(oldValue, newValue); FilterRuleCustomizationFactory.FactoryInstance.ClearValues(oldValue); - newValue.EvaluationResultInvalidated += new EventHandler(this.SelectedValue_EvaluationResultInvalidated); - oldValue.EvaluationResultInvalidated -= new EventHandler(this.SelectedValue_EvaluationResultInvalidated); + newValue.EvaluationResultInvalidated += this.SelectedValue_EvaluationResultInvalidated; + oldValue.EvaluationResultInvalidated -= this.SelectedValue_EvaluationResultInvalidated; this.NotifyEvaluationResultInvalidated(); } @@ -104,8 +104,8 @@ private void SelectedValue_EvaluationResultInvalidated(object sender, EventArgs [OnDeserialized] private void Initialize(StreamingContext context) { - this.AvailableRules.SelectedValueChanged += new EventHandler>(this.AvailableRules_SelectedValueChanged); - this.AvailableRules.SelectedValue.EvaluationResultInvalidated += new EventHandler(this.SelectedValue_EvaluationResultInvalidated); + this.AvailableRules.SelectedValueChanged += this.AvailableRules_SelectedValueChanged; + this.AvailableRules.SelectedValue.EvaluationResultInvalidated += this.SelectedValue_EvaluationResultInvalidated; } private void AvailableRules_SelectedValueChanged(object sender, PropertyChangedEventArgs e) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs index abfc83ba2bf..5aaabe58bfb 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -49,7 +49,7 @@ public override bool IsValid protected SingleValueComparableValueFilterRule() { this.Value = new ValidatingValue(); - this.Value.PropertyChanged += new PropertyChangedEventHandler(this.Value_PropertyChanged); + this.Value.PropertyChanged += this.Value_PropertyChanged; } #endregion Ctor @@ -65,7 +65,7 @@ private void Value_PropertyChanged(object sender, PropertyChangedEventArgs e) [OnDeserialized] private void Initialize(StreamingContext context) { - this.Value.PropertyChanged += new PropertyChangedEventHandler(this.Value_PropertyChanged); + this.Value.PropertyChanged += this.Value_PropertyChanged; } } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs index 2de7780da52..9186827c5f5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs index d2bc1973d5f..dcfeabff4c4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs index 57f8db3972f..3666b17c2de 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs index 9bb052cc248..45a9dd85386 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs index 5b6132b2ce2..6401506bf1d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs index cf9d66a7293..3440935889f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs index 549c5cc637d..8cfdc7960d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterStatus.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterStatus.cs index 6fc01dfc03a..74cca6e890d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterStatus.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterStatus.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs index f1435ffd2f3..f4827d1b454 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterUtilities.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs index 195e27b2598..f83f6b377aa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IFilterExpressionProvider.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IFilterExpressionProvider.cs index 4063fd84a40..b72fcfe5aef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IFilterExpressionProvider.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IFilterExpressionProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs index ad8ec4d3d9e..d68ead8bc4b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ItemsControlFilterEvaluator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs index 7edb2e62a4c..ed5389668e6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -47,6 +47,7 @@ public IList AvailableValues #region SelectedIndex private const string SelectedIndexPropertyName = "SelectedIndex"; + private int selectedIndex; /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index c429cc44854..cf9c553f6b4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index f2ca5b67f2a..f3959685349 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationResult.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationResult.cs index 8b1ab8f17a6..39ccd531c38 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationResult.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs index 42b7b14d9d3..9b4a2b23d0d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs index fea3c9e996d..e326f6542e0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs index d6bab1e092d..d41b0a3e532 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePicker.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs index 6f732a3358e..24c6eec1889 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/AddFilterRulePickerItem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.Generated.cs index dafb4b03a0f..5a87767b70a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index fb27cd19c8c..bcc9a01a92c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -133,7 +133,7 @@ public FilterRulePanel() { this.InitializeTemplates(); - this.Controller.FilterExpressionChanged += new EventHandler(this.Controller_FilterExpressionChanged); + this.Controller.FilterExpressionChanged += this.Controller_FilterExpressionChanged; } #endregion Ctor diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelContentPresenter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelContentPresenter.cs index 1783b366d3b..7955a149435 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelContentPresenter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelContentPresenter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs index 157424b3221..dcec5022d98 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -96,7 +96,7 @@ public void AddFilterRulePanelItem(FilterRulePanelItem item) int insertionIndex = this.GetInsertionIndex(item); this.filterRulePanelItems.Insert(insertionIndex, item); - item.Rule.EvaluationResultInvalidated += new EventHandler(this.Rule_EvaluationResultInvalidated); + item.Rule.EvaluationResultInvalidated += this.Rule_EvaluationResultInvalidated; this.UpdateFilterRulePanelItemTypes(); @@ -121,7 +121,7 @@ public void RemoveFilterRulePanelItem(FilterRulePanelItem item) throw new ArgumentNullException("item"); } - item.Rule.EvaluationResultInvalidated -= new EventHandler(this.Rule_EvaluationResultInvalidated); + item.Rule.EvaluationResultInvalidated -= this.Rule_EvaluationResultInvalidated; this.filterRulePanelItems.Remove(item); this.UpdateFilterRulePanelItemTypes(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index 8d45204a7a5..a1a873cdbc7 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItemType.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItemType.cs index 341005abaf8..490d1776ec0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItemType.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItemType.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs index 0e9773664c2..fc40c3c5768 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -45,11 +45,7 @@ public override DataTemplate SelectTemplate(object item, System.Windows.Dependen return base.SelectTemplate(item, container); } - Type type = item as Type; - if (type == null) - { - type = item.GetType(); - } + Type type = item as Type ?? item.GetType(); DataTemplate template; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs index 5434ffc9754..07a4ed58f8b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs index 20130a7823f..0017f2a4340 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/IsValidatingValueValidConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/IsValidatingValueValidConverter.cs index 8495139b768..4c07ec10f6d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/IsValidatingValueValidConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/IsValidatingValueValidConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs index f864b222ab9..3a6c7fedae8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs index 2472dcb17dc..25830150939 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs index 1af2103eab7..5fa5e3e7703 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index 5a34b0ca985..04ba32ece6d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs index c62ef7f144a..e8708b92a15 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingValueToGenericParameterTypeConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingValueToGenericParameterTypeConverter.cs index 6d56afd4f22..ccd7447e1de 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingValueToGenericParameterTypeConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingValueToGenericParameterTypeConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml index 4c2a6ee6acb..3c4f7e86157 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs index a585aff27ae..470a7670860 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs index e0ac198d500..cf85d79ae36 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/IPropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/IPropertyValueGetter.cs index 03051218587..bf435d20103 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/IPropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/IPropertyValueGetter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs index 7db7d10791e..d53c8eb8daf 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerList.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListColumn.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListColumn.Generated.cs index 9e13b33f1ac..51311c6f875 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListColumn.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListColumn.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs index f949afe6430..73222cae639 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -54,8 +54,8 @@ internal InnerListGridView(ObservableCollection availableColumn this.AvailableColumns = availableColumns; this.AvailableColumns_CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, availableColumns)); - availableColumns.CollectionChanged += new NotifyCollectionChangedEventHandler(this.AvailableColumns_CollectionChanged); - this.Columns.CollectionChanged += new NotifyCollectionChangedEventHandler(this.Columns_CollectionChanged); + availableColumns.CollectionChanged += this.AvailableColumns_CollectionChanged; + this.Columns.CollectionChanged += this.Columns_CollectionChanged; } /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index 28f8be37a4f..03c7acdf008 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -543,8 +543,8 @@ internal void SetColumnHeaderActions() if (header != null) { // header Click - header.Click += new RoutedEventHandler(this.Header_Click); - header.PreviewKeyDown += new KeyEventHandler(this.Header_KeyDown); + header.Click += this.Header_Click; + header.PreviewKeyDown += this.Header_KeyDown; } // If it is a GridViewColumnHeader we will not have the same nice sorting and grouping @@ -695,7 +695,7 @@ private bool SetColumnPickerContextMenuItem() MenuItem columnPicker = new MenuItem(); AutomationProperties.SetAutomationId(columnPicker, "ChooseColumns"); columnPicker.Header = UICultureResources.ColumnPicker; - columnPicker.Click += new RoutedEventHandler(this.innerGrid.OnColumnPicker); + columnPicker.Click += this.innerGrid.OnColumnPicker; this.contextMenu.Items.Add(columnPicker); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs index 2627fa20884..3ffb8993185 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementList.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs index 6b07e1adbf2..841175c97da 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptorFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptorFactory.cs index 276cb798452..07c2cec62fa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptorFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptorFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs index 8becd00210b..6aa6d584e65 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.Generated.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region StyleCop Suppression - generated code diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.cs index a8e27916bf7..66be05cdf33 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListTitle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows.Controls; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs index f977ef72887..5c9f56daa81 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueComparer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 6f809560f28..61a1a71938c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -14,6 +14,7 @@ namespace Microsoft.Management.UI.Internal public class PropertyValueGetter : IPropertyValueGetter { private const string PropertyDescriptorColumnId = "PropertyDescriptor"; + private DataTable cachedProperties; /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/UIPropertyGroupDescription.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/UIPropertyGroupDescription.cs index 4d6b3cb54a1..44d869c3272 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/UIPropertyGroupDescription.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/UIPropertyGroupDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs index 92c3a7a59db..c69cd8e0c08 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/WaitRing.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/WaitRing.cs index a368cad00fc..c65da37d6f0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/WaitRing.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/WaitRing.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs index 502a95b2ad2..9f91f2b74e8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 8513a758fe4..7c36244e0f1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -128,16 +128,16 @@ partial void OnEvaluatorChangedImplementation(PropertyChangedEventArgs diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs index 35ff24db066..5d360017c16 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/AllModulesControl.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml index 63d24fc8516..f7e77ed944d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs index e5bf176b56a..0837bb567e4 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/CmdletControl.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; @@ -23,10 +23,10 @@ public partial class CmdletControl : UserControl public CmdletControl() { InitializeComponent(); - this.NotImportedControl.ImportModuleButton.Click += new RoutedEventHandler(ImportModuleButton_Click); + this.NotImportedControl.ImportModuleButton.Click += ImportModuleButton_Click; this.ParameterSetTabControl.DataContextChanged += new DependencyPropertyChangedEventHandler(this.ParameterSetTabControl_DataContextChanged); - this.KeyDown += new System.Windows.Input.KeyEventHandler(this.CmdletControl_KeyDown); - this.helpButton.innerButton.Click += new RoutedEventHandler(this.HelpButton_Click); + this.KeyDown += this.CmdletControl_KeyDown; + this.helpButton.innerButton.Click += this.HelpButton_Click; } #endregion diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml index 5d4078676e6..024b287e80a 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs index f788b06edab..05247f46ff0 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButton.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -20,7 +20,7 @@ public partial class ImageButton : ImageButtonBase public ImageButton() { InitializeComponent(); - this.Loaded += new System.Windows.RoutedEventHandler(this.ImageButton_Loaded); + this.Loaded += this.ImageButton_Loaded; } /// diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs index f415294d46d..76ab5cf3c28 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml index 36a599399eb..f89e474a2de 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonCommon.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs index 2562db07d53..bec10afc6b7 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageButtonToolTipConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml index 6f8659bded0..c472721ac85 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs index 97056f54916..adc1e1a6421 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ImageButton/ImageToggleButton.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -25,7 +25,7 @@ public partial class ImageToggleButton : ImageButtonBase public ImageToggleButton() { InitializeComponent(); - this.Loaded += new System.Windows.RoutedEventHandler(this.ImageButton_Loaded); + this.Loaded += this.ImageButton_Loaded; } /// diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml index 515bb076e5b..557741edf0d 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs index 1008a691b94..54dcf1896ff 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml index aed99f1bd90..cb0a9198b80 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs index f3299dddca0..65774004236 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/NotImportedCmdletControl.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows.Controls; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml index b991ced09b6..c59f519d663 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs index b9c681018ff..c258a2819ac 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -224,7 +224,7 @@ private static TextBox CreateTextBoxControl(ParameterViewModel parameterViewMode textBox.AcceptsReturn = true; textBox.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; textBox.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; - textBox.Loaded += new RoutedEventHandler(ParameterSetControl.MultiLineTextBox_Loaded); + textBox.Loaded += ParameterSetControl.MultiLineTextBox_Loaded; } return textBox; @@ -238,7 +238,7 @@ private static TextBox CreateTextBoxControl(ParameterViewModel parameterViewMode private static void MultiLineTextBox_Loaded(object sender, RoutedEventArgs e) { TextBox senderTextBox = (TextBox)sender; - senderTextBox.Loaded -= new RoutedEventHandler(ParameterSetControl.MultiLineTextBox_Loaded); + senderTextBox.Loaded -= ParameterSetControl.MultiLineTextBox_Loaded; // This will set the height to about 3 lines since the total height of the // TextBox is a bit greater than a line's height diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml index 7a129e05ad8..e03c7859ed0 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs index cff283bcf6a..440eb329f39 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; @@ -26,10 +26,10 @@ public ShowModuleControl() InitializeComponent(); // See comment in method summary to understand why this event is handled - this.CommandList.PreviewMouseMove += new MouseEventHandler(this.CommandList_PreviewMouseMove); + this.CommandList.PreviewMouseMove += this.CommandList_PreviewMouseMove; // See comment in method summary to understand why this event is handled - this.CommandList.SelectionChanged += new SelectionChangedEventHandler(this.CommandList_SelectionChanged); + this.CommandList.SelectionChanged += this.CommandList_SelectionChanged; } /// diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs index 589fb63b52c..18194cec8fb 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ShowCommandSettings.Designer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------ // diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index ee7ca11ccbd..34159c8f837 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -239,10 +239,10 @@ public ModuleViewModel SelectedModule if (this.selectedModule != null) { - this.selectedModule.SelectedCommandNeedsImportModule -= new EventHandler(this.SelectedModule_SelectedCommandNeedsImportModule); - this.selectedModule.SelectedCommandNeedsHelp -= new EventHandler(this.SelectedModule_SelectedCommandNeedsHelp); - this.selectedModule.RunSelectedCommand -= new EventHandler(this.SelectedModule_RunSelectedCommand); - this.selectedModule.PropertyChanged -= new PropertyChangedEventHandler(this.SelectedModule_PropertyChanged); + this.selectedModule.SelectedCommandNeedsImportModule -= this.SelectedModule_SelectedCommandNeedsImportModule; + this.selectedModule.SelectedCommandNeedsHelp -= this.SelectedModule_SelectedCommandNeedsHelp; + this.selectedModule.RunSelectedCommand -= this.SelectedModule_RunSelectedCommand; + this.selectedModule.PropertyChanged -= this.SelectedModule_PropertyChanged; } this.selectedModule = value; @@ -252,10 +252,10 @@ public ModuleViewModel SelectedModule if (this.selectedModule != null) { this.selectedModule.RefreshFilteredCommands(this.CommandNameFilter); - this.selectedModule.SelectedCommandNeedsImportModule += new EventHandler(this.SelectedModule_SelectedCommandNeedsImportModule); - this.selectedModule.SelectedCommandNeedsHelp += new EventHandler(this.SelectedModule_SelectedCommandNeedsHelp); - this.selectedModule.RunSelectedCommand += new EventHandler(this.SelectedModule_RunSelectedCommand); - this.selectedModule.PropertyChanged += new PropertyChangedEventHandler(this.SelectedModule_PropertyChanged); + this.selectedModule.SelectedCommandNeedsImportModule += this.SelectedModule_SelectedCommandNeedsImportModule; + this.selectedModule.SelectedCommandNeedsHelp += this.SelectedModule_SelectedCommandNeedsHelp; + this.selectedModule.RunSelectedCommand += this.SelectedModule_RunSelectedCommand; + this.selectedModule.PropertyChanged += this.SelectedModule_PropertyChanged; this.selectedModule.SelectedCommand = null; } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs index 5ffdba45b06..857d466c80f 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index c5e25028823..a098185095c 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -168,13 +168,13 @@ public ParameterSetViewModel SelectedParameterSet { if (this.selectedParameterSet != null) { - this.selectedParameterSet.PropertyChanged -= new PropertyChangedEventHandler(this.SelectedParameterSet_PropertyChanged); + this.selectedParameterSet.PropertyChanged -= this.SelectedParameterSet_PropertyChanged; } this.selectedParameterSet = value; if (this.selectedParameterSet != null) { - this.selectedParameterSet.PropertyChanged += new PropertyChangedEventHandler(this.SelectedParameterSet_PropertyChanged); + this.selectedParameterSet.PropertyChanged += this.SelectedParameterSet_PropertyChanged; this.SelectedParameterSetAllMandatoryParametersHaveValues = this.SelectedParameterSet.AllMandatoryParametersHaveValues; } else @@ -429,7 +429,7 @@ public string GetScript() commandName = this.ModuleName + "\\" + commandName; } - if (commandName.IndexOf(' ') != -1) + if (commandName.Contains(' ')) { builder.AppendFormat("& \"{0}\"", commandName); } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs index 039eee9e1e4..3d4c42a6cbe 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/HelpNeededEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs index 5bdeeb87aff..3d7a7ccf3f0 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ImportModuleEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index 66a768940c4..38925e458a9 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -188,9 +188,9 @@ public CommandViewModel SelectedCommand if (this.selectedCommand != null) { - this.selectedCommand.PropertyChanged -= new PropertyChangedEventHandler(this.SelectedCommand_PropertyChanged); - this.selectedCommand.HelpNeeded -= new EventHandler(this.SelectedCommand_HelpNeeded); - this.selectedCommand.ImportModule -= new EventHandler(this.SelectedCommand_ImportModule); + this.selectedCommand.PropertyChanged -= this.SelectedCommand_PropertyChanged; + this.selectedCommand.HelpNeeded -= this.SelectedCommand_HelpNeeded; + this.selectedCommand.ImportModule -= this.SelectedCommand_ImportModule; } this.selectedCommand = value; @@ -199,9 +199,9 @@ public CommandViewModel SelectedCommand if (this.selectedCommand != null) { - this.selectedCommand.PropertyChanged += new PropertyChangedEventHandler(this.SelectedCommand_PropertyChanged); - this.selectedCommand.HelpNeeded += new EventHandler(this.SelectedCommand_HelpNeeded); - this.selectedCommand.ImportModule += new EventHandler(this.SelectedCommand_ImportModule); + this.selectedCommand.PropertyChanged += this.SelectedCommand_PropertyChanged; + this.selectedCommand.HelpNeeded += this.SelectedCommand_HelpNeeded; + this.selectedCommand.ImportModule += this.SelectedCommand_ImportModule; this.IsThereASelectedCommand = true; } else @@ -435,21 +435,21 @@ private static bool Matches(WildcardPattern filterPattern, string commandName, s /// Return match result. private static bool MatchesEvenIfInPlural(string commandName, string filter) { - if (commandName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1) + if (commandName.Contains(filter, StringComparison.OrdinalIgnoreCase)) { return true; } if (filter.Length > 5 && filter.EndsWith("es", StringComparison.OrdinalIgnoreCase)) { - filter = filter.Substring(0, filter.Length - 2); - return commandName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1; + ReadOnlySpan filterSpan = filter.AsSpan(0, filter.Length - 2); + return commandName.AsSpan().Contains(filterSpan, StringComparison.OrdinalIgnoreCase); } if (filter.Length > 4 && filter.EndsWith("s", StringComparison.OrdinalIgnoreCase)) { - filter = filter.Substring(0, filter.Length - 1); - return commandName.IndexOf(filter, StringComparison.OrdinalIgnoreCase) != -1; + ReadOnlySpan filterSpan = filter.AsSpan(0, filter.Length - 1); + return commandName.AsSpan().Contains(filterSpan, StringComparison.OrdinalIgnoreCase); } return false; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 33364d42181..756f58c62c8 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -66,7 +66,7 @@ public ParameterSetViewModel( continue; } - parameter.PropertyChanged += new PropertyChangedEventHandler(this.MandatoryParameter_PropertyChanged); + parameter.PropertyChanged += this.MandatoryParameter_PropertyChanged; } this.EvaluateAllMandatoryParametersHaveValues(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs index eea774177d2..2c6931eb08e 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml index 26991e87e25..185c5513ddb 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs index 8de3b5e1cb3..8097952ffab 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/MultipleSelectionDialog.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml index edbac1f5605..7a88bb3699b 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs index 2ad52f84b5a..b644264376b 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowAllModulesWindow.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -49,10 +49,10 @@ public ShowAllModulesWindow() this.AllModulesControl.ShowModuleControl.Owner = this; } - this.SizeChanged += new SizeChangedEventHandler(this.ShowAllModulesWindow_SizeChanged); - this.LocationChanged += new System.EventHandler(this.ShowAllModulesWindow_LocationChanged); - this.StateChanged += new System.EventHandler(this.ShowAllModulesWindow_StateChanged); - this.Loaded += new RoutedEventHandler(this.ShowAllModulesWindow_Loaded); + this.SizeChanged += this.ShowAllModulesWindow_SizeChanged; + this.LocationChanged += this.ShowAllModulesWindow_LocationChanged; + this.StateChanged += this.ShowAllModulesWindow_StateChanged; + this.Loaded += this.ShowAllModulesWindow_Loaded; RoutedCommand plusSettings = new RoutedCommand(); KeyGestureConverter keyGestureConverter = new KeyGestureConverter(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml index 96258220f04..6617070be4e 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs index 6d1835c6d16..c03a42ed864 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Windows/ShowCommandWindow.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Windows; @@ -20,9 +20,9 @@ public partial class ShowCommandWindow : Window public ShowCommandWindow() { this.InitializeComponent(); - this.SizeChanged += new SizeChangedEventHandler(this.ShowCommandWindow_SizeChanged); - this.LocationChanged += new System.EventHandler(this.ShowCommandWindow_LocationChanged); - this.StateChanged += new System.EventHandler(this.ShowCommandWindow_StateChanged); + this.SizeChanged += this.ShowCommandWindow_SizeChanged; + this.LocationChanged += this.ShowCommandWindow_LocationChanged; + this.StateChanged += this.ShowCommandWindow_StateChanged; } /// diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs index 04e6d74ae69..efed820e71c 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs index ea36be8c73d..85ecd95a36f 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -135,10 +135,10 @@ private void StartWindow(string invocation, string outputModeOptions, AutoResetE { this.gridViewWindow = new Window(); this.managementList = CreateManagementList(outputModeOptions); - this.gridViewWindow.Loaded += new RoutedEventHandler(this.GridViewWindowLoaded); + this.gridViewWindow.Loaded += this.GridViewWindowLoaded; this.gridViewWindow.Content = CreateMainGrid(outputModeOptions); this.gridViewWindow.Title = invocation; - this.gridViewWindow.Closed += new EventHandler(this.GridViewWindowClosed); + this.gridViewWindow.Closed += this.GridViewWindowClosed; RoutedCommand plusSettings = new RoutedCommand(); KeyGestureConverter keyGestureConverter = new KeyGestureConverter(); @@ -323,7 +323,7 @@ private Button CreateOKButton() ok.SetValue(Grid.ColumnProperty, 0); ok.IsDefault = true; ok.SetValue(AutomationProperties.AutomationIdProperty, "OGVOK"); - ok.Click += new RoutedEventHandler(OK_Click); + ok.Click += OK_Click; return ok; } @@ -340,7 +340,7 @@ private Button CreateCancelButton() cancel.SetValue(Grid.ColumnProperty, 1); cancel.IsCancel = true; cancel.SetValue(AutomationProperties.AutomationIdProperty, "OGVCancel"); - cancel.Click += new RoutedEventHandler(Cancel_Click); + cancel.Click += Cancel_Click; return cancel; } diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs index 882f9e21c54..5d401fc94c6 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -597,11 +597,7 @@ internal static List GetCommandList(object[] commandObje /// An array of objects out of . internal static object[] ObjectArrayFromObjectCollection(object commandObjects) { - object[] objectArray = commandObjects as object[]; - if (objectArray == null) - { - objectArray = ((System.Collections.ArrayList)commandObjects).ToArray(); - } + object[] objectArray = commandObjects as object[] ?? ((System.Collections.ArrayList)commandObjects).ToArray(); return objectArray; } @@ -969,7 +965,7 @@ private void ShowCommandWindow(PSCmdlet cmdlet, object commandViewModelObj, doub this.commandViewModel = (CommandViewModel)commandViewModelObj; ShowCommandWindow showCommandWindow = new ShowCommandWindow(); - this.commandViewModel.HelpNeeded += new EventHandler(this.CommandNeedsHelp); + this.commandViewModel.HelpNeeded += this.CommandNeedsHelp; showCommandWindow.DataContext = this.commandViewModel; this.SetupButtonEvents(showCommandWindow.Run, showCommandWindow.Copy, showCommandWindow.Cancel, passThrough); @@ -1101,8 +1097,8 @@ private string GetScript() private void SetupWindow(Window commandWindow) { this.window = commandWindow; - this.window.Closed += new EventHandler(this.Window_Closed); - this.window.Loaded += new RoutedEventHandler(this.Window_Loaded); + this.window.Closed += this.Window_Closed; + this.window.Loaded += this.Window_Loaded; } /// @@ -1153,7 +1149,7 @@ private void Window_Closed(object sender, EventArgs e) /// Event arguments. private void Window_Loaded(object sender, RoutedEventArgs e) { - this.window.Loaded -= new RoutedEventHandler(this.Window_Loaded); + this.window.Loaded -= this.Window_Loaded; this.windowLoaded.Set(); } @@ -1172,9 +1168,9 @@ private void SetupButtonEvents(Button run, Button copy, Button cancel, bool pass run.Content = ShowCommandResources.ActionButtons_Button_Ok; } - run.Click += new RoutedEventHandler(this.Buttons_RunClick); - copy.Click += new RoutedEventHandler(this.Buttons_CopyClick); - cancel.Click += new RoutedEventHandler(this.Buttons_CancelClick); + run.Click += this.Buttons_RunClick; + copy.Click += this.Buttons_CopyClick; + cancel.Click += this.Buttons_CancelClick; } /// @@ -1182,8 +1178,8 @@ private void SetupButtonEvents(Button run, Button copy, Button cancel, bool pass /// private void SetupViewModel() { - this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsHelp += new EventHandler(this.CommandNeedsHelp); - this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsImportModule += new EventHandler(this.CommandNeedsImportModule); + this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsHelp += this.CommandNeedsHelp; + this.allModulesViewModel.SelectedCommandInSelectedModuleNeedsImportModule += this.CommandNeedsImportModule; this.window.DataContext = this.allModulesViewModel; } diff --git a/src/Microsoft.Management.UI.Internal/themes/generic.xaml b/src/Microsoft.Management.UI.Internal/themes/generic.xaml index 2a16a1d87cc..36d2354e1af 100644 --- a/src/Microsoft.Management.UI.Internal/themes/generic.xaml +++ b/src/Microsoft.Management.UI.Internal/themes/generic.xaml @@ -1,5 +1,5 @@ diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index 8c516462f73..bd99ef7aff2 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -39,11 +39,9 @@ uint dwFlags [DllImport(LibraryLoadDllName)] private static extern bool FreeLibrary(IntPtr hModule); - [DllImport(LocalizationDllName, EntryPoint = "GetUserDefaultLangID", CallingConvention = CallingConvention.Winapi, SetLastError = true)] private static extern ushort GetUserDefaultLangID(); - public static uint FormatMessageFromModule(uint lastError, string moduleName, out String msg) { Debug.Assert(!string.IsNullOrEmpty(moduleName)); diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs index 5ea3041de9e..00981ad8847 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if CORECLR diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs index 87c629b9396..cbebb9b4557 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs index c2dbb2b2130..3a7af308f29 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSample.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs index acbfc7e9fb3..c1474ec4209 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterSet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs index fc0183466ad..9385e55909f 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 5cd197d1cce..5ab73cf1ec6 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -90,6 +90,7 @@ public string[] Counter @"\memory\cache faults/sec", @"\physicaldisk(_total)\% disk time", @"\physicaldisk(_total)\current disk queue length"}; + private bool _defaultCounters = true; private List _accumulatedCounters = new List(); @@ -117,6 +118,7 @@ public int SampleInterval // MaxSamples parameter // private const Int64 KEEP_ON_SAMPLING = -1; + [Parameter( ParameterSetName = "GetCounterSet", ValueFromPipeline = false, @@ -210,7 +212,6 @@ public string[] ComputerName // protected override void BeginProcessing() { - if (Platform.IsIoT) { // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. @@ -391,10 +392,7 @@ private void ProcessListSetPerMachine(string machine) Dictionary counterInstanceMapping = new Dictionary(); foreach (string counter in counterSetCounters) { - if (!counterInstanceMapping.ContainsKey(counter)) - { - counterInstanceMapping.Add(counter, instanceArray); - } + counterInstanceMapping.TryAdd(counter, instanceArray); } PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 3d7c3b37546..33e127565e6 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -592,7 +592,7 @@ private void ProcessGetProvider() } logQuery.Session = eventLogSession; - logQuery.ReverseDirection = !_oldest; ; + logQuery.ReverseDirection = !_oldest; ReadEvents(logQuery); } @@ -2018,7 +2018,6 @@ private void AddLogsForProviderToInternalMap(EventLogSession eventLogSession, st _providersByLogMap.Add(logLink.LogName.ToLowerInvariant(), provColl); } else - { // // Log is there: add provider, if needed diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs index 5debeaef176..df3835d9e18 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs index fc08bcd96c4..d571df34084 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index 96682ccc1e0..216e9bca7ea 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -27,6 +27,7 @@ public sealed class NewWinEventCommand : PSCmdlet private const string TemplateTag = "template"; private const string DataTag = "data"; + private ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); /// diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index da136e9bf09..40935f6c8e0 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -270,7 +270,7 @@ private struct PDH_TIME_INFO // We access those fields directly. The struct is here for reference only. // [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] - struct PDH_COUNTER_INFO + private struct PDH_COUNTER_INFO { [FieldOffset(0)] public UInt32 dwLength; [FieldOffset(4)] public UInt32 dwType; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs index c77e9f10f5e..39aded7d646 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhSafeHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt index 4605fbe008c..3e0744889e7 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.txt @@ -1,4 +1,4 @@ -#Copyright (c) Microsoft Corporation. All rights reserved. +#Copyright (c) Microsoft Corporation. Vendor=Microsoft Description=This PowerShell snap-in contains Windows Eventing and Performance Counter cmdlets. diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index a7d3354c36e..979225ef3ec 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -47,7 +47,7 @@ - + diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index 470b7b42be4..9ad44f3a07f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -581,8 +581,8 @@ private TSession GetImpliedSession() /// true if successful method invocations should emit downstream the being operated on. public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { - if (objectInstance == null) throw new ArgumentNullException("objectInstance"); - if (methodInvocationInfo == null) throw new ArgumentNullException("methodInvocationInfo"); + if (objectInstance == null) throw new ArgumentNullException(nameof(objectInstance)); + if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { @@ -607,7 +607,7 @@ public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocat /// Method invocation details. public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) { - if (methodInvocationInfo == null) throw new ArgumentNullException("methodInvocationInfo"); + if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { 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 12331bd9cd4..092103d6fe7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -56,7 +56,7 @@ protected CimJobException( { if (info == null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } _errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord)); @@ -71,7 +71,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs index 4690a729e1a..7f76ff98574 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -76,7 +76,7 @@ internal override IObservable GetCimOperation() else { #if DEBUG - Dbg.Assert(_createInstanceOperationGotStarted == true, "GetInstance should be started *after* CreateInstance"); + Dbg.Assert(_createInstanceOperationGotStarted, "GetInstance should be started *after* CreateInstance"); Dbg.Assert(_getInstanceOperationGotStarted == false, "Should not start GetInstance operation twice"); Dbg.Assert(_resultFromGetInstance == null, "GetInstance operation shouldn't happen twice"); _getInstanceOperationGotStarted = true; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs index 6caf4146d20..327fb83affa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs index 440594322f6..bd024b7d76a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 13c75586f31..3a8b0e2200c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs index b1c8873d29f..cd1eb78d81c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs index edb6b2c991a..075e218ea60 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs index 13e0630bf27..f0d07fc201d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs index f5cc8a862e7..f5bdc0745cd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/PropertySettingJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.Management.Infrastructure; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs index d7648ce809a..4297c00616c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -18,6 +18,7 @@ internal class QueryInstancesJob : QueryJobBase { private readonly string _wqlQuery; private readonly bool _useEnumerateInstances; + internal QueryInstancesJob(CimJobContext jobContext, CimQuery cimQuery, string wqlCondition) : base(jobContext, cimQuery) { diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs index c05d9991fda..8ee336de383 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJobBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs index a025ef77d6b..5a25206fe94 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 15c5d5099d1..730e54a6391 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 84c00126238..3743d1965f0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -27,6 +27,7 @@ internal abstract class CimChildJobBase : { private static long s_globalJobNumberCounter; private readonly long _myJobNumber = Interlocked.Increment(ref s_globalJobNumberCounter); + private const string CIMJobType = "CimJob"; internal CimJobContext JobContext @@ -57,6 +58,7 @@ internal CimChildJobBase(CimJobContext jobContext) } private readonly CimSensitiveValueConverter _cimSensitiveValueConverter = new CimSensitiveValueConverter(); + internal CimSensitiveValueConverter CimSensitiveValueConverter { get { return _cimSensitiveValueConverter; } } internal abstract IObservable GetCimOperation(); @@ -161,9 +163,12 @@ public virtual void OnCompleted() private readonly Random _random; private int _sleepAndRetryDelayRangeMs = 1000; private int _sleepAndRetryExtraDelayMs = 0; + private const int MaxRetryDelayMs = 15 * 1000; private const int MinRetryDelayMs = 100; + private Timer _sleepAndRetryTimer; + private void SleepAndRetry_OnWakeup(object state) { this.ExceptionSafeWrapper( @@ -527,7 +532,9 @@ internal CimOperationOptions CreateOperationOptions() } private readonly Lazy _jobSpecificCustomOptions; + internal abstract CimCustomOptionsDictionary CalculateJobSpecificCustomOptions(); + private CimCustomOptionsDictionary GetJobSpecificCustomOptions() { return _jobSpecificCustomOptions.Value; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs index a7fb3465b69..6fa40516322 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -37,7 +37,9 @@ internal CimCmdletDefinitionContext( private readonly IDictionary _privateData; private const string QueryLanguageKey = "QueryDialect"; + private bool? _useEnumerateInstancesInsteadOfWql; + public bool UseEnumerateInstancesInsteadOfWql { get @@ -112,6 +114,7 @@ public bool ClientSideShouldProcess private Uri _resourceUri; private bool _resourceUriHasBeenCalculated; + public Uri ResourceUri { get @@ -140,6 +143,7 @@ public bool SkipTestConnection } private CimOperationFlags? _schemaConformanceLevel; + public CimOperationFlags SchemaConformanceLevel { get 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 f5bb541c012..cfa26ca0e05 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 abcb5d33f6c..033b8813534 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -52,12 +52,12 @@ private unsafe void Copy(char* source, int offset, int charsToCopy) { if ((offset < 0) || (offset >= _string.Length)) { - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException(nameof(offset)); } if (offset + charsToCopy > _string.Length) { - throw new ArgumentOutOfRangeException("charsToCopy"); + throw new ArgumentOutOfRangeException(nameof(charsToCopy)); } fixed (char* target = _string) @@ -352,7 +352,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) /// The only kind of exception this method can throw. internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType) { - if (expectedDotNetType == null) { throw new ArgumentNullException("expectedDotNetType"); } + if (expectedDotNetType == null) { throw new ArgumentNullException(nameof(expectedDotNetType)); } if (cimObject == null) { @@ -459,8 +459,8 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot return exceptionSafeReturn(delegate { int indexOfLastColon = cimIntrinsicValue.LastIndexOf(':'); - int port = int.Parse(cimIntrinsicValue.Substring(indexOfLastColon + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); - IPAddress address = IPAddress.Parse(cimIntrinsicValue.Substring(0, indexOfLastColon)); + int port = int.Parse(cimIntrinsicValue.AsSpan(indexOfLastColon + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); + IPAddress address = IPAddress.Parse(cimIntrinsicValue.AsSpan(0, indexOfLastColon)); return new IPEndPoint(address, port); }); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs index 3603b339594..5dcca85a9b9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 f6eb6b99403..17801923bf0 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 4e10fc94517..551b2149e41 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -316,12 +316,12 @@ public override void AddQueryOption(string optionName, object optionValue) { if (string.IsNullOrEmpty(optionName)) { - throw new ArgumentNullException("optionName"); + throw new ArgumentNullException(nameof(optionName)); } if (optionValue == null) { - throw new ArgumentNullException("optionValue"); + throw new ArgumentNullException(nameof(optionValue)); } this.queryOptions[optionName] = optionValue; 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 ad37e321aa1..a667e6da2f5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -175,7 +175,7 @@ internal override StartableJob CreateQueryJob(CimSession session, QueryBuilder b CimQuery query = baseQuery as CimQuery; if (query == null) { - throw new ArgumentNullException("baseQuery"); + throw new ArgumentNullException(nameof(baseQuery)); } TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: false); @@ -369,6 +369,7 @@ internal override CimSession GetSessionOfOriginFromInstance(CimInstance instance #region Handling of dynamic parameters private RuntimeDefinedParameterDictionary _dynamicParameters; + private const string CimNamespaceParameter = "CimNamespace"; private string GetDynamicNamespace() 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 e27387f9cbe..6b454ad8b7e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -154,6 +154,7 @@ public virtual IEnumerable GetNotFoundErrors_IfThisIsTheOnlyFilte private abstract class CimInstancePropertyBasedFilter : CimInstanceFilterBase { private readonly List _propertyValueFilters = new List(); + protected IEnumerable PropertyValueFilters { get { return _propertyValueFilters; } } protected void AddPropertyValueFilter(PropertyValueFilter propertyValueFilter) @@ -357,6 +358,7 @@ public BehaviorOnNoMatch BehaviorOnNoMatch } protected abstract BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object cimTypedExpectedPropertyValue); + private BehaviorOnNoMatch _behaviorOnNoMatch; public string PropertyName { get; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs index a1e15c0248e..af8efbd6885 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/AddContentCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index f642cfab6f7..559af13127b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -80,7 +80,7 @@ internal static string WqlQueryAll(string from) internal static T GetFirst(CimSession session, string nameSpace, string wmiClassName) where T : class, new() { if (string.IsNullOrEmpty(wmiClassName)) - throw new ArgumentException("String argument may not be null or empty", "wmiClassName"); + throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName)); try { @@ -133,7 +133,7 @@ internal static string WqlQueryAll(string from) internal static T[] GetAll(CimSession session, string nameSpace, string wmiClassName) where T : class, new() { if (string.IsNullOrEmpty(wmiClassName)) - throw new ArgumentException("String argument may not be null or empty", "wmiClassName"); + throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName)); var rv = new List(); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs index 3f1a3f237e2..61726686f28 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs index d203a8facce..75ee9a639e3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearPropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 8460392ff5e..f42e4dae173 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs index 0f978e9eb2d..38a1b5c48a6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -197,6 +197,7 @@ public static void SetRtf(string plainText, string rtfText) private const uint CF_TEXT = 1; private const uint CF_UNICODETEXT = 13; + private static uint s_CF_RTF; private static bool GetTextImpl(out string text) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs index 5ee3ba4ca34..bd97d485cd1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs index 32eeb443848..6f93119c999 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 92302849359..dc545e76daa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -107,7 +107,7 @@ private RestartComputerTimeoutException(SerializationInfo info, StreamingContext { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } ComputerName = info.GetString("ComputerName"); @@ -128,7 +128,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -1123,6 +1123,7 @@ public sealed class StopComputerCommand : PSCmdlet, IDisposable #region Private Members private readonly CancellationTokenSource _cancel = new CancellationTokenSource(); + private const int forcedShutdown = 5; // See https://msdn.microsoft.com/library/aa394058(v=vs.85).aspx #endregion @@ -1875,7 +1876,7 @@ internal static bool IsValidDrive(string drive) { if (logicalDrive.DriveType.Equals(DriveType.Fixed)) { - if (drive.ToString().Equals(logicalDrive.Name.ToString(), System.StringComparison.OrdinalIgnoreCase)) + if (drive.Equals(logicalDrive.Name, System.StringComparison.OrdinalIgnoreCase)) return true; } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index f0254091348..023fc1d0501 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if UNIX @@ -105,7 +105,7 @@ public class CommandLineCmdletBase : PSCmdlet, IDisposable /// public void Dispose() { - _process.Dispose(); + _process?.Dispose(); } #endregion "IDisposable Members" diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index 5dbe8fcc918..2271388c096 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -348,7 +348,7 @@ internal ContentHolder( { if (pathInfo == null) { - throw PSTraceSource.NewArgumentNullException("pathInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(pathInfo)); } PathInfo = pathInfo; @@ -370,7 +370,7 @@ internal void CloseContent(List contentHolders, bool disposing) { if (contentHolders == null) { - throw PSTraceSource.NewArgumentNullException("contentHolders"); + throw PSTraceSource.NewArgumentNullException(nameof(contentHolders)); } foreach (ContentHolder holder in contentHolders) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs index c2798b03f51..fffb36d2979 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs index 13687aad792..06add515e1c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs index b1271dd398d..699676acfd6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CopyPropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs index b0366872ce2..45c484744fa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs index 9caa7cdee15..3dcd0d51c4a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs index 7dda142c2eb..dc272f40281 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 7cfee303084..14f8a207ae5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index f133d4e5db9..86f252fb8fc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs index 761f054be7d..7f6e4c5b1b4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetPropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs index ed99d63861d..484ddb96680 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs index b078262505f..f460b2c4957 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index 6f6855c6068..c0404fa133c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -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 ConnectionOptions(); /// /// Sets connection options. diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs index e6204c619d0..df0c5775ca1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs index 89094d7487d..0fcc8a3a244 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 1c2388782a3..4389f657f69 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -26,7 +26,7 @@ public abstract class CoreCommandBase : PSCmdlet, IDynamicParameters /// using "NavigationCommands" as the category. /// [Dbg.TraceSourceAttribute("NavigationCommands", "The namespace navigation tracer")] - internal static Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); + internal static readonly Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); #endregion Tracer diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs index b2e6673faf1..e3982d49034 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index 77086c8b7e3..5e0711e55fa 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -107,7 +107,7 @@ public string[] LiteralPath /// The qualifier is the drive or provider that is qualifying /// the MSH path. /// - [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = qualifierSet, Mandatory = false)] + [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = qualifierSet)] public SwitchParameter Qualifier { get; set; } /// @@ -476,4 +476,3 @@ private string RemoveQualifier(string path) } } } - diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs index 17c7082b1a9..83ce50d0049 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughContentCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs index 27e33a01564..f2d18660ee5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PassThroughPropertyCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs index 46ce49079fa..29b905cb0ff 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 1ef115c7764..c20ef98a80d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1000,7 +1000,7 @@ protected override void EndProcessing() if (!process.HasExited) { process.EnableRaisingEvents = true; - process.Exited += new EventHandler(myProcess_Exited); + process.Exited += myProcess_Exited; if (!process.HasExited) { System.Threading.Interlocked.Increment(ref _numberOfProcessesToWaitFor); @@ -1896,7 +1896,7 @@ protected override void BeginProcessing() else { // Working Directory not specified -> Assign Current Path. - startInfo.WorkingDirectory = ResolveFilePath(this.SessionState.Path.CurrentFileSystemLocation.Path); + startInfo.WorkingDirectory = PathUtils.ResolveFilePath(this.SessionState.Path.CurrentFileSystemLocation.Path, this, isLiteralPath: true); } if (this.ParameterSetName.Equals("Default")) @@ -2040,7 +2040,7 @@ protected override void BeginProcessing() else if (!process.HasExited) { // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. - process.Exited += new EventHandler(myProcess_Exited); + process.Exited += myProcess_Exited; process.EnableRaisingEvents = true; process.WaitForExit(); } @@ -2348,22 +2348,8 @@ private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) return bytes; } - /// - /// This method will be used on all windows platforms, both full desktop and headless SKUs. - /// - private Process StartWithCreateProcess(ProcessStartInfo startinfo) + private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods.STARTUPINFO lpStartupInfo, ref int creationFlags) { - ProcessNativeMethods.STARTUPINFO lpStartupInfo = new ProcessNativeMethods.STARTUPINFO(); - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new SafeNativeMethods.PROCESS_INFORMATION(); - int error = 0; - GCHandle pinnedEnvironmentBlock = new GCHandle(); - string message = string.Empty; - - // building the cmdline with the file name given and it's arguments - StringBuilder cmdLine = BuildCommandLine(startinfo.FileName, startinfo.Arguments); - - try - { // RedirectionStandardInput if (_redirectstandardinput != null) { @@ -2375,6 +2361,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) { lpStartupInfo.hStdInput = new SafeFileHandle(ProcessNativeMethods.GetStdHandle(-10), false); } + // RedirectionStandardOutput if (_redirectstandardoutput != null) { @@ -2386,6 +2373,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) { lpStartupInfo.hStdOutput = new SafeFileHandle(ProcessNativeMethods.GetStdHandle(-11), false); } + // RedirectionStandardError if (_redirectstandarderror != null) { @@ -2397,11 +2385,10 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) { lpStartupInfo.hStdError = new SafeFileHandle(ProcessNativeMethods.GetStdHandle(-12), false); } + // STARTF_USESTDHANDLES lpStartupInfo.dwFlags = 0x100; - int creationFlags = 0; - if (startinfo.CreateNoWindow) { // No new window: Inherit the parent process's console window @@ -2411,6 +2398,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) { // CREATE_NEW_CONSOLE creationFlags |= 0x00000010; + // STARTF_USESHOWWINDOW lpStartupInfo.dwFlags |= 0x00000001; @@ -2438,15 +2426,41 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) // Create the new process suspended so we have a chance to get a corresponding Process object in case it terminates quickly. creationFlags |= 0x00000004; + } + + /// + /// This method will be used on all windows platforms, both full desktop and headless SKUs. + /// + private Process StartWithCreateProcess(ProcessStartInfo startinfo) + { + ProcessNativeMethods.STARTUPINFO lpStartupInfo = new ProcessNativeMethods.STARTUPINFO(); + SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new SafeNativeMethods.PROCESS_INFORMATION(); + int error = 0; + GCHandle pinnedEnvironmentBlock = new GCHandle(); + IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; + string message = string.Empty; - IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; - var environmentVars = startinfo.EnvironmentVariables; - if (environmentVars != null) + // building the cmdline with the file name given and it's arguments + StringBuilder cmdLine = BuildCommandLine(startinfo.FileName, startinfo.Arguments); + + try + { + int creationFlags = 0; + + SetStartupInfo(startinfo, ref lpStartupInfo, ref creationFlags); + + // We follow the logic: + // - Ignore `UseNewEnvironment` when we run a process as another user. + // Setting initial environment variables makes sense only for current user. + // - Set environment variables if they present in ProcessStartupInfo. + if (!UseNewEnvironment) { - if (this.UseNewEnvironment) + var environmentVars = startinfo.EnvironmentVariables; + if (environmentVars != null) { // All Windows Operating Systems that we support are Windows NT systems, so we use Unicode for environment. creationFlags |= 0x400; + pinnedEnvironmentBlock = GCHandle.Alloc(ConvertEnvVarsToByteArray(environmentVars), GCHandleType.Pinned); AddressOfEnvironmentBlock = pinnedEnvironmentBlock.AddrOfPinnedObject(); } @@ -2456,6 +2470,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) if (_credential != null) { + // Run process as another user. ProcessNativeMethods.LogonFlags logonFlags = 0; if (startinfo.LoadUserProfile) { @@ -2504,6 +2519,22 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) } } + // Run process as current user. + if (UseNewEnvironment) + { + // All Windows Operating Systems that we support are Windows NT systems, so we use Unicode for environment. + creationFlags |= 0x400; + + IntPtr token = WindowsIdentity.GetCurrent().Token; + if (!ProcessNativeMethods.CreateEnvironmentBlock(out AddressOfEnvironmentBlock, token, false)) + { + Win32Exception win32ex = new Win32Exception(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(); flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation); @@ -2531,6 +2562,10 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) { pinnedEnvironmentBlock.Free(); } + else + { + ProcessNativeMethods.DestroyEnvironmentBlock(AddressOfEnvironmentBlock); + } lpStartupInfo.Dispose(); lpProcessInformation.Dispose(); @@ -2665,14 +2700,14 @@ internal struct JOBOBJECT_BASIC_PROCESS_ID_LIST internal static class ProcessNativeMethods { // Fields - internal static UInt32 GENERIC_READ = 0x80000000; - internal static UInt32 GENERIC_WRITE = 0x40000000; - internal static UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; - internal static UInt32 CREATE_ALWAYS = 2; - internal static UInt32 FILE_SHARE_WRITE = 0x00000002; - internal static UInt32 FILE_SHARE_READ = 0x00000001; - internal static UInt32 OF_READWRITE = 0x00000002; - internal static UInt32 OPEN_EXISTING = 3; + internal static readonly UInt32 GENERIC_READ = 0x80000000; + internal static readonly UInt32 GENERIC_WRITE = 0x40000000; + internal static readonly UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; + internal static readonly UInt32 CREATE_ALWAYS = 2; + internal static readonly UInt32 FILE_SHARE_WRITE = 0x00000002; + internal static readonly UInt32 FILE_SHARE_READ = 0x00000001; + internal static readonly UInt32 OF_READWRITE = 0x00000002; + internal static readonly UInt32 OPEN_EXISTING = 3; // Methods @@ -2720,6 +2755,14 @@ public static extern FileNakedHandle CreateFileW( System.IntPtr hTemplateFile ); + [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); + + [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment); + [Flags] internal enum LogonFlags { @@ -2733,6 +2776,7 @@ internal class SECURITY_ATTRIBUTES public int nLength; public SafeLocalMemHandle lpSecurityDescriptor; public bool bInheritHandle; + public SECURITY_ATTRIBUTES() { this.nLength = 12; @@ -2758,6 +2802,7 @@ internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle) [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport(PinvokeDllNames.LocalFreeDllName)] private static extern IntPtr LocalFree(IntPtr hMem); + protected override bool ReleaseHandle() { return (LocalFree(base.handle) == IntPtr.Zero); @@ -2785,6 +2830,7 @@ internal class STARTUPINFO public SafeFileHandle hStdInput; public SafeFileHandle hStdOutput; public SafeFileHandle hStdError; + public STARTUPINFO() { this.lpReserved = IntPtr.Zero; @@ -2962,7 +3008,7 @@ public override void GetObjectData( base.GetObjectData(info, context); if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); info.AddValue("ProcessName", _processName); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs index ceda21a531f..5a73d16e40e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/PropertyCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs index f2f95e0ca43..0a4d9c6cb34 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs index 55893107000..1f02a4fc6d1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemovePropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs index c9fb150b766..cce50ea1563 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs index 9ba19a521e9..3bed667fb0f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RenamePropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index 9879716be4c..8fa26142c5b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs index 63c71991deb..297dd5269a9 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 72473902466..9b5c1450c49 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX // Not built on Unix @@ -144,7 +144,6 @@ internal void SetServiceSecurityDescriptor( StringUtil.Format(ServiceResources.CouldNotSetServiceSecurityDescriptorSddl, service.ServiceName, exception.Message), accessDenied ? ErrorCategory.PermissionDenied : ErrorCategory.InvalidOperation); } - } #endregion Internal } @@ -547,7 +546,7 @@ private void IncludeExcludeAdd( private bool Matches(ServiceController service, string[] matchList) { if (matchList == null) - throw PSTraceSource.NewArgumentNullException("matchList"); + throw PSTraceSource.NewArgumentNullException(nameof(matchList)); string serviceID = (selectionMode == SelectionMode.DisplayName) ? service.DisplayName : service.ServiceName; @@ -1087,17 +1086,9 @@ internal List DoStopService(ServiceController serviceControll /// True if all dependent services are stopped /// False if not all dependent services are stopped /// - private bool HaveAllDependentServicesStopped(ICollection dependentServices) + private bool HaveAllDependentServicesStopped(ServiceController[] dependentServices) { - foreach (ServiceController service in dependentServices) - { - if (service.Status != ServiceControllerStatus.Stopped) - { - return false; - } - } - - return true; + return Array.TrueForAll(dependentServices, service => service.Status == ServiceControllerStatus.Stopped); } /// @@ -1106,14 +1097,10 @@ private bool HaveAllDependentServicesStopped(ICollection depe /// A list of services. internal void RemoveNotStoppedServices(List services) { - foreach (ServiceController service in services) - { - if (service.Status != ServiceControllerStatus.Stopped && - service.Status != ServiceControllerStatus.StopPending) - { - services.Remove(service); - } - } + // You shall not modify a collection during enumeration. + services.RemoveAll(service => + service.Status != ServiceControllerStatus.Stopped && + service.Status != ServiceControllerStatus.StopPending); } /// @@ -2473,7 +2460,7 @@ protected override void ProcessRecord() service, exception, "CouldNotRemoveService", - ServiceResources.CouldNotSetService, + ServiceResources.CouldNotRemoveService, ErrorCategory.PermissionDenied); return; } @@ -2578,7 +2565,7 @@ protected ServiceCommandException(SerializationInfo info, StreamingContext conte { if (info == null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } _serviceName = info.GetString("ServiceName"); @@ -2593,7 +2580,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -2761,7 +2748,6 @@ NakedWin32Handle CreateServiceW( [In] IntPtr lpPassword ); - [DllImport(PinvokeDllNames.SetServiceObjectSecurityDllName, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index 3aed047f443..bcb7330c674 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs index e7e4eb1fa15..4e040517b02 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetContentCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; @@ -28,7 +28,7 @@ internal override void BeforeOpenStreams(string[] paths) { if (paths == null || paths.Length == 0) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(GetCurrentContext()); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs index eb07082d92d..9e2018342ba 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetPropertyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs index 68c8fdfd507..4b2deac8bef 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs index 509c87915df..4f5c239cc64 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index cb2f37a0ef5..a6ff78d8c08 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable @@ -58,6 +58,8 @@ public class TestConnectionCommand : PSCmdlet, IDisposable private static byte[]? s_DefaultSendBuffer; + private readonly CancellationTokenSource _dnsLookupCancel = new CancellationTokenSource(); + private bool _disposed; private Ping? _sender; @@ -275,6 +277,7 @@ protected override void ProcessRecord() protected override void StopProcessing() { _sender?.SendAsyncCancel(); + _dnsLookupCancel.Cancel(); } #region ConnectionTest @@ -283,6 +286,11 @@ private void ProcessConnectionByTCPPort(string targetNameOrAddress) { if (!TryResolveNameOrAddress(targetNameOrAddress, out _, out IPAddress? targetAddress)) { + if (Quiet.IsPresent) + { + WriteObject(false); + } + return; } @@ -334,6 +342,11 @@ private void ProcessTraceroute(string targetNameOrAddress) if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress)) { + if (!Quiet.IsPresent) + { + WriteObject(false); + } + return; } @@ -471,6 +484,11 @@ private void ProcessMTUSize(string targetNameOrAddress) PingReply? reply, replyResult = null; if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress)) { + if (Quiet.IsPresent) + { + WriteObject(-1); + } + return; } @@ -574,6 +592,11 @@ private void ProcessPing(string targetNameOrAddress) { if (!TryResolveNameOrAddress(targetNameOrAddress, out string resolvedTargetName, out IPAddress? targetAddress)) { + if (Quiet.IsPresent) + { + WriteObject(false); + } + return; } @@ -667,7 +690,7 @@ private bool TryResolveNameOrAddress( if (ResolveDestination) { - hostEntry = Dns.GetHostEntry(targetNameOrAddress); + hostEntry = GetCancellableHostEntry(targetNameOrAddress); resolvedTargetName = hostEntry.HostName; } else @@ -679,27 +702,35 @@ private bool TryResolveNameOrAddress( { try { - hostEntry = Dns.GetHostEntry(targetNameOrAddress); + hostEntry = GetCancellableHostEntry(targetNameOrAddress); if (ResolveDestination) { resolvedTargetName = hostEntry.HostName; - hostEntry = Dns.GetHostEntry(hostEntry.HostName); + hostEntry = GetCancellableHostEntry(hostEntry.HostName); } } + catch (PipelineStoppedException) + { + throw; + } catch (Exception ex) { - string message = StringUtil.Format( - TestConnectionResources.NoPingResult, - resolvedTargetName, - TestConnectionResources.CannotResolveTargetName); - Exception pingException = new PingException(message, ex); - ErrorRecord errorRecord = new ErrorRecord( - pingException, - TestConnectionExceptionId, - ErrorCategory.ResourceUnavailable, - resolvedTargetName); - WriteError(errorRecord); + if (!Quiet.IsPresent) + { + string message = StringUtil.Format( + TestConnectionResources.NoPingResult, + resolvedTargetName, + TestConnectionResources.CannotResolveTargetName); + Exception pingException = new PingException(message, ex); + ErrorRecord errorRecord = new ErrorRecord( + pingException, + TestConnectionExceptionId, + ErrorCategory.ResourceUnavailable, + resolvedTargetName); + WriteError(errorRecord); + } + return false; } @@ -732,6 +763,20 @@ private bool TryResolveNameOrAddress( return true; } + private IPHostEntry GetCancellableHostEntry(string targetNameOrAddress) + { + var task = Dns.GetHostEntryAsync(targetNameOrAddress); + var waitHandles = new[] { ((IAsyncResult)task).AsyncWaitHandle, _dnsLookupCancel.Token.WaitHandle }; + + // WaitAny() returns the index of the first signal it gets; 1 is our cancellation token. + if (WaitHandle.WaitAny(waitHandles) == 1) + { + throw new PipelineStoppedException(); + } + + return task.GetAwaiter().GetResult(); + } + private IPAddress? GetHostAddress(IPHostEntry hostEntry) { AddressFamily addressFamily = IPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs index 250bccaddf6..106c9038981 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs index 6b734d0ec4f..056cf60265b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs index a90a8971e06..eed6efff76a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs index 929dcf6f6e1..547b121c571 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index 68560bef20f..7ccf63cdf8e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx index 0c1151be6b7..65513e55f5f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx @@ -175,7 +175,7 @@ This command stopped operation because process "{0} ({1})" is not stopped in the specified time-out. - This command cannot be run due to the error: {0}. + This command cannot be run due to the error: {0} This command cannot be run because the input "{0}" is not a valid Application. Give a valid application and run your command again. diff --git a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs index abd768a782b..0b0239053ea 100644 --- a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; 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 0d2f77b8523..d5477d109b4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -31,10 +31,10 @@ - - - - + + + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index eb6ea6fc99e..2ea6d6e20ae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -21,6 +21,7 @@ namespace Microsoft.PowerShell.Commands public class AddMemberCommand : PSCmdlet { private static readonly object s_notSpecified = new object(); + private static bool HasBeenSpecified(object obj) { return !System.Object.ReferenceEquals(obj, s_notSpecified); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index 714a852383a..4f7185a7e85 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -577,7 +577,6 @@ protected override void EndProcessing() return; } - if (_loadAssembly) { // File extension is ".DLL" (ParameterSetName = FromPathParameterSetName or FromLiteralPathParameterSetName). @@ -634,7 +633,9 @@ protected override void EndProcessing() private static readonly Dictionary s_sourceAssemblyCache = new Dictionary(); private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; + private const ReportDiagnostic defaultDiagnosticOption = ReportDiagnostic.Error; + private static readonly string[] s_writeInformationTags = new string[] { "PSHOST" }; private int _syntaxTreesHash; @@ -650,11 +651,7 @@ private void LoadAssemblies(IEnumerable assemblies) { // CoreCLR doesn't allow re-load TPA assemblies with different API (i.e. we load them by name and now want to load by path). // LoadAssemblyHelper helps us avoid re-loading them, if they already loaded. - Assembly assembly = LoadAssemblyHelper(assemblyName); - if (assembly == null) - { - assembly = Assembly.LoadFrom(ResolveAssemblyName(assemblyName, false)); - } + Assembly assembly = LoadAssemblyHelper(assemblyName) ?? Assembly.LoadFrom(ResolveAssemblyName(assemblyName, false)); if (PassThru) { @@ -668,14 +665,25 @@ private void LoadAssemblies(IEnumerable assemblies) /// private static IEnumerable InitDefaultRefAssemblies() { - // netcoreapp3.0 currently comes with 148 reference assemblies (maybe more in future), so we use a capacity of '150'. - var defaultRefAssemblies = new List(150); + // Define number of reference assemblies distributed with PowerShell. + const int maxPowershellRefAssemblies = 160; + + const int capacity = maxPowershellRefAssemblies + 1; + var defaultRefAssemblies = new List(capacity); foreach (string file in Directory.EnumerateFiles(s_netcoreAppRefFolder, "*.dll", SearchOption.TopDirectoryOnly)) { defaultRefAssemblies.Add(MetadataReference.CreateFromFile(file)); } + + // Add System.Management.Automation.dll defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location)); + + // We want to avoid reallocating the internal array, so we assert if the list capacity has increased. + Diagnostics.Assert( + defaultRefAssemblies.Capacity <= capacity, + $"defaultRefAssemblies was resized because of insufficient initial capacity! A capacity of {defaultRefAssemblies.Count} is required."); + return defaultRefAssemblies; } @@ -887,7 +895,7 @@ private OutputKind OutputAssemblyTypeToOutputKind(OutputAssemblyType outputType) case OutputAssemblyType.WindowsApplication: return OutputKind.WindowsApplication; default: - throw new ArgumentOutOfRangeException("outputType"); + throw new ArgumentOutOfRangeException(nameof(outputType)); } } 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 524af9fdb3f..5a1b944792d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -99,10 +99,13 @@ public SwitchParameter PassThru #region Internal private List _referenceEntries; + private readonly List _referenceEntryBacklog = new List(); + private readonly List _differenceEntryBacklog = new List(); + private OrderByProperty _orderByProperty = null; private OrderByPropertyComparer _comparer = null; @@ -372,18 +375,13 @@ private void Emit(OrderByPropertyEntry entry, string sideIndicator) #region Overrides /// - /// If the parameter 'ExcludeDifferent' is present, then we need to turn on the - /// 'IncludeEqual' switch unless it's turned off by the user specifically. + /// If the parameter 'ExcludeDifferent' is present, then the 'IncludeEqual' + /// switch is turned on unless it's turned off by the user specifically. /// protected override void BeginProcessing() { if (ExcludeDifferent) { - if (_isIncludeEqualSpecified == false) - { - return; - } - if (_isIncludeEqualSpecified && !_includeEqual) { return; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs index f0b24be51ed..250b00422d6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConsoleColorCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 341b16289c9..1e64dfe7754 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX 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 12491fbd077..2daa22a4f69 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs index 5df1b594391..dfa6bd6c4b0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFromMarkdownCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -58,6 +58,7 @@ public class ConvertFromMarkdownCommand : PSCmdlet private const string PathParameterSet = "PathParamSet"; private const string LiteralPathParameterSet = "LiteralParamSet"; private const string InputObjParamSet = "InputObjParamSet"; + private MarkdownConversionType _conversionType = MarkdownConversionType.HTML; private PSMarkdownOptionInfo _mdOption = null; 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 d8de66a7461..b0c3ff27f35 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs index aba6043d2bb..3bb626ca06e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Csv.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index 2503d925934..0372298d7b5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -853,9 +853,9 @@ protected override void ProcessRecord() internal class ExportCsvHelper : IDisposable { private char _delimiter; - readonly private BaseCsvWritingCommand.QuoteKind _quoteKind; - readonly private HashSet _quoteFields; - readonly private StringBuilder _outputString; + private readonly BaseCsvWritingCommand.QuoteKind _quoteKind; + private readonly HashSet _quoteFields; + private readonly StringBuilder _outputString; /// /// Create ExportCsvHelper instance. @@ -1013,7 +1013,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN AppendStringWithEscapeAlways(_outputString, value); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (value.Contains(_delimiter)) + if (value != null && value.Contains(_delimiter)) { AppendStringWithEscapeAlways(_outputString, value); } @@ -1738,7 +1738,7 @@ internal static char SetDelimiter(PSCmdlet cmdlet, string parameterSetName, char case "UseCulture": case "CulturePath": case "CultureLiteralPath": - if (useCulture == true) + if (useCulture) { // ListSeparator is apparently always a character even though the property returns a string, checked via: // [CultureInfo]::GetCultures("AllCultures") | % { ([CultureInfo]($_.Name)).TextInfo.ListSeparator } | ? Length -ne 1 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 16f30042200..465ef91f037 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -55,12 +55,12 @@ internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth { if (writer == null) { - throw PSTraceSource.NewArgumentException("writer"); + throw PSTraceSource.NewArgumentException(nameof(writer)); } if (depth < 1) { - throw PSTraceSource.NewArgumentException("writer", Serialization.DepthOfOneRequired); + throw PSTraceSource.NewArgumentException(nameof(writer), Serialization.DepthOfOneRequired); } _depth = depth; @@ -648,7 +648,7 @@ private void WriteStartOfPSObject( if (property != null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); - WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property.ToString()); + WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property); } else { @@ -1063,9 +1063,9 @@ private void WritePropertyWithNullValue( XmlWriter writer, PSPropertyInfo source, int depth) { WriteStartElement(writer, CustomSerializationStrings.Properties); - WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name.ToString()); + WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name); if (!_notypeinformation) - WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue.ToString()); + WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue); writer.WriteEndElement(); } @@ -1075,7 +1075,7 @@ private void WriteObjectString( if (property != null) { WriteStartElement(writer, CustomSerializationStrings.Properties); - WriteAttribute(writer, CustomSerializationStrings.NameAttribute, property.ToString()); + WriteAttribute(writer, CustomSerializationStrings.NameAttribute, property); } else { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs index 59ec5432add..ff4b2580f83 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerializationStrings.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index 122fd33ad71..355d94912af 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs index 9e17910a561..c54c9499761 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Disable-PSBreakpoint.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs index c47f09b28e7..d06073c4214 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Enable-PSBreakpoint.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index 433db02826b..c1294a08535 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -75,7 +75,7 @@ public int RunspaceId /// Runspace local Id. public PSRunspaceDebug(bool enabled, bool breakAll, string runspaceName, int runspaceId) { - if (string.IsNullOrEmpty(runspaceName)) { throw new PSArgumentNullException("runspaceName"); } + if (string.IsNullOrEmpty(runspaceName)) { throw new PSArgumentNullException(nameof(runspaceName)); } this.Enabled = enabled; this.BreakAll = breakAll; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index 31d79d2d748..1ac3e781ab7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs index 9536f3d399a..0d2db93302a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 113ba0ffabb..a9d60def958 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,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 32a61eb1f36..d7d863e29b8 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 5caeaf5758b..48a9004e604 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 37bca37c3a2..b95e9968c5c 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -43,6 +43,7 @@ public class OutGridViewCommand : PSCmdlet, IDisposable private const string DataNotQualifiedForGridView = "DataNotQualifiedForGridView"; private const string RemotingNotSupported = "RemotingNotSupported"; + private TypeInfoDataBase _typeInfoDataBase; private PSPropertyExpressionFactory _expressionFactory; private OutWindowProxy _windowProxy; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index cefb5540e87..55158034368 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -20,6 +20,7 @@ internal class OutWindowProxy : IDisposable internal const string OriginalObjectPropertyName = "OutGridViewOriginalObject"; private const string ToStringValuePropertyName = "ToStringValue"; private const string IndexPropertyName = "IndexValue"; + private int _index; /// Columns definition of the underlying Management List @@ -59,17 +60,17 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t { if (propertyNames == null) { - throw new ArgumentNullException("propertyNames"); + throw new ArgumentNullException(nameof(propertyNames)); } if (displayNames == null) { - throw new ArgumentNullException("displayNames"); + throw new ArgumentNullException(nameof(displayNames)); } if (types == null) { - throw new ArgumentNullException("types"); + throw new ArgumentNullException(nameof(types)); } try @@ -178,7 +179,7 @@ internal void AddItem(PSObject livePSObject) { if (livePSObject == null) { - throw new ArgumentNullException("livePSObject"); + throw new ArgumentNullException(nameof(livePSObject)); } if (_headerInfo == null) @@ -204,7 +205,7 @@ internal void AddHeteroViewItem(PSObject livePSObject) { if (livePSObject == null) { - throw new ArgumentNullException("livePSObject"); + throw new ArgumentNullException(nameof(livePSObject)); } if (_headerInfo == null) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs index 75adcd3cf42..b72c9b7d439 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 7dfda541d77..dc967889e69 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index 2324b8e5e05..70967aa897b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Management.Automation; +using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using Microsoft.PowerShell.Commands.Internal.Format; @@ -97,9 +98,28 @@ private static Dictionary> GetTypeGroupMap(IEnumerable protected override void ProcessRecord() { - bool writeOldWay = PowerShellVersion == null || - PowerShellVersion.Major < 5 || - (PowerShellVersion.Major == 5 && PowerShellVersion.Minor < 1); + // Remoting detection: + // * Automatic variable $PSSenderInfo is defined in true remoting contexts as well as in background jobs. + // * $PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion contains the client version, as a [version] instance. + // Note: Even though $PSVersionTable.PSVersion is of type [semver] in PowerShell 6+, it is of type [version] here, + // presumably because only the latter type deserializes type-faithfully. + var clientVersion = PowerShellVersion; + PSSenderInfo remotingClientInfo = GetVariableValue("PSSenderInfo") as PSSenderInfo; + if (clientVersion == null && remotingClientInfo != null) + { + clientVersion = PSObject.Base((PSObject.Base(remotingClientInfo.ApplicationArguments["PSVersionTable"]) as PSPrimitiveDictionary)?["PSVersion"]) as Version; + } + + // During remoting, remain compatible with v5.0- clients by default. + // Passing a -PowerShellVersion argument allows overriding the client version. + bool writeOldWay = + (remotingClientInfo != null && clientVersion == null) // To be safe: Remoting client version could unexpectedly not be determined. + || + (clientVersion != null + && + (clientVersion.Major < 5 + || + (clientVersion.Major == 5 && clientVersion.Minor < 1))); TypeInfoDataBase db = this.Context.FormatDBManager.Database; 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 6d64902e6ff..919264ad180 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,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 09df27f2a92..a0225c8ea6a 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -280,6 +280,7 @@ private void ProcessString(string originalString) } private static readonly Random _idGenerator = new Random(); + private static string GetGroupLabel(Type inputType) => string.Format("{0} ({1}) <{2:X8}>", inputType.Name, inputType.FullName, _idGenerator.Next()); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs index a6d68b89ca8..202250f33a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; 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 a7cc58e38a8..813bfad23c0 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs index dcd256d4962..6939c38643d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. 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 a0c12236e96..5927244d896 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,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 3efd88dbb31..642139c07d9 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,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 5bf7ad6489b..67c173b2077 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; 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 312734c043e..5616a7fa436 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 541912598b7..5dcb3c4f588 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,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 428a2da36c2..7c2fdbe0c14 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.Commands /// Class for Get-Error implementation. /// [Cmdlet(VerbsCommon.Get, "Error", - HelpUri = "https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/get-error?view=powershell-7&WT.mc_id=ps-gethelp", + HelpUri = "https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/get-error", DefaultParameterSetName = NewestParameterSetName)] [OutputType("System.Management.Automation.ErrorRecord#PSExtendedError", "System.Exception#PSExtendedError")] public sealed class GetErrorCommand : PSCmdlet 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 f04f66d4884..ba57278f6c8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs index 9b451f4983f..4d2d0517569 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSCallStack.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs index 3ce9fcb9d8c..49baa9bd296 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs index 81ba7c535d7..82a725ba212 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetCultureCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index 59b57d6bec3..4516568cc34 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -40,6 +40,12 @@ public DateTime Date } } + /// + /// Gets or sets whether to treat a numeric input as ticks, or unix time. + /// + [Parameter] + public SwitchParameter FromUnixTime; + private DateTime _date; private bool _dateSpecified; @@ -237,7 +243,14 @@ protected override void ProcessRecord() // use passed date object if specified if (_dateSpecified) { - dateToUse = Date; + if (FromUnixTime.IsPresent) + { + dateToUse = DateTimeOffset.FromUnixTimeSeconds(Date.Ticks).UtcDateTime; + } + else + { + dateToUse = Date; + } } // use passed year if specified diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs index d6ae515ad56..faf16d384f7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs index c5f25e742d7..cde73b2914d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs index 78017d46db2..65e55a86ab1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -126,40 +126,10 @@ protected override void ProcessRecord() foreach (string path in pathsToProcess) { - byte[] bytehash = null; - string hash = null; - Stream openfilestream = null; - - try + if (ComputeFileHash(path, out string hash)) { - openfilestream = File.OpenRead(path); - bytehash = hasher.ComputeHash(openfilestream); - - hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); WriteHashResult(Algorithm, hash, path); } - catch (FileNotFoundException ex) - { - var errorRecord = new ErrorRecord( - ex, - "FileNotFound", - ErrorCategory.ObjectNotFound, - path); - WriteError(errorRecord); - } - catch (UnauthorizedAccessException ex) - { - var errorRecord = new ErrorRecord( - ex, - "UnauthorizedAccessError", - ErrorCategory.InvalidData, - path); - WriteError(errorRecord); - } - finally - { - openfilestream?.Dispose(); - } } } @@ -181,6 +151,61 @@ protected override void EndProcessing() } } + /// + /// Read the file and calculate the hash. + /// + /// Path to file which will be hashed. + /// Will contain the hash of the file content. + /// Boolean value indicating whether the hash calculation succeeded or failed. + private bool ComputeFileHash(string path, out string hash) + { + byte[] bytehash = null; + Stream openfilestream = null; + + hash = null; + + try + { + openfilestream = File.OpenRead(path); + + bytehash = hasher.ComputeHash(openfilestream); + hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); + } + catch (FileNotFoundException ex) + { + var errorRecord = new ErrorRecord( + ex, + "FileNotFound", + ErrorCategory.ObjectNotFound, + path); + WriteError(errorRecord); + } + catch (UnauthorizedAccessException ex) + { + var errorRecord = new ErrorRecord( + ex, + "UnauthorizedAccessError", + ErrorCategory.InvalidData, + path); + WriteError(errorRecord); + } + catch (IOException ioException) + { + var errorRecord = new ErrorRecord( + ioException, + "FileReadError", + ErrorCategory.ReadError, + path); + WriteError(errorRecord); + } + finally + { + openfilestream?.Dispose(); + } + + return hash != null; + } + /// /// Create FileHashInfo object and output it. /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs index b2ffebcd164..76718bfde3f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHostCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index 4831200555f..daa870d9b1a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index 6fa3993ea47..01cf6534c48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -28,6 +28,8 @@ public class GetRandomCommand : PSCmdlet private const string RandomNumberParameterSet = "RandomNumberParameterSet"; private const string RandomListItemParameterSet = "RandomListItemParameterSet"; + private const string ShuffleParameterSet = "ShuffleParameterSet"; + private static readonly object[] _nullInArray = new object[] { null }; private enum MyParameterSet @@ -50,7 +52,8 @@ private MyParameterSet EffectiveParameterSet { _effectiveParameterSet = MyParameterSet.RandomListItem; } - else if (ParameterSetName.Equals(GetRandomCommand.RandomListItemParameterSet, StringComparison.OrdinalIgnoreCase)) + else if (ParameterSetName == GetRandomCommand.RandomListItemParameterSet + || ParameterSetName == GetRandomCommand.ShuffleParameterSet) { _effectiveParameterSet = MyParameterSet.RandomListItem; } @@ -276,6 +279,7 @@ private double ConvertToDouble(object o, double defaultIfNull) /// List from which random elements are chosen. /// [Parameter(ParameterSetName = RandomListItemParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] + [Parameter(ParameterSetName = ShuffleParameterSet, ValueFromPipeline = true, Position = 0, Mandatory = true)] [System.Management.Automation.AllowNull] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] InputObject { get; set; } @@ -283,12 +287,23 @@ private double ConvertToDouble(object o, double defaultIfNull) /// /// Number of items to output (number of list items or of numbers). /// - [Parameter] + [Parameter(ParameterSetName = RandomNumberParameterSet)] + [Parameter(ParameterSetName = RandomListItemParameterSet)] [ValidateRange(1, int.MaxValue)] public int Count { get; set; } = 1; #endregion + #region Shuffle parameter + + /// + /// Gets or sets whether the command should return all input objects in randomized order. + /// + [Parameter(ParameterSetName = ShuffleParameterSet, Mandatory = true)] + public SwitchParameter Shuffle { get; set; } + + #endregion + #region Cmdlet processing methods private double GetRandomDouble(double minValue, double maxValue) @@ -492,29 +507,39 @@ protected override void ProcessRecord() { if (EffectiveParameterSet == MyParameterSet.RandomListItem) { - // this allows for $null to be in an array passed to InputObject - foreach (object item in InputObject ?? _nullInArray) + if (ParameterSetName == ShuffleParameterSet) { - // (3) - if (_numberOfProcessedListItems < Count) + // this allows for $null to be in an array passed to InputObject + foreach (object item in InputObject ?? _nullInArray) { - Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems"); _chosenListItems.Add(item); } - else + } + else + { + foreach (object item in InputObject ?? _nullInArray) { - Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K"); - - // (1) - if (Generator.Next(_numberOfProcessedListItems + 1) < Count) + // (3) + if (_numberOfProcessedListItems < Count) { - // (2) - int indexToReplace = Generator.Next(_chosenListItems.Count); - _chosenListItems[indexToReplace] = item; + Debug.Assert(_chosenListItems.Count == _numberOfProcessedListItems, "Initial K elements should all be included in chosenListItems"); + _chosenListItems.Add(item); + } + else + { + Debug.Assert(_chosenListItems.Count == Count, "After processing K initial elements, the length of chosenItems should stay equal to K"); + + // (1) + if (Generator.Next(_numberOfProcessedListItems + 1) < Count) + { + // (2) + int indexToReplace = Generator.Next(_chosenListItems.Count); + _chosenListItems[indexToReplace] = item; + } } - } - _numberOfProcessedListItems++; + _numberOfProcessedListItems++; + } } } } @@ -620,7 +645,7 @@ internal int Next(int maxValue) { if (maxValue < 0) { - throw new ArgumentOutOfRangeException("maxValue", GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi); + throw new ArgumentOutOfRangeException(nameof(maxValue), GetRandomCommandStrings.MaxMustBeGreaterThanZeroApi); } return Next(0, maxValue); @@ -636,7 +661,7 @@ public int Next(int minValue, int maxValue) { if (minValue > maxValue) { - throw new ArgumentOutOfRangeException("minValue", GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); + throw new ArgumentOutOfRangeException(nameof(minValue), GetRandomCommandStrings.MinGreaterThanOrEqualMaxApi); } int randomNumber = 0; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs index 4d6cdeb3244..0aedd4c9d06 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRunspaceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs index 5b50efd978d..53e8c5d3adf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUICultureCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs index b2a45626b27..9dc133caced 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs index 0527ed8fce8..e8dcfbe254a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs index 4f00c11d6ee..766b38116c0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 bb3f9a0bf3e..9938dc15c7f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index 06a5459ad58..58d9d762ab7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -20,7 +20,6 @@ using Dbg = System.Management.Automation.Diagnostics; - namespace Microsoft.PowerShell.Commands { using PowerShell = System.Management.Automation.PowerShell; @@ -187,7 +186,7 @@ private void RegisterModuleCleanUp(PSModuleInfo moduleInfo) { if (moduleInfo == null) { - throw PSTraceSource.NewArgumentNullException("moduleInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(moduleInfo)); } // Note: we are using this.Context.Events to make sure that the event handler @@ -534,7 +533,7 @@ internal ErrorDetails GetErrorDetails(string errorId, params object[] args) { if (string.IsNullOrEmpty(errorId)) { - throw PSTraceSource.NewArgumentNullException("errorId"); + throw PSTraceSource.NewArgumentNullException(nameof(errorId)); } return new ErrorDetails( @@ -564,7 +563,7 @@ private ErrorRecord GetErrorMalformedDataFromRemoteCommand(string commandName) { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } string errorId = "ErrorMalformedDataFromRemoteCommand"; @@ -585,7 +584,7 @@ private ErrorRecord GetErrorCommandSkippedBecauseOfShadowing(string commandNames { if (string.IsNullOrEmpty(commandNames)) { - throw PSTraceSource.NewArgumentNullException("commandNames"); + throw PSTraceSource.NewArgumentNullException(nameof(commandNames)); } string errorId = "ErrorCommandSkippedBecauseOfShadowing"; @@ -606,7 +605,7 @@ private ErrorRecord GetErrorSkippedNonRequestedCommand(string commandName) { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } string errorId = "ErrorSkippedNonRequestedCommand"; @@ -627,7 +626,7 @@ private ErrorRecord GetErrorSkippedNonRequestedTypeDefinition(string typeName) { if (string.IsNullOrEmpty(typeName)) { - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } string errorId = "ErrorSkippedNonRequestedTypeDefinition"; @@ -648,7 +647,7 @@ private ErrorRecord GetErrorSkippedUnsafeCommandName(string commandName) { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } string errorId = "ErrorSkippedUnsafeCommandName"; @@ -669,18 +668,18 @@ private ErrorRecord GetErrorSkippedUnsafeNameInMetadata(string commandName, stri { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } if (string.IsNullOrEmpty(nameType)) { - throw PSTraceSource.NewArgumentNullException("nameType"); + throw PSTraceSource.NewArgumentNullException(nameof(nameType)); } Dbg.Assert(nameType.Equals("Alias") || nameType.Equals("ParameterSet") || nameType.Equals("Parameter"), "nameType matches resource names"); if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } string errorId = "ErrorSkippedUnsafe" + nameType + "Name"; @@ -701,12 +700,12 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } if (runtimeException == null) { - throw PSTraceSource.NewArgumentNullException("runtimeException"); + throw PSTraceSource.NewArgumentNullException(nameof(runtimeException)); } string errorId; @@ -755,7 +754,7 @@ private ErrorRecord GetErrorCouldntResolvedAlias(string aliasName) { if (string.IsNullOrEmpty(aliasName)) { - throw PSTraceSource.NewArgumentNullException("aliasName"); + throw PSTraceSource.NewArgumentNullException(nameof(aliasName)); } string errorId = "ErrorCouldntResolveAlias"; @@ -776,7 +775,7 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } string errorId = "ErrorNoResultsFromRemoteEnd"; @@ -794,12 +793,13 @@ private ErrorRecord GetErrorNoResultsFromRemoteEnd(string commandName) } private List _commandsSkippedBecauseOfShadowing = new List(); + private void ReportSkippedCommands() { if (_commandsSkippedBecauseOfShadowing.Count != 0) { string skippedCommands = string.Join(", ", _commandsSkippedBecauseOfShadowing.ToArray()); - ErrorRecord errorRecord = this.GetErrorCommandSkippedBecauseOfShadowing(skippedCommands.ToString()); + ErrorRecord errorRecord = this.GetErrorCommandSkippedBecauseOfShadowing(skippedCommands); this.WriteWarning(errorRecord.ErrorDetails.Message); } } @@ -825,6 +825,7 @@ private bool IsCommandNameMatchingParameters(string commandName) } private Dictionary _existingCommands; + private Dictionary ExistingCommands { get @@ -872,7 +873,7 @@ private bool IsCommandNameAllowedForImport(string commandName) { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentNullException("commandName"); + throw PSTraceSource.NewArgumentNullException(nameof(commandName)); } if (this.AllowClobber.IsPresent) @@ -1270,7 +1271,7 @@ private ParameterMetadata RehydrateParameterMetadata(PSObject deserializedParame { if (deserializedParameterMetadata == null) { - throw PSTraceSource.NewArgumentNullException("deserializedParameterMetadata"); + throw PSTraceSource.NewArgumentNullException(nameof(deserializedParameterMetadata)); } string name = GetPropertyValue("Get-Command", deserializedParameterMetadata, "Name"); @@ -1311,7 +1312,7 @@ private CommandMetadata RehydrateCommandMetadata(PSObject deserializedCommandInf { if (deserializedCommandInfo == null) { - throw PSTraceSource.NewArgumentNullException("deserializedCommandInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(deserializedCommandInfo)); } string name = GetPropertyValue("Get-Command", deserializedCommandInfo, "Name"); @@ -1964,7 +1965,7 @@ private string EscapeFunctionNameForRemoteHelp(string name) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } StringBuilder result = new StringBuilder(name.Length); @@ -2014,7 +2015,7 @@ private void GenerateManifest(TextWriter writer, string psm1fileName, string for { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } GenerateTopComment(writer); @@ -2087,7 +2088,7 @@ private void GenerateModuleHeader(TextWriter writer) { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } // In Win8, we are no longer loading all assemblies by default. @@ -2119,11 +2120,12 @@ function Write-PSImplicitRemotingMessage try { & $script:WriteHost -Object $message -ErrorAction SilentlyContinue } catch { } } "; + private void GenerateHelperFunctionsWriteMessage(TextWriter writer) { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } writer.Write(HelperFunctionsWriteMessage); @@ -2173,11 +2175,12 @@ function Set-PSImplicitRemotingSession if ($PSSessionOverride) {{ Set-PSImplicitRemotingSession $PSSessionOverride }} "; + private void GenerateHelperFunctionsSetImplicitRunspace(TextWriter writer) { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } string runspaceNameTemplate = StringUtil.Format(ImplicitRemotingStrings.ProxyRunspaceNameTemplate); @@ -2204,11 +2207,12 @@ function Get-PSImplicitRemotingSessionOption }} }} "; + private void GenerateHelperFunctionsGetSessionOption(TextWriter writer) { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } writer.Write( @@ -2403,7 +2407,7 @@ private void GenerateHelperFunctionsGetImplicitRunspace(TextWriter writer) { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } string hashString; @@ -2434,6 +2438,7 @@ private void GenerateHelperFunctionsGetImplicitRunspace(TextWriter writer) }} -ErrorAction SilentlyContinue }} catch {{ }} "; + private string GenerateReimportingOfModules() { StringBuilder result = new StringBuilder(); @@ -2543,6 +2548,7 @@ private string GenerateNewRunspaceExpression() private const string ComputerNameParameterTemplate = @"-ComputerName '{0}' ` -ApplicationName '{1}' {2} {3} "; + private const string VMIdParameterTemplate = @"-VMId '{0}' "; private const string ContainerIdParameterTemplate = @"-ContainerId '{0}' "; @@ -2748,11 +2754,12 @@ function Get-PSImplicitRemotingClientSideParameters return $clientSideParameters } "; + private void GenerateHelperFunctionsClientSideParameters(TextWriter writer) { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } writer.Write(HelperFunctionsModifyParameters); @@ -2831,7 +2838,7 @@ private void GenerateCommandProxy(TextWriter writer, CommandMetadata commandMeta { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } string functionNameForString = CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name); @@ -2853,12 +2860,12 @@ private void GenerateCommandProxy(TextWriter writer, IEnumerable GetListOfCommandNames(IEnumerable listOfCo { if (listOfCommandMetadata == null) { - throw PSTraceSource.NewArgumentNullException("listOfCommandMetadata"); + throw PSTraceSource.NewArgumentNullException(nameof(listOfCommandMetadata)); } List listOfCommandNames = new List(); @@ -2915,7 +2922,7 @@ private string GenerateArrayString(IEnumerable listOfStrings) { if (listOfStrings == null) { - throw PSTraceSource.NewArgumentNullException("listOfStrings"); + throw PSTraceSource.NewArgumentNullException(nameof(listOfStrings)); } StringBuilder arrayString = new StringBuilder(); @@ -2976,12 +2983,12 @@ private void GenerateFormatFile(TextWriter writer, List { if (writer == null) { - throw PSTraceSource.NewArgumentNullException("writer"); + throw PSTraceSource.NewArgumentNullException(nameof(writer)); } if (listOfFormatData == null) { - throw PSTraceSource.NewArgumentNullException("listOfFormatData"); + throw PSTraceSource.NewArgumentNullException(nameof(listOfFormatData)); } XmlWriterSettings settings = new XmlWriterSettings(); 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 1f64879df51..4749d28322c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index f2db97cdd51..3da62e88d25 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -225,6 +225,7 @@ protected override void ProcessRecord() } private Dictionary _existingCommands; + private Dictionary ExistingCommands { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 1edac551584..694e82686be 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs index a4abba2dbd5..d51f20f8704 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 c1971c3da11..652e32652ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -22,6 +22,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 CultureInfo _cultureInfo = CultureInfo.InvariantCulture; private string _separator; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs index 61953205445..0ee80712123 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MarkdownOptionCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -272,6 +272,7 @@ protected override void EndProcessing() internal static class PSMarkdownOptionInfoCache { private static ConcurrentDictionary markdownOptionInfoCache; + private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; static PSMarkdownOptionInfoCache() diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 43db8154484..3a5d4c77a5f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 c668e41b98d..2ef311e38f3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 9596df44e79..c19c85d0a86 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -168,7 +168,7 @@ protected override void BeginProcessing() targetObject: null)); } - throw e; + throw; } Diagnostics.Assert(type != null, "LanguagePrimitives.TryConvertTo failed but returned true"); @@ -465,7 +465,7 @@ private object CreateComObject() thread.Join(); - if (createInfo.success == true) + if (createInfo.success) { return createInfo.objectCreated; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs index cbf09d0087e..3c95ebbc7de 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewAliasCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs index 198d2c31048..34c95a116f3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs index badbaa21b4d..537d86c24ec 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs index f7a5bd63afc..f8bb3d4e6ea 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTemporaryFileCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs index b75932b869d..0e633ca5b2e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index 24a7ce46ca2..fd69a2011fb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index a7258cb1bb0..c2ebc9261a1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -72,7 +72,7 @@ public string Culture if (trimmedValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { if ((trimmedValue.Length > 2) && - int.TryParse(trimmedValue.Substring(2), NumberStyles.AllowHexSpecifier, + int.TryParse(trimmedValue.AsSpan(2), NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, out cultureNumber)) { _cultureInfo = new CultureInfo(cultureNumber); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCreationBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCreationBase.cs index 43e3e93839d..cb0e9ea2435 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCreationBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCreationBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs index 205b61fcd8d..23b4bac873a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ReadConsoleCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.Commands /// Retrieves input from the host virtual console and writes it to the pipeline output. /// - [Cmdlet(VerbsCommunications.Read, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096610")] + [Cmdlet(VerbsCommunications.Read, "Host", DefaultParameterSetName = "AsString", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096610")] [OutputType(typeof(string), typeof(SecureString))] public sealed class ReadHostCommand : PSCmdlet { @@ -55,10 +55,9 @@ public sealed class ReadHostCommand : PSCmdlet } /// - /// Set to no echo the input as is is typed. + /// Gets or sets to no echo the input as is is typed. If set then the cmdlet returns a secure string. /// - - [Parameter] + [Parameter(ParameterSetName = "AsSecureString")] public SwitchParameter AsSecureString @@ -73,6 +72,18 @@ public sealed class ReadHostCommand : PSCmdlet _safe = value; } } + + /// + /// Gets or sets whether the console will echo the input as is is typed. If set then the cmdlet returns a regular string. + /// + [Parameter(ParameterSetName = "AsString")] + public + SwitchParameter + MaskInput + { + get; + set; + } #endregion Parameters #region Cmdlet Overrides @@ -149,6 +160,10 @@ protected override void BeginProcessing() { result = Host.UI.ReadLineAsSecureString(); } + else if (MaskInput) + { + result = Host.UI.ReadLineMaskedAsString(); + } else { result = Host.UI.ReadLine(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs index 6229cd42e84..ce72dac51fe 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterObjectEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs index c634779cb78..f04124e9a4c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RegisterPSEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs index c3ec16fa0b6..458b471b322 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Remove-PSBreakpoint.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs index 8a32bfa30c5..7b44a0c2664 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs index 0ec00f82236..14acbbdf6af 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 47a6c2d51cd..bba2ac2873d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -25,7 +25,7 @@ internal PSPropertyExpressionFilter(string[] wildcardPatternsStrings) { if (wildcardPatternsStrings == null) { - throw new ArgumentNullException("wildcardPatternsStrings"); + throw new ArgumentNullException(nameof(wildcardPatternsStrings)); } _wildcardPatterns = new WildcardPattern[wildcardPatternsStrings.Length]; @@ -329,6 +329,7 @@ internal UniquePSObjectHelper(PSObject o, int notePropertyCount) } internal readonly PSObject WrittenObject; + internal int NotePropertyCount { get; } } 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 74861700732..78e65d806a3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -374,9 +374,13 @@ protected override void EndProcessing() ErrorRecord er = new ErrorRecord(ex, "AuthenticationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } + finally + { + _mSmtpClient.Dispose(); - // If we don't dispose the attachments, the sender can't modify or use the files sent. - _mMailMessage.Attachments.Dispose(); + // If we don't dispose the attachments, the sender can't modify or use the files sent. + _mMailMessage.Attachments.Dispose(); + } } #endregion 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 9b18c6fd4c5..cb4b14a6619 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Set-PSBreakpoint.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs index eda5028b373..b2746625375 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetAliasCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs index 3382ec5cdb0..e00a3bda2d9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 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 2e260c5953d..701508ed4ff 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -377,7 +377,7 @@ private bool CanProcessRecordForOneCommand() try { - _commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.IndexOf('\\') != -1); + _commandViewModelObj = _showCommandProxy.GetCommandViewModel(new ShowCommandCommandInfo(commandInfo), _noCommonParameter.ToBool(), _importedModules, this.Name.Contains('\\')); _showCommandProxy.ShowCommandWindow(_commandViewModelObj, _passThrough); } catch (TargetInvocationException ti) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index 7b6bb0674c7..c0226471bdd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -23,7 +23,7 @@ public ShowCommandCommandInfo(CommandInfo other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Name; @@ -71,7 +71,7 @@ public ShowCommandCommandInfo(PSObject other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Members["Name"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index 9c3f97d5165..457cf6d7028 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -21,7 +21,7 @@ public ShowCommandModuleInfo(PSModuleInfo other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Name; @@ -37,7 +37,7 @@ public ShowCommandModuleInfo(PSObject other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Members["Name"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index a7fb2664a11..665fa039929 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -23,7 +23,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Name; @@ -50,7 +50,7 @@ public ShowCommandParameterInfo(PSObject other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Members["Name"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index e9d149bfca5..e3c4cbf2cb7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -23,7 +23,7 @@ public ShowCommandParameterSetInfo(CommandParameterSetInfo other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Name; @@ -41,7 +41,7 @@ public ShowCommandParameterSetInfo(PSObject other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.Name = other.Members["Name"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index 3bde6cdf858..d7a3258d27b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -22,7 +22,7 @@ public ShowCommandParameterType(Type other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.FullName = other.FullName; @@ -51,7 +51,7 @@ public ShowCommandParameterType(PSObject other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } this.IsEnum = (bool)(other.Members["IsEnum"].Value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs index 8b39c5f13fb..4a5700bdf7a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs index 65fb48e4126..2203fbb20a7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 f2847b3d50e..5f66b39753f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index 0e62652842a..4fe5c641ff9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 3866c1202ad..32048362b06 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index 23f0cc7c37f..668c5072841 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -1,12 +1,13 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; -using System.Collections.Generic; +using System.Globalization; +using System.IO; using System.Management.Automation; -using System.Management.Automation.Internal; - -using Newtonsoft.Json; +using System.Reflection; +using System.Runtime.ExceptionServices; +using System.Security; using Newtonsoft.Json.Linq; using NJsonSchema; @@ -15,50 +16,122 @@ namespace Microsoft.PowerShell.Commands /// /// This class implements Test-Json command. /// - [Cmdlet(VerbsDiagnostic.Test, "Json", HelpUri = "")] + [Cmdlet(VerbsDiagnostic.Test, "Json", DefaultParameterSetName = ParameterAttribute.AllParameterSets, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096609")] public class TestJsonCommand : PSCmdlet { + private const string SchemaFileParameterSet = "SchemaFile"; + private const string SchemaStringParameterSet = "SchemaString"; + /// - /// An JSON to be validated. + /// Gets or sets JSON string to be validated. /// [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] public string Json { get; set; } /// - /// A schema to validate the JSON against. + /// Gets or sets schema to validate the JSON against. /// This is optional parameter. /// If the parameter is absent the cmdlet only attempts to parse the JSON string. /// If the parameter present the cmdlet attempts to parse the JSON string and /// then validates the JSON against the schema. Before testing the JSON string, /// the cmdlet parses the schema doing implicitly check the schema too. /// - [Parameter(Position = 1)] - [ValidateNotNullOrEmpty()] + [Parameter(Position = 1, ParameterSetName = SchemaStringParameterSet)] + [ValidateNotNullOrEmpty] public string Schema { get; set; } + /// + /// Gets or sets path to the file containg schema to validate the JSON string against. + /// This is optional parameter. + /// + [Parameter(Position = 1, ParameterSetName = SchemaFileParameterSet)] + [ValidateNotNullOrEmpty] + public string SchemaFile { get; set; } + private JsonSchema _jschema; /// - /// Prepare an JSON schema. + /// Process all exceptions in the AggregateException. + /// Unwrap TargetInvocationException if any and + /// rethrow inner exception without losing the stack trace. + /// + /// AggregateException to be unwrapped. + /// Return value is unreachable since we always rethrow. + private static bool UnwrapException(Exception e) + { + if (e is TargetInvocationException) + { + ExceptionDispatchInfo.Capture(e.InnerException).Throw(); + } + else + { + ExceptionDispatchInfo.Capture(e).Throw(); + } + + return true; + } + + /// + /// Prepare a JSON schema. /// protected override void BeginProcessing() { - if (Schema != null) + string resolvedpath = string.Empty; + + try { - try + if (Schema != null) { - _jschema = JsonSchema.FromJsonAsync(Schema).Result; + try + { + _jschema = JsonSchema.FromJsonAsync(Schema).Result; + } + catch (AggregateException ae) + { + // Even if only one exception is thrown, it is still wrapped in an AggregateException exception + // https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library + ae.Handle(UnwrapException); + } } - catch (Exception exc) + else if (SchemaFile != null) { - Exception exception = new Exception(TestJsonCmdletStrings.InvalidJsonSchema, exc); - ThrowTerminatingError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, null)); + try + { + resolvedpath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(SchemaFile); + _jschema = JsonSchema.FromFileAsync(resolvedpath).Result; + } + catch (AggregateException ae) + { + ae.Handle(UnwrapException); + } } } + catch (Exception e) when ( + // Handle exceptions related to file access to provide more specific error message + // https://docs.microsoft.com/en-us/dotnet/standard/io/handling-io-errors + e is IOException || + e is UnauthorizedAccessException || + e is NotSupportedException || + e is SecurityException + ) + { + Exception exception = new Exception( + string.Format( + CultureInfo.CurrentUICulture, + TestJsonCmdletStrings.JsonSchemaFileOpenFailure, + resolvedpath), + e); + ThrowTerminatingError(new ErrorRecord(exception, "JsonSchemaFileOpenFailure", ErrorCategory.OpenError, resolvedpath)); + } + catch (Exception e) + { + Exception exception = new Exception(TestJsonCmdletStrings.InvalidJsonSchema, e); + ThrowTerminatingError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, resolvedpath)); + } } /// - /// Validate an JSON. + /// Validate a JSON. /// protected override void ProcessRecord() { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs index 3e45cf8d7f7..d7071a06605 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TimeExpressionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index 8e4a92ea389..fad330212ed 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -188,7 +188,7 @@ private bool IsValidFileForUnblocking(string resolvedpath) } else { - isValidUnblockableFile = true; ; + isValidUnblockableFile = true; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs index d6d9e4c222a..f89b3d6e4cc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 a0b093cfb90..d19810522d0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-Data.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 ceac0ad541e..dbff09ef36a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 8131fbcded6..de7d2590176 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -29,6 +29,7 @@ public class UpdateTypeDataCommand : UpdateData private const string TypeDataSet = "TypeDataSet"; private static object s_notSpecified = new object(); + private static bool HasBeenSpecified(object obj) { return !System.Object.ReferenceEquals(obj, s_notSpecified); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index f3c9d86a8e9..aa4c2634266 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -43,6 +43,11 @@ public enum TextEncodingType /// BigEndianUnicode, + /// + /// Big Endian UTF32 encoding. + /// + BigEndianUTF32, + /// /// UTF8 encoding. /// @@ -116,7 +121,7 @@ public ByteCollection(ulong offset, byte[] value, string path) { if (value == null) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } Offset64 = offset; @@ -145,7 +150,7 @@ public ByteCollection(ulong offset, byte[] value) { if (value == null) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } Offset64 = offset; @@ -174,7 +179,7 @@ public ByteCollection(byte[] value) { if (value == null) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } Bytes = value; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index 2ad4b0c04c6..6739dbb38e5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 5fbfb6f8763..7aeb864e2ba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 664c3d69d46..1d33957d624 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,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -57,22 +57,28 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentSt #region Properties /// - /// Gets the Content property. + /// Gets the text body content of this response. /// + /// + /// Content of the response body, decoded using , + /// if the Content-Type response header is a recognized text + /// type. Otherwise null. + /// public new string Content { get; private set; } /// - /// Gets the Encoding that was used to decode the Content. + /// Gets the encoding of the text body content of this response. /// /// - /// The Encoding used to decode the Content; otherwise, a null reference if the content is not text. + /// Encoding of the response body from the Content-Type header, + /// or null if the encoding could not be determined. /// public Encoding Encoding { get; private set; } private WebCmdletElementCollection _inputFields; /// - /// Gets the Fields property. + /// Gets the HTML input field elements parsed from . /// public WebCmdletElementCollection InputFields { @@ -99,7 +105,7 @@ public WebCmdletElementCollection InputFields private WebCmdletElementCollection _links; /// - /// Gets the Links property. + /// Gets the HTML a link elements parsed from . /// public WebCmdletElementCollection Links { @@ -126,7 +132,7 @@ public WebCmdletElementCollection Links private WebCmdletElementCollection _images; /// - /// Gets the Images property. + /// Gets the HTML img elements parsed from . /// public WebCmdletElementCollection Images { @@ -226,7 +232,7 @@ private void EnsureHtmlParser() if (s_imageRegex == null) { - s_imageRegex = new Regex(@"]*>", + s_imageRegex = new Regex(@"]*?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } } 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 98d5a73d328..8e28c630e17 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 344323cd939..273fae835c3 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -85,7 +85,7 @@ public int MaximumFollowRelLink #region Helper Methods - private bool TryProcessFeedStream(BufferingStreamReader responseStream) + private bool TryProcessFeedStream(Stream responseStream) { bool isRssOrFeed = false; @@ -380,97 +380,97 @@ public partial class InvokeRestMethodCommand : WebRequestPSCmdlet /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException("response"); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } - using (BufferingStreamReader responseStream = new BufferingStreamReader(StreamHelper.GetResponseStream(response))) + var baseResponseStream = StreamHelper.GetResponseStream(response); + + if (ShouldWriteToPipeline) { - if (ShouldWriteToPipeline) + using var responseStream = new BufferingStreamReader(baseResponseStream); + + // First see if it is an RSS / ATOM feed, in which case we can + // stream it - unless the user has overridden it with a return type of "XML" + if (TryProcessFeedStream(responseStream)) { - // First see if it is an RSS / ATOM feed, in which case we can - // stream it - unless the user has overridden it with a return type of "XML" - if (TryProcessFeedStream(responseStream)) + // Do nothing, content has been processed. + } + else + { + // determine the response type + RestReturnType returnType = CheckReturnType(response); + + // Try to get the response encoding from the ContentType header. + Encoding encoding = null; + string charSet = response.Content.Headers.ContentType?.CharSet; + if (!string.IsNullOrEmpty(charSet)) { - // Do nothing, content has been processed. + // NOTE: Don't use ContentHelper.GetEncoding; it returns a + // default which bypasses checking for a meta charset value. + StreamHelper.TryGetEncoding(charSet, out encoding); } - else - { - // determine the response type - RestReturnType returnType = CheckReturnType(response); - - // Try to get the response encoding from the ContentType header. - Encoding encoding = null; - string charSet = response.Content.Headers.ContentType?.CharSet; - if (!string.IsNullOrEmpty(charSet)) - { - // NOTE: Don't use ContentHelper.GetEncoding; it returns a - // default which bypasses checking for a meta charset value. - StreamHelper.TryGetEncoding(charSet, out encoding); - } - if (string.IsNullOrEmpty(charSet) && returnType == RestReturnType.Json) - { - encoding = Encoding.UTF8; - } - - object obj = null; - Exception ex = null; + if (string.IsNullOrEmpty(charSet) && returnType == RestReturnType.Json) + { + encoding = Encoding.UTF8; + } - string str = StreamHelper.DecodeStream(responseStream, ref encoding); + object obj = null; + Exception ex = null; - string encodingVerboseName; - try - { - encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName) ? encoding.EncodingName : encoding.HeaderName; - } - catch (NotSupportedException) - { - encodingVerboseName = encoding.EncodingName; - } - // NOTE: Tests use this verbose output to verify the encoding. - WriteVerbose(string.Format - ( - System.Globalization.CultureInfo.InvariantCulture, - "Content encoding: {0}", - encodingVerboseName) - ); - bool convertSuccess = false; - - if (returnType == RestReturnType.Json) - { - convertSuccess = TryConvertToJson(str, out obj, ref ex) || TryConvertToXml(str, out obj, ref ex); - } - // default to try xml first since it's more common - else - { - convertSuccess = TryConvertToXml(str, out obj, ref ex) || TryConvertToJson(str, out obj, ref ex); - } + string str = StreamHelper.DecodeStream(responseStream, ref encoding); - if (!convertSuccess) - { - // fallback to string - obj = str; - } + string encodingVerboseName; + try + { + encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName) ? encoding.EncodingName : encoding.HeaderName; + } + catch (NotSupportedException) + { + encodingVerboseName = encoding.EncodingName; + } + // NOTE: Tests use this verbose output to verify the encoding. + WriteVerbose(string.Format + ( + System.Globalization.CultureInfo.InvariantCulture, + "Content encoding: {0}", + encodingVerboseName) + ); + bool convertSuccess = false; + + if (returnType == RestReturnType.Json) + { + convertSuccess = TryConvertToJson(str, out obj, ref ex) || TryConvertToXml(str, out obj, ref ex); + } + // default to try xml first since it's more common + else + { + convertSuccess = TryConvertToXml(str, out obj, ref ex) || TryConvertToJson(str, out obj, ref ex); + } - WriteObject(obj); + if (!convertSuccess) + { + // fallback to string + obj = str; } - } - if (ShouldSaveToOutFile) - { - StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this); + WriteObject(obj); } + } + else if (ShouldSaveToOutFile) + { + StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, _cancelToken.Token); + } - if (!string.IsNullOrEmpty(StatusCodeVariable)) - { - PSVariableIntrinsics vi = SessionState.PSVariable; - vi.Set(StatusCodeVariable, (int)response.StatusCode); - } + if (!string.IsNullOrEmpty(StatusCodeVariable)) + { + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(StatusCodeVariable, (int)response.StatusCode); + } - if (!string.IsNullOrEmpty(ResponseHeadersVariable)) - { - PSVariableIntrinsics vi = SessionState.PSVariable; - vi.Set(ResponseHeadersVariable, WebResponseHelper.GetHeadersDictionary(response)); - } + if (!string.IsNullOrEmpty(ResponseHeadersVariable)) + { + PSVariableIntrinsics vi = SessionState.PSVariable; + vi.Set(ResponseHeadersVariable, WebResponseHelper.GetHeadersDictionary(response)); } } @@ -480,7 +480,7 @@ internal override void ProcessResponse(HttpResponseMessage response) private RestReturnType CheckReturnType(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException("response"); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } RestReturnType rt = RestReturnType.Detect; string contentType = ContentHelper.GetContentType(response); 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 5bd4e0226fe..f38446ed57f 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 @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -751,7 +751,7 @@ private Uri PrepareUri(Uri uri) private Uri CheckProtocol(Uri uri) { - if (uri == null) { throw new ArgumentNullException("uri"); } + if (uri == null) { throw new ArgumentNullException(nameof(uri)); } if (!uri.IsAbsoluteUri) { @@ -763,14 +763,14 @@ private Uri CheckProtocol(Uri uri) private string QualifyFilePath(string path) { - string resolvedFilePath = PathUtils.ResolveFilePath(path, this, false); + string resolvedFilePath = PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); return resolvedFilePath; } private string FormatDictionary(IDictionary content) { if (content == null) - throw new ArgumentNullException("content"); + throw new ArgumentNullException(nameof(content)); StringBuilder bodyBuilder = new StringBuilder(); foreach (string key in content.Keys) @@ -918,7 +918,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet /// /// Cancellation token source. /// - private CancellationTokenSource _cancelToken = null; + internal CancellationTokenSource _cancelToken = null; /// /// Parse Rel Links. @@ -1070,7 +1070,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) if (!string.IsNullOrEmpty(CustomMethod)) { // set the method if the parameter was provided - httpMethod = new HttpMethod(CustomMethod.ToString().ToUpperInvariant()); + httpMethod = new HttpMethod(CustomMethod.ToUpperInvariant()); } break; @@ -1165,7 +1165,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) internal virtual void FillRequestStream(HttpRequestMessage request) { - if (request == null) { throw new ArgumentNullException("request"); } + if (request == null) { throw new ArgumentNullException(nameof(request)); } // set the content type if (ContentType != null) @@ -1338,9 +1338,9 @@ private bool ShouldRetry(HttpStatusCode code) internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) { - if (client == null) { throw new ArgumentNullException("client"); } + if (client == null) { throw new ArgumentNullException(nameof(client)); } - if (request == null) { throw new ArgumentNullException("request"); } + if (request == null) { throw new ArgumentNullException(nameof(request)); } // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; @@ -1452,7 +1452,7 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException("response"); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } } #endregion Virtual Methods @@ -1478,7 +1478,7 @@ protected override void ProcessRecord() && PreserveAuthorizationOnRedirect.IsPresent && - WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization.ToString()); + WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); using (HttpClient client = GetHttpClient(keepAuthorization)) { @@ -1658,7 +1658,7 @@ protected override void StopProcessing() internal long SetRequestContent(HttpRequestMessage request, byte[] content) { if (request == null) - throw new ArgumentNullException("request"); + throw new ArgumentNullException(nameof(request)); if (content == null) return 0; @@ -1681,7 +1681,7 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) internal long SetRequestContent(HttpRequestMessage request, string content) { if (request == null) - throw new ArgumentNullException("request"); + throw new ArgumentNullException(nameof(request)); if (content == null) return 0; @@ -1730,7 +1730,7 @@ internal long SetRequestContent(HttpRequestMessage request, string content) internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { if (request == null) - throw new ArgumentNullException("request"); + throw new ArgumentNullException(nameof(request)); if (xmlNode == null) return 0; @@ -1767,9 +1767,9 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) internal long SetRequestContent(HttpRequestMessage request, Stream contentStream) { if (request == null) - throw new ArgumentNullException("request"); + throw new ArgumentNullException(nameof(request)); if (contentStream == null) - throw new ArgumentNullException("contentStream"); + throw new ArgumentNullException(nameof(contentStream)); var streamContent = new StreamContent(contentStream); request.Content = streamContent; @@ -1791,12 +1791,12 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon { if (request == null) { - throw new ArgumentNullException("request"); + throw new ArgumentNullException(nameof(request)); } if (multipartContent == null) { - throw new ArgumentNullException("multipartContent"); + throw new ArgumentNullException(nameof(multipartContent)); } request.Content = multipartContent; @@ -1807,9 +1807,9 @@ internal long SetRequestContent(HttpRequestMessage request, MultipartFormDataCon internal long SetRequestContent(HttpRequestMessage request, IDictionary content) { if (request == null) - throw new ArgumentNullException("request"); + throw new ArgumentNullException(nameof(request)); if (content == null) - throw new ArgumentNullException("content"); + throw new ArgumentNullException(nameof(content)); string body = FormatDictionary(content); return (SetRequestContent(request, body)); @@ -1845,7 +1845,7 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr if (url != string.Empty && rel != string.Empty && !_relationLink.ContainsKey(rel)) { Uri absoluteUri = new Uri(requestUri, url); - _relationLink.Add(rel, absoluteUri.AbsoluteUri.ToString()); + _relationLink.Add(rel, absoluteUri.AbsoluteUri); } } } @@ -1899,7 +1899,7 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF } // Treat the value as a collection and enumerate it if enumeration is true - if (enumerate == true && fieldValue is IEnumerable items) + if (enumerate && fieldValue is IEnumerable items) { foreach (var item in items) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 39ac6bdf20e..70c5721dbc1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -18,13 +18,13 @@ public partial class WebResponseObject #region Properties /// - /// Gets or protected sets the Content property. + /// Gets or protected sets the response body content. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public byte[] Content { get; protected set; } /// - /// Gets the StatusCode property. + /// Gets the response status code. /// public int StatusCode { @@ -32,7 +32,7 @@ public int StatusCode } /// - /// Gets the StatusDescription property. + /// Gets the response status description. /// public string StatusDescription { @@ -41,7 +41,7 @@ public string StatusDescription private MemoryStream _rawContentStream; /// - /// Gets the RawContentStream property. + /// Gets the response body content as a . /// public MemoryStream RawContentStream { @@ -49,7 +49,7 @@ public MemoryStream RawContentStream } /// - /// Gets the RawContentLength property. + /// Gets the length (in bytes) of . /// public long RawContentLength { @@ -57,8 +57,11 @@ public long RawContentLength } /// - /// Gets or protected sets the RawContent property. + /// Gets or protected sets the full response content. /// + /// + /// Full response content, including the HTTP status line, headers, and body. + /// public string RawContent { get; protected set; } #endregion Properties @@ -179,7 +182,7 @@ private void InitializeRawContent(HttpResponseMessage baseResponse) private void SetResponse(HttpResponseMessage response, Stream contentStream) { - if (response == null) { throw new ArgumentNullException("response"); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } BaseResponse = response; 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 518613ea0e4..955786248f7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 8ebbabee593..92e67f5681a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -26,7 +26,9 @@ public class ConvertToJsonCommand : PSCmdlet public object InputObject { get; set; } private int _depth = 2; + private const int maxDepthAllowed = 100; + private readonly CancellationTokenSource _cancellationSource = new CancellationTokenSource(); /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index 1de3a7c14e5..80d07a54ddf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -6,7 +6,7 @@ namespace Microsoft.PowerShell.Commands { - internal static partial class HttpKnownHeaderNames + internal static class HttpKnownHeaderNames { #region Known_HTTP_Header_Names @@ -79,6 +79,7 @@ internal static partial class HttpKnownHeaderNames #endregion Known_HTTP_Header_Names private static HashSet s_contentHeaderSet = null; + internal static HashSet ContentHeaders { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index 1e98d253745..b0f849490cd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -31,7 +31,7 @@ public InvokeWebRequestCommand() : base() /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException("response"); } + if (response == null) { throw new ArgumentNullException(nameof(response)); } Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) @@ -51,7 +51,7 @@ internal override void ProcessResponse(HttpResponseMessage response) if (ShouldSaveToOutFile) { - StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this); + StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this, _cancelToken.Token); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index c338be5ac9f..5cb4f2b4fde 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -15,7 +15,7 @@ internal WebProxy(Uri address) { if (address == null) { - throw new ArgumentNullException("address"); + throw new ArgumentNullException(nameof(address)); } _proxyAddress = address; @@ -50,7 +50,7 @@ public Uri GetProxy(Uri destination) { if (destination == null) { - throw new ArgumentNullException("destination"); + throw new ArgumentNullException(nameof(destination)); } if (destination.IsLoopback) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index b61977d87e9..dc2f734d6bd 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.Commands { - internal static partial class WebResponseHelper + internal static class WebResponseHelper { internal static string GetCharacterSet(HttpResponseMessage response) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs index bc8502ccc16..c4371515fe7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs index aadaf616d38..d1a4cde2115 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs index 53c60384136..9072e431cae 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 2a03d53f4f2..def03fc9c45 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -780,7 +780,7 @@ private static object ProcessCustomObject(object o, int depth, in ConvertToJs if (!info2.IsDefined(typeof(T), true)) { MethodInfo getMethod = info2.GetGetMethod(); - if ((getMethod != null) && (getMethod.GetParameters().Length <= 0)) + if ((getMethod != null) && (getMethod.GetParameters().Length == 0)) { object value; try 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 be3b79ecfc5..a730c043216 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 91a9a0e9975..58d63c36ca3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -9,6 +9,8 @@ using System.Net.Http; using System.Text; using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; namespace Microsoft.PowerShell.Commands { @@ -99,7 +101,7 @@ public override long Length /// /// /// - public override System.Threading.Tasks.Task CopyToAsync(Stream destination, int bufferSize, System.Threading.CancellationToken cancellationToken) + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { Initialize(); return base.CopyToAsync(destination, bufferSize, cancellationToken); @@ -124,7 +126,7 @@ public override int Read(byte[] buffer, int offset, int count) /// /// /// - public override System.Threading.Tasks.Task ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Initialize(); return base.ReadAsync(buffer, offset, count, cancellationToken); @@ -175,7 +177,7 @@ public override void Write(byte[] buffer, int offset, int count) /// /// /// - public override System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Initialize(); return base.WriteAsync(buffer, offset, count, cancellationToken); @@ -273,73 +275,55 @@ internal static class StreamHelper #region Static Methods - internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet) + internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, CancellationToken cancellationToken) { - byte[] data = new byte[ChunkSize]; + if (cmdlet == null) + { + throw new ArgumentNullException(nameof(cmdlet)); + } - int read = 0; - long totalWritten = 0; - do + Task copyTask = input.CopyToAsync(output, cancellationToken); + + ProgressRecord record = new ProgressRecord( + ActivityId, + WebCmdletStrings.WriteRequestProgressActivity, + WebCmdletStrings.WriteRequestProgressStatus); + try { - if (cmdlet != null) + do { - ProgressRecord record = new ProgressRecord(ActivityId, - WebCmdletStrings.WriteRequestProgressActivity, - StringUtil.Format(WebCmdletStrings.WriteRequestProgressStatus, totalWritten)); + record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestProgressStatus, output.Position); cmdlet.WriteProgress(record); - } - read = input.Read(data, 0, ChunkSize); + Task.Delay(1000).Wait(cancellationToken); + } + while (!copyTask.IsCompleted && !cancellationToken.IsCancellationRequested); - if (0 < read) + if (copyTask.IsCompleted) { - output.Write(data, 0, read); - totalWritten += read; + record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestComplete, output.Position); + cmdlet.WriteProgress(record); } - } while (read != 0); - - if (cmdlet != null) + } + catch (OperationCanceledException) { - ProgressRecord record = new ProgressRecord(ActivityId, - WebCmdletStrings.WriteRequestProgressActivity, - StringUtil.Format(WebCmdletStrings.WriteRequestComplete, totalWritten)); - record.RecordType = ProgressRecordType.Completed; - cmdlet.WriteProgress(record); } - - output.Flush(); - } - - internal static void WriteToStream(byte[] input, Stream output) - { - output.Write(input, 0, input.Length); - output.Flush(); } /// /// Saves content from stream into filePath. /// Caller need to ensure position is properly set. /// - /// - /// - /// - internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet) + /// Input stream. + /// Output file name. + /// Current cmdlet (Invoke-WebRequest or Invoke-RestMethod). + /// CancellationToken to track the cmdlet cancellation. + internal static void SaveStreamToFile(Stream stream, string filePath, PSCmdlet cmdlet, CancellationToken cancellationToken) { // If the web cmdlet should resume, append the file instead of overwriting. - if (cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume) - { - using (FileStream output = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.Read)) - { - WriteToStream(stream, output, cmdlet); - } - } - else - { - using (FileStream output = File.Create(filePath)) - { - WriteToStream(stream, output, cmdlet); - } - } + FileMode fileMode = cmdlet is WebRequestPSCmdlet webCmdlet && webCmdlet.ShouldResume ? FileMode.Append : FileMode.Create; + using FileStream output = new FileStream(filePath, fileMode, FileAccess.Write, FileShare.Read); + WriteToStream(stream, output, cmdlet, cancellationToken); } private static string StreamToString(Stream stream, Encoding encoding) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs index 340baf18550..fada385d4ac 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs index 1ed35bd9545..aa7067f1c23 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index 384c72a5219..a28f07c842c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs index e24cc35702b..2d7fc9d233d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write-Object.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index 727eaa9d779..6f374336da5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs index 130f88c2a8f..3dbb2e378ad 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 2b32e2acf02..7c2f2e44bf9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -71,7 +71,7 @@ private string ProcessObject(object o) foreach (object element in enumerable) { - if (printSeparator == true && Separator != null) + if (printSeparator && Separator != null) { result.Append(Separator.ToString()); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index d3abb9d2285..070c1275aa8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 0013b22963c..8736965fd61 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs index cefb4dd9744..b37f06b2b2f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Linq; 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 c95c9793be0..9b225bdc141 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -31,7 +31,7 @@ internal PSHostTraceListener(PSCmdlet cmdlet) { if (cmdlet == null) { - throw new PSArgumentNullException("cmdlet"); + throw new PSArgumentNullException(nameof(cmdlet)); } Diagnostics.Assert( diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs index 032fa63006c..d05a535145d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; 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 c52862fc8c3..a2e04f79ae1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; 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 a3000848988..12f8e5b4e09 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -334,12 +334,12 @@ internal TracePipelineWriter( { if (cmdlet == null) { - throw new ArgumentNullException("cmdlet"); + throw new ArgumentNullException(nameof(cmdlet)); } if (matchingSources == null) { - throw new ArgumentNullException("matchingSources"); + throw new ArgumentNullException(nameof(matchingSources)); } _cmdlet = cmdlet; 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 31a6845c0eb..3eecdd51cba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceListenerCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx index a5c8d5d24d9..ab105e47fd3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx @@ -126,4 +126,7 @@ The JSON is not valid with the schema. + + Can not open JSON schema file: {0} + diff --git a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs index c86dad7e054..1c29b44c603 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs b/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs index 7a8ebd5fbd2..26b1dbe9a48 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.CompilerServices; diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs index a62e51c29fb..761c6f6e26f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -56,39 +56,52 @@ void GetPath( int cchMaxPath, IntPtr pfd, uint fFlags); + void GetIDList(out IntPtr ppidl); void SetIDList(IntPtr pidl); + void GetDescription( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxName); + void SetDescription( [MarshalAs(UnmanagedType.LPWStr)] string pszName); + void GetWorkingDirectory( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath ); + void SetWorkingDirectory( [MarshalAs(UnmanagedType.LPWStr)] string pszDir); + void GetArguments( [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); + void SetArguments( [MarshalAs(UnmanagedType.LPWStr)] string pszArgs); + void GetHotKey(out short wHotKey); void SetHotKey(short wHotKey); void GetShowCmd(out uint iShowCmd); void SetShowCmd(uint iShowCmd); + void GetIconLocation( [Out(), MarshalAs(UnmanagedType.LPWStr)] out StringBuilder pszIconPath, int cchIconPath, out int iIcon); + void SetIconLocation( [MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); + void SetRelativePath( [MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved); + void Resolve(IntPtr hwnd, uint fFlags); + void SetPath( [MarshalAs(UnmanagedType.LPWStr)] string pszFile); } @@ -151,26 +164,34 @@ internal interface ICustomDestinationList { void SetAppID( [MarshalAs(UnmanagedType.LPWStr)] string pszAppID); + [PreserveSig] HResult BeginList( out uint cMaxSlots, ref Guid riid, [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); + [PreserveSig] HResult AppendCategory( [MarshalAs(UnmanagedType.LPWStr)] string pszCategory, [MarshalAs(UnmanagedType.Interface)] IObjectArray poa); + void AppendKnownCategory( [MarshalAs(UnmanagedType.I4)] KnownDestinationCategory category); + [PreserveSig] HResult AddUserTasks( [MarshalAs(UnmanagedType.Interface)] IObjectArray poa); + void CommitList(); + void GetRemovedDestinations( ref Guid riid, [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); + void DeleteList( [MarshalAs(UnmanagedType.LPWStr)] string pszAppID); + void AbortList(); } @@ -186,6 +207,7 @@ internal enum KnownDestinationCategory internal interface IObjectArray { void GetCount(out uint cObjects); + void GetAt( uint iIndex, ref Guid riid, @@ -208,8 +230,10 @@ void GetAt( // IObjectCollection void AddObject( [MarshalAs(UnmanagedType.Interface)] object pvObject); + void AddFromArray( [MarshalAs(UnmanagedType.Interface)] IObjectArray poaSource); + void RemoveObject(uint uiIndex); void Clear(); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs index 13e6fb612d6..e23f0810ea1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.PowerShell diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index 8beb35c637c..5c76d6051b8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -19,10 +19,10 @@ internal sealed class PropVariant : IDisposable { // This is actually a VarEnum value, but the VarEnum type requires 4 bytes instead of the expected 2. [FieldOffset(0)] - ushort _valueType; + private ushort _valueType; [FieldOffset(8)] - IntPtr _ptr; + private IntPtr _ptr; /// /// Set a string value. @@ -31,7 +31,7 @@ internal PropVariant(string value) { if (value == null) { - throw new ArgumentException("PropVariantNullString", "value"); + throw new ArgumentException("PropVariantNullString", nameof(value)); } #pragma warning disable CS0618 // Type or member is obsolete (might get deprecated in future versions diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs index 2040c905a52..be45b0d8d84 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 39014cbee82..5b7572c94b2 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index 47129d45861..f65736a52dc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -96,6 +96,17 @@ public override string ReadLine() throw new PSNotImplementedException(); } + /// + /// Null implementation of ReadLineMaskedAsString. + /// + /// + /// It throws an exception. + /// + public override string ReadLineMaskedAsString() + { + throw new PSNotImplementedException(); + } + /// /// ReadLineAsSecureString. /// @@ -172,7 +183,7 @@ internal class CommandLineParameterParser private const int MaxPipePathLengthLinux = 108; private const int MaxPipePathLengthMacOS = 104; - internal static string[] validParameters = { + internal static readonly string[] validParameters = { "sta", "mta", "command", @@ -847,7 +858,7 @@ private void ParseHelper(string[] args) #if DEBUG // this option is useful when debugging ConsoleHost remotely using VS remote debugging, as you can only // attach to an already running process with that debugger. - else if (MatchSwitch(switchKey, "wait", "w")) + else if (MatchSwitch(switchKey, "wait", "wa")) { // This does not need to be localized: its chk only @@ -868,7 +879,6 @@ private void ParseHelper(string[] args) { // Just toss this option, it was processed earlier... } - else if (MatchSwitch(switchKey, "modules", "mod")) { if (ConsoleHost.DefaultInitialSessionState == null) diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index 45d95ff7920..6159e349497 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -136,6 +136,7 @@ internal struct CONSOLE_FONT_INFO_EX internal short FontHeight; internal int FontFamily; internal int FontWeight; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] internal string FontFace; } @@ -1084,7 +1085,7 @@ internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); if (contents == null) { - throw PSTraceSource.NewArgumentNullException("contents"); + throw PSTraceSource.NewArgumentNullException(nameof(contents)); } uint codePage; @@ -3005,6 +3006,7 @@ internal static void MimicKeyPress(INPUT[] inputs) internal static class NativeMethods { internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h + internal const int FontTypeMask = 0x06; internal const int TrueTypeFont = 0x04; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index e6e8759d3cd..39a32d77c22 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -579,7 +579,7 @@ public void PushRunspace(Runspace newRunspace) RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); - remoteRunspace.StateChanged += new EventHandler(HandleRemoteRunspaceStateChanged); + remoteRunspace.StateChanged += HandleRemoteRunspaceStateChanged; // Unsubscribe the local session debugger. if (_runspaceRef.Runspace.Debugger != null) @@ -735,7 +735,7 @@ public class ConsoleColorProxy public ConsoleColorProxy(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException("ui"); + if (ui == null) throw new ArgumentNullException(nameof(ui)); _ui = ui; } @@ -1280,7 +1280,7 @@ internal bool ShouldEndSession { // If ShouldEndSession is already true, you can't set it back - Dbg.Assert(_shouldEndSession != true || value != false, + Dbg.Assert(_shouldEndSession != true || value, "ShouldEndSession can only be set from false to true"); _shouldEndSession = value; @@ -1580,7 +1580,7 @@ private bool IsScreenReaderActive() if (Platform.IsWindowsDesktop) { // Note: this API can detect if a third-party screen reader is active, such as NVDA, but not the in-box Windows Narrator. - // Quoted from https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfoa about the + // Quoted from https://docs.microsoft.com/windows/win32/api/winuser/nf-winuser-systemparametersinfoa about the // accessibility parameter 'SPI_GETSCREENREADER': // "Narrator, the screen reader that is included with Windows, does not set the SPI_SETSCREENREADER or SPI_GETSCREENREADER flags." bool enabled = false; @@ -2375,8 +2375,8 @@ private InputLoop(ConsoleHost parent, bool isNested) _parent = parent; _isNested = isNested; _isRunspacePushed = parent.IsRunspacePushed; - parent.RunspacePopped += new EventHandler(HandleRunspacePopped); - parent.RunspacePushed += new EventHandler(HandleRunspacePushed); + parent.RunspacePopped += HandleRunspacePopped; + parent.RunspacePushed += HandleRunspacePushed; _exec = new Executor(parent, isNested, false); _promptExec = new Executor(parent, isNested, true); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index af9d754861c..91aceef2fbd 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -609,7 +609,7 @@ public override { if ((options & (ReadKeyOptions.IncludeKeyDown | ReadKeyOptions.IncludeKeyUp)) == 0) { - throw PSTraceSource.NewArgumentException("options", ConsoleHostRawUserInterfaceStrings.InvalidReadKeyOptionsError); + throw PSTraceSource.NewArgumentException(nameof(options), ConsoleHostRawUserInterfaceStrings.InvalidReadKeyOptionsError); } // keyInfo is initialized in the below if-else statement @@ -880,14 +880,14 @@ public override { if (contents == null) { - PSTraceSource.NewArgumentNullException("contents"); + PSTraceSource.NewArgumentNullException(nameof(contents)); } // the origin must be within the window. ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; ConsoleHandle handle = GetBufferInfo(out bufferInfo); - CheckCoordinateWithinBuffer(ref origin, ref bufferInfo, "origin"); + CheckCoordinateWithinBuffer(ref origin, ref bufferInfo, nameof(origin)); // The output is clipped by the console subsystem, so we don't have to check that the array exceeds the buffer // boundaries. @@ -931,14 +931,14 @@ public override // make sure the rect is valid if (region.Right < region.Left) { - throw PSTraceSource.NewArgumentException("region", + throw PSTraceSource.NewArgumentException(nameof(region), ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, "region.Right", "region.Left"); } if (region.Bottom < region.Top) { - throw PSTraceSource.NewArgumentException("region", + throw PSTraceSource.NewArgumentException(nameof(region), ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, "region.Bottom", "region.Top"); } @@ -960,7 +960,7 @@ public override ConsoleControl.IsCJKOutputCodePage(out codePage) && LengthInBufferCells(fill.Character) == 2) { - throw PSTraceSource.NewArgumentException("fill"); + throw PSTraceSource.NewArgumentException(nameof(fill)); } int cells = bufferWidth * bufferHeight; @@ -1005,7 +1005,7 @@ public override { if (leftExisting[r, 0].BufferCellType == BufferCellType.Leading) { - throw PSTraceSource.NewArgumentException("fill"); + throw PSTraceSource.NewArgumentException(nameof(fill)); } } } @@ -1014,7 +1014,7 @@ public override { if (charLength == 2) { - throw PSTraceSource.NewArgumentException("fill"); + throw PSTraceSource.NewArgumentException(nameof(fill)); } } else @@ -1030,7 +1030,7 @@ public override { if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading) { - throw PSTraceSource.NewArgumentException("fill"); + throw PSTraceSource.NewArgumentException(nameof(fill)); } } } @@ -1040,7 +1040,7 @@ public override { if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading ^ charLength == 2) { - throw PSTraceSource.NewArgumentException("fill"); + throw PSTraceSource.NewArgumentException(nameof(fill)); } } } @@ -1091,14 +1091,14 @@ public override // make sure the rect is valid if (region.Right < region.Left) { - throw PSTraceSource.NewArgumentException("region", + throw PSTraceSource.NewArgumentException(nameof(region), ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, "region.Right", "region.Left"); } if (region.Bottom < region.Top) { - throw PSTraceSource.NewArgumentException("region", + throw PSTraceSource.NewArgumentException(nameof(region), ConsoleHostRawUserInterfaceStrings.InvalidRegionErrorTemplate, "region.Bottom", "region.Top"); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs index fe3b37a77ba..fd1b91574b4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostTranscript.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 1addb3dc5b0..483fdb4625d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -29,6 +29,11 @@ namespace Microsoft.PowerShell [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] internal partial class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInterface { + /// + /// This is the char that is echoed to the console when the input is masked. This not localizable. + /// + private const char PrintToken = '*'; + /// /// Command completion implementation object. /// @@ -174,6 +179,39 @@ public override string ReadLine() return ReadLine(false, string.Empty, out unused, true, true); } + /// + /// See base class. + /// + /// + /// The characters typed by the user. + /// + /// + /// If obtaining a handle to the active screen buffer failed + /// OR + /// Win32's setting input buffer mode to disregard window and mouse input failed. + /// OR + /// Win32's ReadConsole failed. + /// + /// + /// If Ctrl-C is entered by user. + /// + public override string ReadLineMaskedAsString() + { + HandleThrowOnReadAndPrompt(); + + // we lock here so that multiple threads won't interleave the various reads and writes here. + object result = null; + lock (_instanceLock) + { + result = ReadLineSafe(false, PrintToken); + } + + StringBuilder resultSb = result as StringBuilder; + Dbg.Assert(resultSb != null, "ReadLineMaskedAsString did not return a stringBuilder"); + + return resultSb.ToString(); + } + /// /// See base class. /// @@ -193,14 +231,12 @@ public override SecureString ReadLineAsSecureString() { HandleThrowOnReadAndPrompt(); - const char printToken = '*'; // This is not localizable - // we lock here so that multiple threads won't interleave the various reads and writes here. object result = null; lock (_instanceLock) { - result = ReadLineSafe(true, printToken); + result = ReadLineSafe(true, PrintToken); } SecureString secureResult = result as SecureString; @@ -603,7 +639,7 @@ private void WriteToConsole(ReadOnlySpan value, bool transcribeResult, boo private void WriteToConsole(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string text, bool newLine = false) { - // Sync access so that we don't race on color settings if called from multiple threads. + // Sync access so that we don't conflict on color settings if called from multiple threads. lock (_instanceLock) { ConsoleColor fg = RawUI.ForegroundColor; @@ -779,7 +815,7 @@ public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgr private void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value, bool newLine) { - // Sync access so that we don't race on color settings if called from multiple threads. + // Sync access so that we don't conflict on color settings if called from multiple threads. lock (_instanceLock) { ConsoleColor fg = RawUI.ForegroundColor; @@ -1376,8 +1412,8 @@ public override void WriteErrorLine(string value) public ConsoleColor VerboseBackgroundColor { get; set; } = Console.BackgroundColor; // Progress colors - public ConsoleColor ProgressForegroundColor { get; set; } = ConsoleColor.Yellow; - public ConsoleColor ProgressBackgroundColor { get; set; } = ConsoleColor.DarkCyan; + public ConsoleColor ProgressForegroundColor { get; set; } = ConsoleColor.Black; + public ConsoleColor ProgressBackgroundColor { get; set; } = ConsoleColor.Yellow; #endregion Line-oriented interaction @@ -1385,7 +1421,8 @@ public override void WriteErrorLine(string value) // We use System.Environment.NewLine because we are platform-agnostic - internal static string Crlf = System.Environment.NewLine; + internal static readonly string Crlf = System.Environment.NewLine; + private const string Tab = "\x0009"; internal enum ReadLineResult @@ -1865,8 +1902,11 @@ private char GetCharacterUnderCursor(Coordinates cursorPosition) /// The string with any \0 characters removed... private string RemoveNulls(string input) { - if (input.IndexOf('\0') == -1) + if (input.Contains('\0')) + { return input; + } + StringBuilder sb = new StringBuilder(); foreach (char c in input) { @@ -2126,6 +2166,7 @@ private CommandCompletion GetNewCompletionResults(string input) } private const string CustomReadlineCommand = "PSConsoleHostReadLine"; + private bool TryInvokeUserDefinedReadLine(out string input) { // We're using GetCommands instead of GetCommand so we don't auto-load a module should the command exist, but isn't loaded. diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index afe2cbd8d63..ffc5735f35f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -192,7 +192,9 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt private PendingProgress _pendingProgress = null; // The timer set up 'progPaneUpdateFlag' every 'UpdateTimerThreshold' milliseconds to update 'ProgressPane' private Timer _progPaneUpdateTimer = null; + private const int UpdateTimerThreshold = 200; + private int progPaneUpdateFlag = 0; } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index bcb729d87cb..9449669ab65 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -97,12 +97,12 @@ public override if (descriptions == null) { - throw PSTraceSource.NewArgumentNullException("descriptions"); + throw PSTraceSource.NewArgumentNullException(nameof(descriptions)); } if (descriptions.Count < 1) { - throw PSTraceSource.NewArgumentException("descriptions", + throw PSTraceSource.NewArgumentException(nameof(descriptions), ConsoleHostUserInterfaceStrings.PromptEmptyDescriptionsErrorTemplate, "descriptions"); } @@ -139,7 +139,7 @@ public override descIndex++; if (desc == null) { - throw PSTraceSource.NewArgumentException("descriptions", + throw PSTraceSource.NewArgumentException(nameof(descriptions), ConsoleHostUserInterfaceStrings.NullErrorTemplate, string.Format(CultureInfo.InvariantCulture, "descriptions[{0}]", descIndex)); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index 660877be1e1..70163c865e4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -46,18 +46,18 @@ public override int PromptForChoice(string caption, string message, Collection= choices.Count)) { - throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(defaultChoice), defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceErrorTemplate, "defaultChoice", "choice"); } @@ -175,12 +175,12 @@ public Collection PromptForChoice(string caption, if (choices == null) { - throw PSTraceSource.NewArgumentNullException("choices"); + throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { - throw PSTraceSource.NewArgumentException("choices", + throw PSTraceSource.NewArgumentException(nameof(choices), ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } @@ -199,10 +199,7 @@ public Collection PromptForChoice(string caption, defaultChoice); } - if (!defaultChoiceKeys.ContainsKey(defaultChoice)) - { - defaultChoiceKeys.Add(defaultChoice, true); - } + defaultChoiceKeys.TryAdd(defaultChoice, true); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs index f78e5b9304b..6926f685795 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceSecurity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs index f8467e634cb..cd8364fc7ce 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs index 590ad7c1a21..c875bc0c506 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index e432b01f6da..24b48837005 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -131,7 +131,7 @@ private class PipelineFinishedWaitHandle { internal PipelineFinishedWaitHandle(Pipeline p) { - p.StateChanged += new EventHandler(PipelineStateChangedHandler); + p.StateChanged += PipelineStateChangedHandler; } internal void Wait() @@ -205,8 +205,8 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc tempPipeline.Commands.Add(outDefault); } - tempPipeline.Output.DataReady += new EventHandler(OutputObjectStreamHandler); - tempPipeline.Error.DataReady += new EventHandler(ErrorObjectStreamHandler); + tempPipeline.Output.DataReady += OutputObjectStreamHandler; + tempPipeline.Error.DataReady += ErrorObjectStreamHandler; PipelineFinishedWaitHandle pipelineWaiter = new PipelineFinishedWaitHandle(tempPipeline); // close the input pipeline so the command will do something @@ -241,7 +241,7 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc // hence the Input pipe. break; } - }; + } des.End(); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 5c271197af2..cfe7f0c16e1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index e0c2b011d4c..ce4b6d95acb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1019,6 +1019,7 @@ internal static private ArrayList _topLevelNodes = new ArrayList(); private int _nodeCount; + private const int maxNodeCount = 128; } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index c3965908bfb..35066c0bf09 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index e2f1bfeb850..55dba38d6b4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -27,7 +27,7 @@ class ProgressPane internal ProgressPane(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException("ui"); + if (ui == null) throw new ArgumentNullException(nameof(ui)); _ui = ui; _rawui = ui.RawUI; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index e24823da6cc..696e47313d5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index 399ed27a94b..1587f91d3f9 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs index 66f76157033..9fae35ac83e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index ff7b952ed39..5c202eb32b1 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index 02eaca3954e..45f387df28b 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -119,7 +119,7 @@ PowerShell {0} -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs index 2cb5dd6d83a..1b3f939158f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs index f06bd4e0b64..c532aeb190d 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs index e007c82fc81..4d72090e088 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Reflection; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs index 0dd474169d9..34fa9105085 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -12,16 +12,22 @@ public struct EventDescriptor { [FieldOffset(0)] private ushort _id; + [FieldOffset(2)] private byte _version; + [FieldOffset(3)] private byte _channel; + [FieldOffset(4)] private byte _level; + [FieldOffset(5)] private byte _opcode; + [FieldOffset(6)] private ushort _task; + [FieldOffset(8)] private long _keywords; @@ -38,12 +44,12 @@ long keywords { if (id < 0) { - throw new ArgumentOutOfRangeException("id", DotNetEventingStrings.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(id), DotNetEventingStrings.ArgumentOutOfRange_NeedNonNegNum); } if (id > ushort.MaxValue) { - throw new ArgumentOutOfRangeException("id", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); + throw new ArgumentOutOfRangeException(nameof(id), string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); } _id = (ushort)id; @@ -55,12 +61,12 @@ long keywords if (task < 0) { - throw new ArgumentOutOfRangeException("task", DotNetEventingStrings.ArgumentOutOfRange_NeedNonNegNum); + throw new ArgumentOutOfRangeException(nameof(task), DotNetEventingStrings.ArgumentOutOfRange_NeedNonNegNum); } if (task > ushort.MaxValue) { - throw new ArgumentOutOfRangeException("task", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); + throw new ArgumentOutOfRangeException(nameof(task), string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_NeedValidId, 1, ushort.MaxValue)); } _task = (ushort)task; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index 9178a5d202b..a1eba143e28 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; @@ -14,6 +14,7 @@ public class EventProvider : IDisposable { [SecurityCritical] private UnsafeNativeMethods.EtwEnableCallback _etwCallback; // Trace Callback function + private long _regHandle; // Trace Registration Handle private byte _level; // Tracing Level private long _anyKeywordMask; // Trace Enable Flags @@ -24,6 +25,7 @@ public class EventProvider : IDisposable [ThreadStatic] private static WriteEventErrorCode t_returnCode; // thread slot to keep last error + [ThreadStatic] private static Guid t_activityId; @@ -48,8 +50,10 @@ private struct EventData { [FieldOffset(0)] internal ulong DataPointer; + [FieldOffset(8)] internal uint Size; + [FieldOffset(12)] internal int Reserved; } @@ -435,7 +439,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe if (eventMessage == null) { - throw new ArgumentNullException("eventMessage"); + throw new ArgumentNullException(nameof(eventMessage)); } if (IsEnabled(eventLevel, eventKeywords)) @@ -619,7 +623,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related // // too many arguments to log // - throw new ArgumentOutOfRangeException("eventPayload", + throw new ArgumentOutOfRangeException(nameof(eventPayload), string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxNumberArguments)); } @@ -656,7 +660,7 @@ public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid related } else { - throw new ArgumentOutOfRangeException("eventPayload", + throw new ArgumentOutOfRangeException(nameof(eventPayload), string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount)); } } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 45927d2c076..97c10d167ef 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -20,10 +20,13 @@ public class EventProviderTraceListener : TraceListener // // private EventProvider _provider; + private const string s_nullStringValue = "null"; private const string s_nullStringComaValue = "null,"; private const string s_nullCStringValue = ": null"; + private string _delimiter = ";"; + private const uint s_keyWordMask = 0xFFFFFF00; private const int s_defaultPayloadSize = 512; @@ -70,7 +73,7 @@ public EventProviderTraceListener(string providerId, string name, string delimit : base(name) { if (delimiter == null) - throw new ArgumentNullException("delimiter"); + throw new ArgumentNullException(nameof(delimiter)); if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs index 71be5f4ca3e..d26c629d54e 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemSafeHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /*============================================================ diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs index 6e7694949a6..8b9c9e44ebc 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/CoTaskMemUnicodeSafeHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /*============================================================ diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs index 06222aa8081..b9956b30681 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/EventLogHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /*============================================================ 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 12bbaca9af2..8858b067f8a 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /*============================================================ @@ -685,7 +685,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; - if ((bool)val == true) varVal.Bool = 1; + if ((bool)val) varVal.Bool = 1; else varVal.Bool = 0; } @@ -730,7 +730,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; - if ((bool)val == true) varVal.Bool = 1; + if ((bool)val) varVal.Bool = 1; else varVal.Bool = 0; } @@ -738,7 +738,7 @@ public static void EvtSetChannelConfigProperty(EventLogHandle handle, UnsafeNati case UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup: { varVal.Type = (uint)UnsafeNativeMethods.EvtVariantType.EvtVarTypeBoolean; - if ((bool)val == true) varVal.Bool = 1; + if ((bool)val) varVal.Bool = 1; else varVal.Bool = 0; } diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 76674132b2d..5da8809897d 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -14,6 +14,7 @@ internal static class UnsafeNativeMethods private const string FormatMessageDllName = "api-ms-win-core-localization-l1-2-0.dll"; private const string EventProviderDllName = "api-ms-win-eventing-provider-l1-1-0.dll"; private const string WEVTAPI = "wevtapi.dll"; + private static readonly IntPtr s_NULL = IntPtr.Zero; // WinError.h codes: @@ -239,18 +240,25 @@ internal struct SystemTime { [MarshalAs(UnmanagedType.U2)] public short Year; + [MarshalAs(UnmanagedType.U2)] public short Month; + [MarshalAs(UnmanagedType.U2)] public short DayOfWeek; + [MarshalAs(UnmanagedType.U2)] public short Day; + [MarshalAs(UnmanagedType.U2)] public short Hour; + [MarshalAs(UnmanagedType.U2)] public short Minute; + [MarshalAs(UnmanagedType.U2)] public short Second; + [MarshalAs(UnmanagedType.U2)] public short Milliseconds; } @@ -261,50 +269,73 @@ internal struct EvtVariant { [FieldOffset(0)] public UInt32 UInteger; + [FieldOffset(0)] public Int32 Integer; + [FieldOffset(0)] public byte UInt8; + [FieldOffset(0)] public short Short; + [FieldOffset(0)] public ushort UShort; + [FieldOffset(0)] public UInt32 Bool; + [FieldOffset(0)] public byte ByteVal; + [FieldOffset(0)] public byte SByte; + [FieldOffset(0)] public UInt64 ULong; + [FieldOffset(0)] public Int64 Long; + [FieldOffset(0)] public Single Single; + [FieldOffset(0)] public double Double; + [FieldOffset(0)] public IntPtr StringVal; + [FieldOffset(0)] public IntPtr AnsiString; + [FieldOffset(0)] public IntPtr SidVal; + [FieldOffset(0)] public IntPtr Binary; + [FieldOffset(0)] public IntPtr Reference; + [FieldOffset(0)] public IntPtr Handle; + [FieldOffset(0)] public IntPtr GuidReference; + [FieldOffset(0)] public UInt64 FileTime; + [FieldOffset(0)] public IntPtr SystemTime; + [FieldOffset(0)] public IntPtr SizeT; + [FieldOffset(8)] public UInt32 Count; // number of elements (not length) in bytes. + [FieldOffset(12)] public UInt32 Type; } @@ -493,12 +524,16 @@ internal struct EvtRpcLogin { [MarshalAs(UnmanagedType.LPWStr)] public string Server; + [MarshalAs(UnmanagedType.LPWStr)] public string User; + [MarshalAs(UnmanagedType.LPWStr)] public string Domain; + [SecurityCritical] public CoTaskMemUnicodeSafeHandle Password; + public int Flags; } @@ -825,8 +860,10 @@ internal struct EvtStringVariant { [MarshalAs(UnmanagedType.LPWStr), FieldOffset(0)] public string StringVal; + [FieldOffset(8)] public UInt32 Count; + [FieldOffset(12)] public UInt32 Type; }; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index 2e025805f4a..3230ef91d5f 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,7 @@ - + diff --git a/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs b/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs index 79c13b4efc5..47a66ea8767 100644 --- a/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs +++ b/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -36,6 +36,11 @@ public static int Main(string[] args) if (File.Exists(pwshPath)) { + Console.CancelKeyPress += (sender, e) => + { + e.Cancel = true; + }; + var process = System.Diagnostics.Process.Start("dotnet", processArgs); process.WaitForExit(); return process.ExitCode; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs index d799a70d9db..375a8101075 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs index 5125f28c88e..09e7bdf9452 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs index 60f7f21c3fd..e321a03e266 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs index 74836e1aa14..3965c362335 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs index e3853d73ccb..a10300e9065 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs index f25791df48c..e469d043ffa 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs index 2c2f28d6173..59e4f4ca13f 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs index a5d012e187f..b3916f46071 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs index 2fc7c332111..0c0af710af1 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs index 0ed137b08f4..7e132405b2a 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs index 4ef9da3b599..0c61da2e117 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs index 05fd348e95e..f32e3365086 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs index 42250fc6eff..e6b1297a7d5 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs index 8926848d7e3..b1943971e3d 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs index 63756347b66..8fafa52c9e4 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs index 18eb8e1f167..1c7a7630ea3 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs index d492336bd6d..007966cb0a8 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.InteropServices; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs index 25af6b87e90..b43904fb773 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs index fa7add127ae..dcfec24631b 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Security.Principal; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs index 35a0059057b..9cad9777cac 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs index 2441c9a2ae7..c34dbcd64d8 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs index d1db20b4fe7..654d221a69b 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs index 026a47ca6f6..68a7d31e833 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs index cd5ee5fccab..e87147fd35d 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs index 9768eb32d92..c2d9bc7f95b 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs index c80c14be7f6..3534b34cc49 100644 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs +++ b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; diff --git a/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs index 72fb6428821..681c38cc6d8 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/CodeInlineRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs index e4ce8ab0e6f..8a4be614796 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/EmphasisInlineRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs index 36f04aca067..121c7ee01fa 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/FencedCodeBlockRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs index 87dc5c0e5aa..eb975d6b6a3 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/HeaderBlockRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs index 7585759675a..55a8ff32a73 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/LeafInlineRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs index ed008b8609e..1f4c8f4ceaf 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/LineBreakRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs index 677143bbff1..3999fd5f4e1 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/LinkInlineRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs index a4076ab04a6..b65d7c25475 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/ListBlockRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs index 417ad052bcb..281cec47d54 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/ListItemBlockRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -61,6 +61,7 @@ private void RenderWithIndent(VT100Renderer renderer, MarkdownObject block, char // 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) diff --git a/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs b/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs index 9a39a6b26ba..c68d9af3d3b 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/MarkdownConverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj index 7c0eca47b7e..6cc2b02c660 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj +++ b/src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs index bdeb1d13c61..26986311614 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/ParagraphBlockRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs index 273f1c05a57..1f26adc5883 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/QuoteBlockRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs index 4b2213ab702..0827fdf049f 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/VT100EscapeSequences.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -273,10 +273,12 @@ private void SetCodeColor(bool isDarkTheme) public class VT100EscapeSequences { private const char Esc = (char)0x1B; + private string endSequence = Esc + "[0m"; // For code blocks, [500@ make sure that the whole line has background color. private const string LongBackgroundCodeBlock = "[500@"; + private PSMarkdownOptionInfo options; /// @@ -287,7 +289,7 @@ public VT100EscapeSequences(PSMarkdownOptionInfo optionInfo) { if (optionInfo == null) { - throw new ArgumentNullException("optionInfo"); + throw new ArgumentNullException(nameof(optionInfo)); } options = optionInfo; diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs index d42c85e1c45..566a086015d 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/VT100ObjectRenderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs b/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs index 65af4a83f80..c817cea7e87 100644 --- a/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs +++ b/src/Microsoft.PowerShell.MarkdownRender/VT100Renderer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index 96a91f1178f..000efa63316 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -16,11 +16,11 @@ - + - - - + + + @@ -30,7 +30,7 @@ - + diff --git a/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs b/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs index 08853e30b8b..3e2e4ff3268 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Reflection; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs index 9bdc6e42e65..48c9fd056d7 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs index 474265eac42..650c643ecf9 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs index b8582600204..2daedddc554 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs index 3c5e833706c..53434c729e7 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs index e2982d85b25..bd9d7439696 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs index 4fef0e1c45b..a507e3161af 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs index 1b89e955984..a8d76ef7da8 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs index 603bfabe31f..2936fcf78c6 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs index bd1ed864a14..d76b1829d42 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs index d692b4aabb1..d06020ed3d6 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs index 9bb46d60ca4..02e37c0acfb 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs index e377287e775..c00626e6d64 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs index 67584690694..6f236ea57af 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs index 39063f9c1ef..955dde31dfe 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs index 00ab434769c..772027f4fa5 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs index dc1e08bc678..0218395f3a1 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs index 26458fda2df..4de3131b223 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs index 9fcdf500838..99ce575bec3 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs index 55fb9a4c0bd..09eab549426 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs index 895c4e33528..e473f91dfd4 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs index a281d830d78..81cdb8ecc35 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs index f01d5b5ad30..e8112877019 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs index 5d0bd636fa6..cd70dc0a8f1 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs index 2a8da6f00ef..0d56f5640e4 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs index cac4dda1793..4eeab7fcc72 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs index 8dbac01b438..bc1e07b1473 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs index 7b25a749989..c6c3885fb90 100644 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs +++ b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index 100b7dde2d1..7447318f054 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -178,7 +178,7 @@ public static string GetPath(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } else { @@ -205,13 +205,13 @@ public static string GetOwner(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } // Get owner @@ -245,13 +245,13 @@ public static string GetGroup(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } // Get Group @@ -284,13 +284,13 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { - PSTraceSource.NewArgumentException("instance"); + PSTraceSource.NewArgumentException(nameof(instance)); } // Get DACL @@ -323,13 +323,13 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { - PSTraceSource.NewArgumentException("instance"); + PSTraceSource.NewArgumentException(nameof(instance)); } AuthorizationRuleCollection sacl; @@ -585,13 +585,13 @@ public static string GetSddl(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ObjectSecurity sd = instance.BaseObject as ObjectSecurity; if (sd == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } string sddl = sd.GetSecurityDescriptorSddlForm(AccessControlSections.All); diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index f4b1602f2a1..5d094413904 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 7366bccb4d6..28163845d22 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index fa23e31a473..3436ddb6062 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -31,20 +31,18 @@ namespace Microsoft.PowerShell.Commands { /// /// Defines the Certificate Provider dynamic parameters. - /// /// We only support one dynamic parameter for Win 7 and earlier: /// CodeSigningCert /// If provided, we only return certificates valid for signing code or /// scripts. /// - - internal sealed class CertificateProviderCodeSigningDynamicParameters + internal sealed class CertificateProviderDynamicParameters { /// - /// Switch that controls whether we only return + /// Gets or sets a switch that controls whether we only return /// code signing certs. /// - [Parameter()] + [Parameter] public SwitchParameter CodeSigningCert { get { return _codeSigningCert; } @@ -53,6 +51,70 @@ public SwitchParameter CodeSigningCert } private SwitchParameter _codeSigningCert = new SwitchParameter(); + + /// + /// Gets or sets a filter that controls whether we only return + /// data encipherment certs. + /// + [Parameter] + public SwitchParameter DocumentEncryptionCert + { + get; + set; + } + + /// + /// Gets or sets a filter that controls whether we only return + /// server authentication certs. + /// + [Parameter] + public SwitchParameter SSLServerAuthentication + { + get; + set; + } + + /// + /// Gets or sets a filter by DNSName. + /// Expected content is a single DNS Name that may start and/or end + /// with '*': "contoso.com" or "*toso.c*". + /// All WildcardPattern class features supported. + /// + [Parameter] + public string DnsName + { + get; + set; + } + + /// + /// Gets or sets a filter by EKU. + /// Expected content is one or more OID strings: + /// "1.3.6.1.5.5.7.3.1", "*Server*", etc. + /// For a cert to match, it must be valid for all listed OIDs. + /// All WildcardPattern class features supported. + /// + [Parameter] + public string[] Eku + { + get; + set; + } + + /// + /// Gets or sets a filter by the number of valid days. + /// Expected content is a non-negative integer. + /// "0" matches all certs that have already expired. + /// "1" matches all certs that are currently valid and will expire + /// by next day (local time). + /// + [Parameter] + [ValidateRange(ValidateRangeKind.NonNegative)] + public int ExpiringInDays + { + get; + set; + } = -1; } /// @@ -169,7 +231,7 @@ internal sealed class ProviderRemoveItemDynamicParameters /// Switch that controls whether we should delete private key /// when remove a certificate. /// - [Parameter()] + [Parameter] public SwitchParameter DeleteKey { get @@ -506,7 +568,7 @@ public sealed class CertificateProvider : NavigationCmdletProvider, ICmdletProvi /// [TraceSource("CertificateProvider", "The core command provider for certificates")] - private readonly static PSTraceSource s_tracer = PSTraceSource.GetTracer("CertificateProvider", + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CertificateProvider", "The core command provider for certificates"); #endregion tracer @@ -565,6 +627,7 @@ public sealed class CertificateProvider : NavigationCmdletProvider, ICmdletProvi /// this property. /// private static Regex s_certPathRegex = null; + private static Regex CertPathRegex { get @@ -605,7 +668,7 @@ public CertificateProvider() X509StoreLocation user = new X509StoreLocation(StoreLocation.CurrentUser); s_storeLocations.Add(user); - AddItemToCache(StoreLocation.CurrentUser.ToString(), + AddItemToCache(nameof(StoreLocation.CurrentUser), user); // @@ -614,7 +677,7 @@ public CertificateProvider() X509StoreLocation machine = new X509StoreLocation(StoreLocation.LocalMachine); s_storeLocations.Add(machine); - AddItemToCache(StoreLocation.LocalMachine.ToString(), + AddItemToCache(nameof(StoreLocation.LocalMachine), machine); AddItemToCache(string.Empty, s_storeLocations); @@ -1184,15 +1247,11 @@ protected override void GetItem(string path) } else { - // The filter is non null. If the certificate - // satisfies the filter, output it. Otherwise, don't. - + // The filter is non null. If the certificate + // satisfies the filter, output it. Otherwise, don't. X509Certificate2 cert = item as X509Certificate2; Dbg.Diagnostics.Assert(cert != null, "item should be a certificate"); - // If it's Win8 or above, filter matching for certain properties is done by - // the certificate enumeration filter at the API level. In that case, - // filter.Purpose will be 'None' and MatchesFilter will return 'True'. if (MatchesFilter(cert, filter)) { WriteItemObject(item, path, isContainer); @@ -1324,7 +1383,7 @@ private string MyGetChildName(string path) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Normalize the path @@ -2211,7 +2270,7 @@ protected override bool IsItemContainer(string path) /// protected override object GetItemDynamicParameters(string path) { - return new CertificateProviderCodeSigningDynamicParameters(); + return new CertificateProviderDynamicParameters(); } /// @@ -2233,7 +2292,7 @@ protected override object GetItemDynamicParameters(string path) /// protected override object GetChildItemsDynamicParameters(string path, bool recurse) { - return new CertificateProviderCodeSigningDynamicParameters(); + return new CertificateProviderDynamicParameters(); } #endregion DriveCmdletProvider overrides @@ -2606,8 +2665,8 @@ private CertificateFilterInfo GetFilter() if (DynamicParameters != null) { - CertificateProviderCodeSigningDynamicParameters dp = - DynamicParameters as CertificateProviderCodeSigningDynamicParameters; + CertificateProviderDynamicParameters dp = + DynamicParameters as CertificateProviderDynamicParameters; if (dp != null) { if (dp.CodeSigningCert) @@ -2615,6 +2674,40 @@ private CertificateFilterInfo GetFilter() filter = new CertificateFilterInfo(); filter.Purpose = CertificatePurpose.CodeSigning; } + + if (dp.DocumentEncryptionCert) + { + filter = filter ?? new CertificateFilterInfo(); + filter.Purpose = CertificatePurpose.DocumentEncryption; + } + + if (dp.DnsName != null) + { + filter = filter ?? new CertificateFilterInfo(); + filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase); + } + + if (dp.Eku != null) + { + filter = filter ?? new CertificateFilterInfo(); + filter.Eku = new List(); + foreach (var pattern in dp.Eku) + { + filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase)); + } + } + + if (dp.ExpiringInDays >= 0) + { + filter = filter ?? new CertificateFilterInfo(); + filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays); + } + + if (dp.SSLServerAuthentication) + { + filter = filter ?? new CertificateFilterInfo(); + filter.SSLServerAuthentication = true; + } } } @@ -2633,42 +2726,131 @@ private bool IncludeArchivedCerts() return includeArchivedCerts; } - // If it's Win8 or above, filter matching for certain properties is done by - // the certificate enumeration filter at the API level. In that case, - // filter.Purpose will be 'None' and MatchesFilter will return 'True'. - private static bool MatchesFilter(X509Certificate2 cert, - CertificateFilterInfo filter) + private static bool MatchesFilter(X509Certificate2 cert, CertificateFilterInfo filter) { - // - // no filter means, match everything - // - if ((filter == null) || - (filter.Purpose == CertificatePurpose.NotSpecified) || - (filter.Purpose == CertificatePurpose.All)) + // No filter means, match everything + if (filter == null) { return true; } + if (filter.Expiring > DateTime.MinValue && !SecuritySupport.CertExpiresByTime(cert, filter.Expiring)) + { + return false; + } + + if (filter.DnsName != null && !CertContainsName(cert, filter.DnsName)) + { + return false; + } + + if (filter.Eku != null && !CertContainsEku(cert, filter.Eku)) + { + return false; + } + + if (filter.SSLServerAuthentication && !CertIsSSLServerAuthentication(cert)) + { + return false; + } + switch (filter.Purpose) { case CertificatePurpose.CodeSigning: - if (SecuritySupport.CertIsGoodForSigning(cert)) - { - return true; - } + return SecuritySupport.CertIsGoodForSigning(cert); + + case CertificatePurpose.DocumentEncryption: + return SecuritySupport.CertIsGoodForEncryption(cert); + case CertificatePurpose.NotSpecified: + case CertificatePurpose.All: + return true; + + default: break; + } - case CertificatePurpose.DocumentEncryption: - if (SecuritySupport.CertIsGoodForEncryption(cert)) + return false; + } + + /// + /// Check if the specified certificate has the name in DNS name list. + /// + /// Certificate object. + /// Wildcard pattern for DNS name to search. + /// True on success, false otherwise. + internal static bool CertContainsName(X509Certificate2 cert, WildcardPattern pattern) + { + List list = (new DnsNameProperty(cert)).DnsNameList; + foreach (DnsNameRepresentation dnsName in list) + { + if (pattern.IsMatch(dnsName.Unicode)) + { + return true; + } + } + + return false; + } + + /// + /// Check if the specified certificate is a server authentication certificate. + /// + /// Certificate object. + /// True on success, false otherwise. + internal static bool CertIsSSLServerAuthentication(X509Certificate2 cert) + { + X509ExtensionCollection extentionList = cert.Extensions; + foreach (var extension in extentionList) + { + if (extension is X509EnhancedKeyUsageExtension eku) + { + foreach (Oid usage in eku.EnhancedKeyUsages) { - return true; + if (usage.Value.Equals(CertificateFilterInfo.OID_PKIX_KP_SERVER_AUTH, StringComparison.Ordinal)) + { + return true; + } } + } + } - break; + return false; + } - default: - break; + /// + /// Check if the specified certificate contains EKU matching all of these patterns. + /// + /// Certificate object. + /// EKU patterns. + /// True on success, false otherwise. + internal static bool CertContainsEku(X509Certificate2 cert, List ekuPatterns) + { + X509ExtensionCollection extensionList = cert.Extensions; + foreach (var extension in extensionList) + { + if (extension is X509EnhancedKeyUsageExtension eku) + { + OidCollection enhancedKeyUsages = eku.EnhancedKeyUsages; + foreach (WildcardPattern ekuPattern in ekuPatterns) + { + bool patternPassed = false; + foreach (var usage in enhancedKeyUsages) + { + if (ekuPattern.IsMatch(usage.Value) || ekuPattern.IsMatch(usage.FriendlyName)) + { + return true; + } + } + + if (!patternPassed) + { + return false; + } + } + + return true; + } } return false; @@ -3093,6 +3275,7 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin } private static readonly char[] s_separators = new char[] { '/', '\\' }; + private static string[] GetPathElements(string path) { string[] allElts = path.Split(s_separators); @@ -3177,6 +3360,7 @@ public sealed class DnsNameProperty { private List _dnsList = new List(); private System.Globalization.IdnMapping idnMapping = new System.Globalization.IdnMapping(); + private const string dnsNamePrefix = "DNS Name="; private const string distinguishedNamePrefix = "CN="; @@ -3192,7 +3376,7 @@ public List DnsNameList } /// - /// Constructor for EkuList. + /// Constructor for DnsNameProperty. /// public DnsNameProperty(X509Certificate2 cert) { @@ -3383,7 +3567,7 @@ internal static class Crypt32Helpers /// private static object s_staticLock = new object(); - internal static List storeNames = new List(); + internal static readonly List storeNames = new List(); /// /// Get a list of store names at the specified location. diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 6a7502f7a7d..4c90c02e941 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs index 3fbe9bd237c..cb23979c77f 100644 --- a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs b/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs index 80d125b0f5e..7924fcd7652 100644 --- a/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives @@ -233,10 +233,8 @@ protected override void ProcessRecord() } } -#if !CORECLR PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(Context, MyInvocation), EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null); -#endif } } diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 85ecca4d029..74dee890cdf 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 789ae2fa014..91a3e8e3a83 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -555,7 +555,7 @@ protected override Signature PerformAction(string filePath) System.Globalization.CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, filePath); - PSArgumentException e = new PSArgumentException(message, "filePath"); + PSArgumentException e = new PSArgumentException(message, nameof(filePath)); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SignatureCommandsBaseFileSmallerThan4Bytes" diff --git a/src/Microsoft.PowerShell.Security/security/Utils.cs b/src/Microsoft.PowerShell.Security/security/Utils.cs index 75481ff292f..f8eb7243285 100644 --- a/src/Microsoft.PowerShell.Security/security/Utils.cs +++ b/src/Microsoft.PowerShell.Security/security/Utils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs index 4eb3838f5ea..efd205e5769 100644 --- a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs +++ b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs index 1460cb8a184..efc4ec63daa 100644 --- a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs +++ b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index bc6b961adc6..326f53d4d94 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -24,7 +24,7 @@ namespace Microsoft.WSMan.Management /// WsMan Provider. /// [CmdletProvider(WSManStringLiterals.ProviderName, ProviderCapabilities.Credentials)] - public sealed partial class WSManConfigProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp + public sealed class WSManConfigProvider : NavigationCmdletProvider, ICmdletProviderSupportsHelp { // Plugin Name Storage private PSObject objPluginNames = null; @@ -38,17 +38,17 @@ public sealed partial class WSManConfigProvider : NavigationCmdletProvider, ICmd /// private bool clearItemIsCalled = false; - WSManHelper helper = new WSManHelper(); + private WSManHelper helper = new WSManHelper(); /// /// Object contains the cache of the enumerate results for the cmdlet to execute. /// - Dictionary enumerateMapping = new Dictionary(); + private Dictionary enumerateMapping = new Dictionary(); /// /// Mapping of ResourceURI with the XML returned by the Get call. /// - Dictionary getMapping = new Dictionary(); + private Dictionary getMapping = new Dictionary(); #region ICmdletProviderSupportsHelp Members @@ -823,7 +823,7 @@ protected override void GetItem(string path) try { PSObject mshObject = null; - if (!uri.Equals(WinrmRootName[0].ToString(), StringComparison.OrdinalIgnoreCase)) + if (!uri.Equals(WinrmRootName[0], StringComparison.OrdinalIgnoreCase)) { foreach (XmlNode innerResourceNodes in xmlResource.ChildNodes) { @@ -1977,8 +1977,8 @@ private void NewItemCreateComputerConnection(string Name) helper.CreateWsManConnection(parametersetName, dynParams.ConnectionURI, dynParams.Port, Name, dynParams.ApplicationName, dynParams.UseSSL, dynParams.Authentication, dynParams.SessionOption, this.Credential, dynParams.CertificateThumbprint); if (dynParams.ConnectionURI != null) { - string[] constrsplit = dynParams.ConnectionURI.OriginalString.Split(new string[] { ":" + dynParams.Port + "/" + dynParams.ApplicationName }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = dynParams.ConnectionURI.OriginalString.Split(":" + dynParams.Port + "/" + dynParams.ApplicationName, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); Name = constrsplit1[1].Trim(); } @@ -2259,7 +2259,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h inputStr = ConstructPluginXml(ps, uri, host, "Set", ResourceArray, SecurityArray, InitParamArray); try { - ((IWSManSession)sessionobj).Put(uri + "?" + "Name=" + pName, inputStr.ToString(), 0); + ((IWSManSession)sessionobj).Put(uri + "?" + "Name=" + pName, inputStr, 0); if (path.EndsWith(strPathChk + WSManStringLiterals.containerInitParameters, StringComparison.OrdinalIgnoreCase)) { WriteItemObject(GetItemPSObjectWithTypeName(mshObj.Properties[NewItem].Name, mshObj.Properties[NewItem].TypeNameOfValue, mshObj.Properties[NewItem].Value, null, "InitParams", WsManElementObjectTypes.WSManConfigLeafElement), path + WSManStringLiterals.DefaultPathSeparator + mshObj.Properties[NewItem].Name, false); @@ -2526,9 +2526,9 @@ private string GetHostName(string path) private string GetRootNodeName(string ResourceURI) { string tempuri = string.Empty; - if (ResourceURI.Contains("?")) + if (ResourceURI.Contains('?')) { - ResourceURI = ResourceURI.Split(new char[] { '?' }).GetValue(0).ToString(); + ResourceURI = ResourceURI.Split('?').GetValue(0).ToString(); } string PTRN_URI_LAST = "([a-z_][-a-z0-9._]*)$"; @@ -2536,7 +2536,7 @@ private string GetRootNodeName(string ResourceURI) MatchCollection regexmatch = objregex.Matches(ResourceURI); if (regexmatch.Count > 0) { - tempuri = regexmatch[0].Value.ToString(); + tempuri = regexmatch[0].Value; } return tempuri; @@ -2686,7 +2686,7 @@ private void PutResourceValue(object sessionobj, string ResourceURI, Hashtable v if (Itemfound) { ResourceURI = GetURIWithFilter(ResourceURI, value); - ((IWSManSession)sessionobj).Put(ResourceURI, node.OuterXml.ToString(), 0); + ((IWSManSession)sessionobj).Put(ResourceURI, node.OuterXml, 0); } else { @@ -3164,8 +3164,8 @@ private string SplitAndUpdateStringUsingDelimiter(object sessionobj, string uri, if (!string.IsNullOrEmpty(existingvalue)) { - string[] existingsplitvalues = existingvalue.Split(new string[] { Delimiter }, StringSplitOptions.None); - string[] newvalues = value.Split(new string[] { Delimiter }, StringSplitOptions.None); + string[] existingsplitvalues = existingvalue.Split(Delimiter, StringSplitOptions.None); + string[] newvalues = value.Split(Delimiter, StringSplitOptions.None); foreach (string val in newvalues) { if (Array.IndexOf(existingsplitvalues, val) == -1) @@ -3336,7 +3336,7 @@ private string SetSchemaPath(string uri) /// private string NormalizePath(string path, string host) { - string uri = string.Empty; ; + string uri = string.Empty; if (path.StartsWith(host, StringComparison.OrdinalIgnoreCase)) { if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) @@ -3344,7 +3344,7 @@ private string NormalizePath(string path, string host) if (path.Equals(host, StringComparison.OrdinalIgnoreCase)) { - uri = WinrmRootName[0].ToString(); + uri = WinrmRootName[0]; return uri; } @@ -3353,19 +3353,19 @@ private string NormalizePath(string path, string host) string host_prefix = host + WSManStringLiterals.DefaultPathSeparator; if (path.StartsWith(host_prefix + WSManStringLiterals.containerClientCertificate, StringComparison.OrdinalIgnoreCase)) { - uri = WinrmRootName[0].ToString() + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerCertMapping; + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerCertMapping; } else if (path.StartsWith(host_prefix + WSManStringLiterals.containerPlugin, StringComparison.OrdinalIgnoreCase)) { - uri = WinrmRootName[0].ToString() + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerPlugin; + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerPlugin; } else if (path.StartsWith(host_prefix + WSManStringLiterals.containerShell, StringComparison.OrdinalIgnoreCase)) { - uri = WinrmRootName[0].ToString() + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerWinrs; + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerWinrs; } else if (path.StartsWith(host_prefix + WSManStringLiterals.containerListener, StringComparison.OrdinalIgnoreCase)) { - uri = WinrmRootName[0].ToString() + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerListener; + uri = WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerListener; } else { @@ -3380,7 +3380,7 @@ private string NormalizePath(string path, string host) } } - uri = WinrmRootName[0].ToString() + uri; + uri = WinrmRootName[0] + uri; } return uri; @@ -3795,7 +3795,6 @@ private void GetItemListenerOrCertMapping(string path, XmlDocument xmlResource, if (path.EndsWith(host + WSManStringLiterals.DefaultPathSeparator + ContainerListenerOrClientCert, StringComparison.OrdinalIgnoreCase)) { if (Objcache.ContainsKey(childname)) - WriteItemObject(GetItemPSObjectWithTypeName(childname, WSManStringLiterals.ContainerChildValue, null, (string[])Keyscache[childname], null, WsManElementObjectTypes.WSManConfigContainerElement), path + WSManStringLiterals.DefaultPathSeparator + childname, true); } else @@ -4105,7 +4104,7 @@ private bool ItemExistListenerOrClientCertificate(object sessionobj, string Reso PSObject obj = (PSObject)objcache[CurrentNode]; CurrentNode = RemainingPath.Substring(pos + 1); - if (CurrentNode.IndexOf(WSManStringLiterals.DefaultPathSeparator) != -1) + if (CurrentNode.Contains(WSManStringLiterals.DefaultPathSeparator)) { // No more directories allowed after listeners objects return false; @@ -5431,13 +5430,13 @@ private bool IsValueOfParamList(string name, string[] paramcontainer) #endregion Plugin private functions - enum ProviderMethods + private enum ProviderMethods { GetChildItems, GetChildNames }; - enum WsManElementObjectTypes + private enum WsManElementObjectTypes { WSManConfigElement, WSManConfigContainerElement, @@ -5446,6 +5445,7 @@ enum WsManElementObjectTypes #region def private static readonly string[] WinrmRootName = new string[] { "winrm/Config" }; + private static readonly string[] WinRmRootConfigs = new string[] { "Client", "Service", @@ -5490,8 +5490,8 @@ enum WsManElementObjectTypes /// private static readonly List globalWarningUris = new List { - WinrmRootName[0].ToString() + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerWinrs, - WinrmRootName[0].ToString() + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerService}; + WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerWinrs, + WinrmRootName[0] + WSManStringLiterals.WinrmPathSeparator + WSManStringLiterals.containerService}; #endregion def diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index 60cfe742767..52c4f4e921d 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -480,7 +480,6 @@ protected override void BeginProcessing() } } - #endregion /// @@ -665,17 +664,13 @@ private void UpdateGPORegistrySettings(string applicationname, string[] delegate { string Registry_Path_Credentials_Delegation = Registry_Path + @"\CredentialsDelegation"; // open the registry key.If key is not present,create a new one - Credential_Delegation_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true); - if (Credential_Delegation_Key == null) - Credential_Delegation_Key = rootKey.CreateSubKey(Registry_Path_Credentials_Delegation, RegistryKeyPermissionCheck.ReadWriteSubTree); + Credential_Delegation_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation, RegistryKeyPermissionCheck.ReadWriteSubTree); Credential_Delegation_Key.SetValue(helper.Key_Allow_Fresh_Credentials, 1, RegistryValueKind.DWord); Credential_Delegation_Key.SetValue(helper.Key_Concatenate_Defaults_AllowFresh, 1, RegistryValueKind.DWord); // add the delegate value - Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true); - if (Allow_Fresh_Credential_Key == null) - Allow_Fresh_Credential_Key = rootKey.CreateSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, RegistryKeyPermissionCheck.ReadWriteSubTree); + Allow_Fresh_Credential_Key = rootKey.OpenSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, true) ?? rootKey.CreateSubKey(Registry_Path_Credentials_Delegation + @"\" + helper.Key_Allow_Fresh_Credentials, RegistryKeyPermissionCheck.ReadWriteSubTree); if (Allow_Fresh_Credential_Key != null) { @@ -751,7 +746,7 @@ private void UpdateGPORegistrySettings(string applicationname, string[] delegate public class GetWSManCredSSPCommand : PSCmdlet, IDisposable { #region private - WSManHelper helper = null; + private WSManHelper helper = null; /// /// Method to get the values. /// diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 41427678150..01ba71f68a7 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -63,7 +63,7 @@ public CurrentConfigurations(IWSManSession serverSession) { if (serverSession == null) { - throw new ArgumentNullException("serverSession"); + throw new ArgumentNullException(nameof(serverSession)); } this.rootDocument = new XmlDocument(); @@ -81,7 +81,7 @@ public bool RefreshCurrentConfiguration(string responseOfGet) { if (string.IsNullOrEmpty(responseOfGet)) { - throw new ArgumentNullException("responseOfGet"); + throw new ArgumentNullException(nameof(responseOfGet)); } this.rootDocument.LoadXml(responseOfGet); @@ -103,7 +103,7 @@ public void PutConfigurationOnServer(string resourceUri) { if (string.IsNullOrEmpty(resourceUri)) { - throw new ArgumentNullException("resourceUri"); + throw new ArgumentNullException(nameof(resourceUri)); } this.serverSession.Put(resourceUri, this.rootDocument.InnerXml, 0); @@ -119,7 +119,7 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) { if (pathToNodeFromRoot == null) { - throw new ArgumentNullException("pathToNodeFromRoot"); + throw new ArgumentNullException(nameof(pathToNodeFromRoot)); } XmlNode nodeToRemove = @@ -136,7 +136,7 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) } else { - throw new ArgumentException("Node is not present in the XML, Please give valid XPath", "pathToNodeFromRoot"); + throw new ArgumentException("Node is not present in the XML, Please give valid XPath", nameof(pathToNodeFromRoot)); } } @@ -152,17 +152,17 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati { if (pathToNodeFromRoot == null) { - throw new ArgumentNullException("pathToNodeFromRoot"); + throw new ArgumentNullException(nameof(pathToNodeFromRoot)); } if (string.IsNullOrEmpty(configurationName)) { - throw new ArgumentNullException("configurationName"); + throw new ArgumentNullException(nameof(configurationName)); } if (configurationValue == null) { - throw new ArgumentNullException("configurationValue"); + throw new ArgumentNullException(nameof(configurationValue)); } XmlNode nodeToUpdate = @@ -197,7 +197,7 @@ public string GetOneConfiguration(string pathFromRoot) { if (pathFromRoot == null) { - throw new ArgumentNullException("pathFromRoot"); + throw new ArgumentNullException(nameof(pathFromRoot)); } XmlNode requiredNode = diff --git a/src/Microsoft.WSMan.Management/Interop.cs b/src/Microsoft.WSMan.Management/Interop.cs index d9394f4a941..7df5d16fc93 100644 --- a/src/Microsoft.WSMan.Management/Interop.cs +++ b/src/Microsoft.WSMan.Management/Interop.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1056,7 +1056,7 @@ public class GPClass [ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - interface IGroupPolicyObject + internal interface IGroupPolicyObject { void New( [MarshalAs(UnmanagedType.LPWStr)] string pszDomainName, diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 88657b30a30..71f8ae4c84d 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -245,9 +245,9 @@ public Uri ResourceURI private Uri resourceuri; private WSManHelper helper; - IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); - IWSManSession m_session = null; - string connectionStr = string.Empty; + private IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + private IWSManSession m_session = null; + private string connectionStr = string.Empty; /// /// BeginProcessing method. diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 02720796dab..835e26b2cf0 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -9,7 +9,7 @@ - + diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 73ea9f68c53..b2d6719e7e9 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index 5603f9882e3..9581eaabc33 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs index 484247a2e5a..c318ea76477 100644 --- a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs +++ b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -233,7 +233,7 @@ private void QuickConfigRemoting(bool serviceonly) xpathResult = "/cfg:EnableRemoting_OUTPUT/cfg:Results"; } - if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.ToString().Equals("succeeded")) + if (finalxml.SelectSingleNode(xpathStatus, nsmgr).InnerText.Equals("succeeded")) { if (serviceonly) { diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 3453c5cffa0..4aeb283b81f 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -259,8 +259,8 @@ protected override void BeginProcessing() try { // always in the format http://server:port/applicationname - string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) @@ -269,11 +269,7 @@ protected override void BeginProcessing() } } - string crtComputerName = computername; - if (crtComputerName == null) - { - crtComputerName = "localhost"; - } + string crtComputerName = computername ?? "localhost"; if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(this.SessionState.Drive.Current.Name + ":" + WSManStringLiterals.DefaultPathSeparator + crtComputerName, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index b0873b6d1d9..5a3d6b74f7f 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -397,7 +397,8 @@ public SwitchParameter UseSSL #endregion parameter # region private - WSManHelper helper; + private WSManHelper helper; + private string GetFilter() { string name; @@ -418,7 +419,7 @@ private string GetFilter() } filter = filter + ""; - return (filter.ToString()); + return (filter); } private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) @@ -528,8 +529,8 @@ protected override void ProcessRecord() try { // in the format http(s)://server[:port/applicationname] - string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) @@ -908,8 +909,8 @@ protected override void ProcessRecord() try { // in the format http(s)://server[:port/applicationname] - string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) @@ -1202,8 +1203,8 @@ protected override void ProcessRecord() try { // in the format http(s)://server[:port/applicationname] - string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) @@ -1474,9 +1475,9 @@ public Hashtable ValueSet private Hashtable valueset; private WSManHelper helper; - IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); - IWSManSession m_session = null; - string connectionStr = string.Empty; + private IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); + private IWSManSession m_session = null; + private string connectionStr = string.Empty; /// /// BeginProcessing method. @@ -1491,8 +1492,8 @@ protected override void BeginProcessing() try { // in the format http(s)://server[:port/applicationname] - string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 81762a099f9..f09ba2bb233 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -94,7 +94,7 @@ internal class Sessions /// /// Dictionary object to store the connection. /// - internal static Dictionary SessionObjCache = new Dictionary(); + internal static readonly Dictionary SessionObjCache = new Dictionary(); ~Sessions() { @@ -102,7 +102,7 @@ internal class Sessions } } - internal static Sessions AutoSession = new Sessions(); + internal static readonly Sessions AutoSession = new Sessions(); // // // @@ -180,12 +180,12 @@ private static string FormatResourceMsgFromResourcetextS( { if (resourceManager == null) { - throw new ArgumentNullException("resourceManager"); + throw new ArgumentNullException(nameof(resourceManager)); } if (string.IsNullOrEmpty(resourceName)) { - throw new ArgumentNullException("resourceName"); + throw new ArgumentNullException(nameof(resourceName)); } string template = resourceManager.GetString(resourceName); @@ -478,7 +478,7 @@ internal string ProcessInput(IWSManEx wsman, string filepath, string operation, if (string.IsNullOrEmpty(entry.Key.ToString())) { // XmlNode newnode = xmlfile.CreateNode(XmlNodeType.Attribute, ATTR_NIL_NAME, NS_XSI_URI); - XmlAttribute newnode = xmlfile.CreateAttribute(XmlNodeType.Attribute.ToString(), ATTR_NIL_NAME, NS_XSI_URI); + XmlAttribute newnode = xmlfile.CreateAttribute(nameof(XmlNodeType.Attribute), ATTR_NIL_NAME, NS_XSI_URI); newnode.Value = "true"; node.Attributes.Append(newnode); // (newnode.Attributes.Item(0).FirstChild ); @@ -953,18 +953,14 @@ internal void CreateWsManConnection(string ParameterSetName, Uri connectionuri, if (connectionuri != null) { // in the format http(s)://server[:port/applicationname] - string[] constrsplit = connectionStr.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); - string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); + string[] constrsplit = connectionStr.Split(":" + port + "/" + applicationname, StringSplitOptions.None); + string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } IWSManSession m_session = CreateSessionObject(m_wsmanObject, authentication, sessionoption, credential, connectionStr, certificateThumbprint, usessl); m_session.Identify(0); - string key = computername; - if (key == null) - { - key = "localhost"; - } + string key = computername ?? "localhost"; AddtoDictionary(key, m_session); } @@ -1032,7 +1028,7 @@ internal bool ValidateCredSSPRegistry(bool AllowFreshCredentialsValueShouldBePre } string[] valuenames = rGPOLocalMachineKey.GetValueNames(); - if (valuenames.Length <= 0) + if (valuenames.Length == 0) { return !AllowFreshCredentialsValueShouldBePresent; } @@ -1098,19 +1094,19 @@ internal static void LoadResourceData() string Line = _sr.ReadLine(); if (Line.Contains("=")) { - string[] arr = Line.Split(new char[] { '=' }, 2); + string[] arr = Line.Split('=', count: 2); if (!ResourceValueCache.ContainsKey(arr[0].Trim())) { - string value = arr[1].TrimStart(new char[] { '"' }).TrimEnd(new char[] { '"' }); + string value = arr[1].Trim('"'); ResourceValueCache.Add(arr[0].Trim(), value.Trim()); } } } } } - catch (IOException e) + catch (IOException) { - throw (e); + throw; } } @@ -1123,7 +1119,7 @@ internal static void LoadResourceData() internal static string GetResourceString(string Key) { // Checks whether resource values already loaded and loads. - if (ResourceValueCache.Count <= 0) + if (ResourceValueCache.Count == 0) { LoadResourceData(); } diff --git a/src/Microsoft.WSMan.Management/WsManSnapin.cs b/src/Microsoft.WSMan.Management/WsManSnapin.cs index 903d02c7784..4093caf12db 100644 --- a/src/Microsoft.WSMan.Management/WsManSnapin.cs +++ b/src/Microsoft.WSMan.Management/WsManSnapin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Microsoft.WSMan.Management/resources/WsManResources.txt b/src/Microsoft.WSMan.Management/resources/WsManResources.txt index 61be75be118..50cf1bf1fe5 100644 --- a/src/Microsoft.WSMan.Management/resources/WsManResources.txt +++ b/src/Microsoft.WSMan.Management/resources/WsManResources.txt @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # {0} = Delegate diff --git a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs index 42c684a9c8d..014cc03c8ec 100644 --- a/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs +++ b/src/Microsoft.WSMan.Runtime/WSManSessionOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/Modules/PSGalleryModules.csproj b/src/Modules/PSGalleryModules.csproj index 8d1e2e5cdb0..613e3d5ce49 100644 --- a/src/Modules/PSGalleryModules.csproj +++ b/src/Modules/PSGalleryModules.csproj @@ -3,10 +3,10 @@ - - - - + + + + diff --git a/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 b/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 index 3dfba7c32e6..0270ceffca0 100644 --- a/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 +++ b/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 @@ -2,7 +2,7 @@ GUID="56D66100-99A0-4FFC-A12D-EEE9A6718AEF" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" @@ -10,5 +10,5 @@ FunctionsToExport = @() CmdletsToExport="Start-Transcript", "Stop-Transcript" AliasesToExport = @() NestedModules="Microsoft.PowerShell.ConsoleHost.dll" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113538' +HelpInfoURI = 'https://aka.ms/powershell71-help' } diff --git a/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 index e69dfe1a0d6..da8f8707945 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -2,12 +2,12 @@ GUID="EEFCB906-B326-4E99-9F54-8B4BB6EF3C6D" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" NestedModules="Microsoft.PowerShell.Commands.Management.dll" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113632' +HelpInfoURI = 'https://aka.ms/powershell71-help' FunctionsToExport = @() AliasesToExport = @("gcb", "gtz", "scb") CmdletsToExport=@("Add-Content", diff --git a/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 index d5961d1008d..1f4cc15e118 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 @@ -2,13 +2,13 @@ GUID="A94C8C7E-9810-47C0-B8AF-65089C13A35A" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" FunctionsToExport = @() -CmdletsToExport="Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "ConvertFrom-SecureString", "ConvertTo-SecureString", "Get-PfxCertificate" +CmdletsToExport="Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "ConvertFrom-SecureString", "ConvertTo-SecureString", "Get-PfxCertificate" , "Protect-CmsMessage", "Unprotect-CmsMessage", "Get-CmsMessage" AliasesToExport = @() NestedModules="Microsoft.PowerShell.Security.dll" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113533' +HelpInfoURI = 'https://aka.ms/powershell71-help' } 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 eb9299a4807..33823700f7f 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -2,7 +2,7 @@ GUID = "1DA87E53-152B-403E-98DC-74D7B4D63D59" Author = "PowerShell" CompanyName = "Microsoft Corporation" -Copyright = "Copyright (c) Microsoft Corporation. All rights reserved." +Copyright = "Copyright (c) Microsoft Corporation." ModuleVersion = "7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion = "3.0" @@ -30,7 +30,7 @@ CmdletsToExport = @( FunctionsToExport = @() AliasesToExport = @('fhx') NestedModules = @("Microsoft.PowerShell.Commands.Utility.dll") -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113633' +HelpInfoURI = 'https://aka.ms/powershell71-help' PrivateData = @{ PSData = @{ ExperimentalFeatures = @( diff --git a/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 b/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 index f7a0f18400e..4b38d4abc9e 100644 --- a/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 +++ b/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 @@ -2,7 +2,7 @@ GUID="{Fb6cc51d-c096-4b38-b78d-0fed6277096a}" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" @@ -14,5 +14,5 @@ CmdletsToExport= "Get-CimAssociatedInstance", "Get-CimClass", "Get-CimInstance", "Remove-CimSession","Set-CimInstance", "Export-BinaryMiLog","Import-BinaryMiLog" AliasesToExport = "gcim","scim","ncim", "rcim","icim","gcai","rcie","ncms","rcms","gcms","ncso","gcls" -HelpInfoUri="https://go.microsoft.com/fwlink/?linkid=2113536" +HelpInfoUri="https://aka.ms/powershell71-help" } diff --git a/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml b/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml index 95386960921..e63a9b56d94 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml +++ b/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/GetEvent.types.ps1xml @@ -5,7 +5,7 @@ PowerShell engine. Do not edit or change the contents of this file directly. Please see the PowerShell documentation or type Get-Help Update-TypeData for more information. -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. THIS SAMPLE CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO diff --git a/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 index 8907dd40417..ed2344b51b2 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 @@ -2,7 +2,7 @@ GUID="CA046F10-CA64-4740-8FF9-2565DBA61A4F" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" @@ -12,5 +12,5 @@ AliasesToExport = @() NestedModules="Microsoft.PowerShell.Commands.Diagnostics.dll" TypesToProcess="GetEvent.types.ps1xml" FormatsToProcess="Event.format.ps1xml", "Diagnostics.format.ps1xml" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113532' +HelpInfoURI = 'https://aka.ms/powershell71-help' } diff --git a/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 index 34328bb14aa..f7cd1dc6ace 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -2,12 +2,12 @@ GUID="EEFCB906-B326-4E99-9F54-8B4BB6EF3C6D" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" NestedModules="Microsoft.PowerShell.Commands.Management.dll" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113632' +HelpInfoURI = 'https://aka.ms/powershell71-help' FunctionsToExport = @() AliasesToExport = @("gcb", "gin", "gtz", "scb", "stz") CmdletsToExport=@("Add-Content", diff --git a/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 index 2873dbc3ecc..cbc5b2dc78e 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 @@ -2,7 +2,7 @@ GUID="A94C8C7E-9810-47C0-B8AF-65089C13A35A" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" @@ -10,5 +10,5 @@ FunctionsToExport = @() CmdletsToExport="Get-Acl", "Set-Acl", "Get-PfxCertificate", "Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "Get-AuthenticodeSignature", "Set-AuthenticodeSignature", "ConvertFrom-SecureString", "ConvertTo-SecureString", "Get-CmsMessage", "Unprotect-CmsMessage", "Protect-CmsMessage" , "New-FileCatalog" , "Test-FileCatalog" AliasesToExport = @() NestedModules="Microsoft.PowerShell.Security.dll" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113533' +HelpInfoURI = 'https://aka.ms/powershell71-help' } 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 e3d4643c855..cd12b64d034 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -2,7 +2,7 @@ GUID = "1DA87E53-152B-403E-98DC-74D7B4D63D59" Author = "PowerShell" CompanyName = "Microsoft Corporation" -Copyright = "Copyright (c) Microsoft Corporation. All rights reserved." +Copyright = "Copyright (c) Microsoft Corporation." ModuleVersion = "7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion = "3.0" @@ -29,7 +29,7 @@ CmdletsToExport = @( FunctionsToExport = @() AliasesToExport = @('fhx') NestedModules = @("Microsoft.PowerShell.Commands.Utility.dll") -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113633' +HelpInfoURI = 'https://aka.ms/powershell71-help' PrivateData = @{ PSData = @{ ExperimentalFeatures = @( diff --git a/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 b/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 index d3d84d7c409..d2bb2398541 100644 --- a/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 +++ b/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 @@ -2,7 +2,7 @@ GUID="766204A6-330E-4263-A7AB-46C87AFC366C" Author="PowerShell" CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation. All rights reserved." +Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" @@ -11,5 +11,5 @@ CmdletsToExport="Disable-WSManCredSSP", "Enable-WSManCredSSP", "Get-WSManCredSSP AliasesToExport = @() NestedModules="Microsoft.WSMan.Management.dll" FormatsToProcess="WSMan.format.ps1xml" -HelpInfoURI = 'https://go.microsoft.com/fwlink/?linkid=2113537' +HelpInfoURI = 'https://aka.ms/powershell71-help' } diff --git a/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml b/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml index 71a30b7dec5..bbee94971d5 100644 --- a/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml +++ b/src/Modules/Windows/Microsoft.WSMan.Management/WSMan.format.ps1xml @@ -5,7 +5,7 @@ PowerShell engine. Do not edit or change the contents of this file directly. Please see the PowerShell documentation or type Get-Help Update-FormatData for more information. -Copyright (c) Microsoft Corporation. All rights reserved. +Copyright (c) Microsoft Corporation. THIS SAMPLE CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO diff --git a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 index f5fc194f503..dded04d4920 100644 --- a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 +++ b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 @@ -2,7 +2,7 @@ GUID="c61d6278-02a3-4618-ae37-a524d40a7f44 " Author="PowerShell" CompanyName="Microsoft Corporation" - Copyright="Copyright (c) Microsoft Corporation. All rights reserved." + Copyright="Copyright (c) Microsoft Corporation." ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" @@ -10,5 +10,5 @@ FunctionsToExport="Disable-PSTrace","Disable-PSWSManCombinedTrace","Disable-WSManTrace","Enable-PSTrace","Enable-PSWSManCombinedTrace","Enable-WSManTrace","Get-LogProperties","Set-LogProperties","Start-Trace","Stop-Trace" CmdletsToExport = @() AliasesToExport = @() - HelpInfoUri="https://go.microsoft.com/fwlink/?linkid=2113635" + HelpInfoUri="https://aka.ms/powershell71-help" } diff --git a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 index ecfdb1364d4..ce0739eb622 100644 --- a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 +++ b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. <# @@ -130,35 +130,35 @@ function Enable-WSManTrace { # winrm - "{04c6e16d-b99f-4a3a-9b3e-b8325bbc781e} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii + "{04c6e16d-b99f-4a3a-9b3e-b8325bbc781e} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii # winrsmgr - "{c0a36be8-a515-4cfa-b2b6-2676366efff7} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{c0a36be8-a515-4cfa-b2b6-2676366efff7} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append # WinrsExe - "{f1cab2c0-8beb-4fa2-90e1-8f17e0acdd5d} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{f1cab2c0-8beb-4fa2-90e1-8f17e0acdd5d} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append # WinrsCmd - "{03992646-3dfe-4477-80e3-85936ace7abb} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{03992646-3dfe-4477-80e3-85936ace7abb} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append # IPMIPrv - "{651d672b-e11f-41b7-add3-c2f6a4023672} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{651d672b-e11f-41b7-add3-c2f6a4023672} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append #IpmiDrv - "{D5C6A3E9-FA9C-434e-9653-165B4FC869E4} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{D5C6A3E9-FA9C-434e-9653-165B4FC869E4} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append # WSManProvHost - "{6e1b64d7-d3be-4651-90fb-3583af89d7f1} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{6e1b64d7-d3be-4651-90fb-3583af89d7f1} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append # Event Forwarding - "{6FCDF39A-EF67-483D-A661-76D715C6B008} 0xffffffff 0xff" | out-file $script:wsmprovfile -encoding ascii -append + "{6FCDF39A-EF67-483D-A661-76D715C6B008} 0xffffffff 0xff" | Out-File $script:wsmprovfile -Encoding ascii -Append - Start-Trace -SessionName $script:wsmsession -ETS -OutputFilePath $script:wsmanlogfile -Format bincirc -MinBuffers 16 -MaxBuffers 256 -BufferSizeInKb 64 -MaxLogFileSizeInMB 256 -ProviderFilePath $script:wsmprovfile + Start-Trace -SessionName $script:wsmsession -ETS -OutputFilePath $script:wsmanlogfile -Format bincirc -MinBuffers 16 -MaxBuffers 256 -BufferSizeInKB 64 -MaxLogFileSizeInMB 256 -ProviderFilePath $script:wsmprovfile } function Disable-WSManTrace { - Stop-Trace $script:wsmsession -ets + Stop-Trace $script:wsmsession -ETS } function Enable-PSWSManCombinedTrace @@ -177,27 +177,27 @@ function Enable-PSWSManCombinedTrace $logfile = $PSHOME + "\\Traces\\PSTrace.etl" } - "Microsoft-Windows-PowerShell 0 5" | out-file $provfile -encoding ascii - "Microsoft-Windows-WinRM 0 5" | out-file $provfile -encoding ascii -append + "Microsoft-Windows-PowerShell 0 5" | Out-File $provfile -Encoding ascii + "Microsoft-Windows-WinRM 0 5" | Out-File $provfile -Encoding ascii -Append if (!(Test-Path $PSHOME\Traces)) { - New-Item -ItemType Directory -Force $PSHOME\Traces | out-null + New-Item -ItemType Directory -Force $PSHOME\Traces | Out-Null } if (Test-Path $logfile) { - Remove-Item -Force $logfile | out-null + Remove-Item -Force $logfile | Out-Null } - Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ets + Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ETS - remove-item $provfile -Force -ea 0 + Remove-Item $provfile -Force -ea 0 } function Disable-PSWSManCombinedTrace { - Stop-Trace -SessionName $script:pssession -ets + Stop-Trace -SessionName $script:pssession -ETS } function Set-LogProperties @@ -220,7 +220,7 @@ function Set-LogProperties $retention = $LogDetails.Retention.ToString() $autobackup = $LogDetails.AutoBackup.ToString() $maxLogSize = $LogDetails.MaxLogSize.ToString() - $osVersion = [Version] (Get-Ciminstance Win32_OperatingSystem).Version + $osVersion = [Version] (Get-CimInstance Win32_OperatingSystem).Version if (($LogDetails.Type -eq "Analytic") -or ($LogDetails.Type -eq "Debug")) { @@ -347,7 +347,7 @@ function Disable-PSTrace } } } -add-type @" +Add-Type @" using System; namespace Microsoft.PowerShell.Diagnostics diff --git a/src/PowerShell.Core.Instrumentation/RegisterManifest.ps1 b/src/PowerShell.Core.Instrumentation/RegisterManifest.ps1 index 6221691d85c..992c7b1c159 100644 --- a/src/PowerShell.Core.Instrumentation/RegisterManifest.ps1 +++ b/src/PowerShell.Core.Instrumentation/RegisterManifest.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. <# diff --git a/src/ResGen/Program.cs b/src/ResGen/Program.cs index f07b992484d..6e25d9239e7 100644 --- a/src/ResGen/Program.cs +++ b/src/ResGen/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/ResGen/ResGen.csproj b/src/ResGen/ResGen.csproj index cb89ac9d875..70170d7c1cb 100644 --- a/src/ResGen/ResGen.csproj +++ b/src/ResGen/ResGen.csproj @@ -2,7 +2,7 @@ Generates C# typed bindings for .resx files - netcoreapp3.1 + net5.0 resgen Exe true diff --git a/src/System.Management.Automation/AssemblyInfo.cs b/src/System.Management.Automation/AssemblyInfo.cs index 731fb02e7e2..279feede65b 100644 --- a/src/System.Management.Automation/AssemblyInfo.cs +++ b/src/System.Management.Automation/AssemblyInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Reflection; diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index c034d355559..293c3599267 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -71,14 +71,14 @@ private PowerShellAssemblyLoadContext(string basePaths) } else { - _probingPaths = basePaths.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + _probingPaths = basePaths.Split(';', StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < _probingPaths.Length; i++) { string basePath = _probingPaths[i]; if (!Directory.Exists(basePath)) { string message = string.Format(CultureInfo.CurrentCulture, BaseFolderDoesNotExist, basePath); - throw new ArgumentException(message, "basePaths"); + throw new ArgumentException(message, nameof(basePaths)); } _probingPaths[i] = basePath.Trim(); @@ -113,6 +113,7 @@ private PowerShellAssemblyLoadContext(string basePaths) // - Value: strong name of the TPA that contains the type represented by Key. private readonly Dictionary _coreClrTypeCatalog; private readonly Lazy> _availableDotNetAssemblyNames; + private readonly HashSet _denyListedAssemblies = new HashSet(StringComparer.OrdinalIgnoreCase){ "System.Windows.Forms" }; @@ -235,11 +236,11 @@ internal IEnumerable GetAssembly(string namespaceQualifiedTypeName) /// internal static IntPtr NativeDllHandler(Assembly assembly, string libraryName) { - var folder = Path.GetDirectoryName(assembly.Location); s_nativeDllSubFolder ??= GetNativeDllSubFolderName(out s_nativeDllExtension); - var fullName = Path.Combine(folder, s_nativeDllSubFolder, libraryName) + s_nativeDllExtension; + string folder = Path.GetDirectoryName(assembly.Location); + string fullName = Path.Combine(folder, s_nativeDllSubFolder, libraryName) + s_nativeDllExtension; - return NativeLibrary.Load(fullName); + return NativeLibrary.TryLoad(fullName, out IntPtr pointer) ? pointer : IntPtr.Zero; } #endregion Internal_Methods @@ -582,7 +583,7 @@ public class PowerShellAssemblyLoadContextInitializer public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPWStr)]string basePaths) { if (string.IsNullOrEmpty(basePaths)) - throw new ArgumentNullException("basePaths"); + throw new ArgumentNullException(nameof(basePaths)); PowerShellAssemblyLoadContext.InitializeSingleton(basePaths); } diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index 108574d9f00..c6ac57070cb 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -155,7 +155,7 @@ public static bool IsWindowsDesktop #endif // format files - internal static List FormatFileNames = new List + internal static readonly List FormatFileNames = new List { "Certificate.format.ps1xml", "Diagnostics.format.ps1xml", @@ -785,7 +785,7 @@ public string GetUserName() return username; } - // Get and add the user name to the cache so we don't need to + // Get and add the user name to the cache so we don't need to // have a pinvoke for each file. username = NativeMethods.GetPwUid(UserId); usernameCache.Add(UserId, username); @@ -805,7 +805,7 @@ public string GetGroupName() return groupname; } - // Get and add the group name to the cache so we don't need to + // Get and add the group name to the cache so we don't need to // have a pinvoke for each file. groupname = NativeMethods.GetGrGid(GroupId); groupnameCache.Add(GroupId, groupname); @@ -976,7 +976,7 @@ public static int GetProcFSParentPid(int pid) try { var stat = System.IO.File.ReadAllText(path); - var parts = stat.Split(new[] { ' ' }, 5); + var parts = stat.Split(' ', 5); if (parts.Length < 5) { return invalidPid; @@ -1092,8 +1092,8 @@ internal static extern int GetInodeData([MarshalAs(UnmanagedType.LPStr)]string p /// /// This is a struct from getcommonstat.h in the native library. - /// It presents each member of the stat structure as the largest type of that member across - /// all stat structures on the platforms we support. This allows us to present a common + /// It presents each member of the stat structure as the largest type of that member across + /// all stat structures on the platforms we support. This allows us to present a common /// stat structure for all our platforms. /// [StructLayout(LayoutKind.Sequential)] diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index 783b36af188..2691e168364 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/CoreCLR/EventResource.cs b/src/System.Management.Automation/CoreCLR/EventResource.cs index 56a53066f90..178602e7da4 100755 --- a/src/System.Management.Automation/CoreCLR/EventResource.cs +++ b/src/System.Management.Automation/CoreCLR/EventResource.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if UNIX diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index b314aa6087a..be547213afa 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -298,7 +298,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input if (engineIntrinsics == null) { - throw PSTraceSource.NewArgumentNullException("engineIntrinsics"); + throw PSTraceSource.NewArgumentNullException(nameof(engineIntrinsics)); } return PsUtils.EvaluatePowerShellDataFileAsModuleManifest( @@ -372,7 +372,7 @@ internal static byte[] GetFileContent(string fullFilePath) { if (string.IsNullOrEmpty(fullFilePath)) { - throw PSTraceSource.NewArgumentNullException("fullFilePath"); + throw PSTraceSource.NewArgumentNullException(nameof(fullFilePath)); } if (!File.Exists(fullFilePath)) @@ -656,6 +656,7 @@ private static HashSet ScriptKeywordFileCache /// [ThreadStatic] private static bool t_cacheResourcesFromMultipleModuleVersions; + private static bool CacheResourcesFromMultipleModuleVersions { get @@ -951,7 +952,7 @@ public static List ImportClasses(string path, Tuple m { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } s_tracer.WriteLine("DSC ClassCache: importing file: {0}", path); @@ -1179,7 +1180,7 @@ public static List GetCachedClassByFileName(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { - throw PSTraceSource.NewArgumentNullException("fileName"); + throw PSTraceSource.NewArgumentNullException(nameof(fileName)); } List listCimClass; @@ -1197,7 +1198,7 @@ public static List GetCachedClassByModuleName(string moduleName) { if (string.IsNullOrWhiteSpace(moduleName)) { - throw PSTraceSource.NewArgumentNullException("moduleName"); + throw PSTraceSource.NewArgumentNullException(nameof(moduleName)); } var moduleFileName = moduleName + ".schema.mof"; @@ -1214,7 +1215,7 @@ public static List ImportInstances(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback); @@ -1233,8 +1234,7 @@ public static List ImportInstances(string path, int schemaValidatio { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentNullException("path"); - throw new ArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (schemaValidationOption < (int)Microsoft.Management.Infrastructure.Serialization.MofDeserializerSchemaValidationOption.Default || @@ -1257,7 +1257,7 @@ public static void ValidateInstanceText(string instanceText) { if (string.IsNullOrEmpty(instanceText)) { - throw PSTraceSource.NewArgumentNullException("instanceText"); + throw PSTraceSource.NewArgumentNullException(nameof(instanceText)); } var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback); @@ -2414,7 +2414,7 @@ private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitio const string setMethodName = "Set"; const string testMethodName = "Test"; - methodsLinePosition = new Dictionary(); ; + methodsLinePosition = new Dictionary(); foreach (var member in typeDefinitionAst.Members) { var functionMemberAst = member as FunctionMemberAst; @@ -3221,12 +3221,12 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou { if (module == null) { - throw PSTraceSource.NewArgumentNullException("module"); + throw PSTraceSource.NewArgumentNullException(nameof(module)); } if (resourceName == null) { - throw PSTraceSource.NewArgumentNullException("resourceName"); + throw PSTraceSource.NewArgumentNullException(nameof(resourceName)); } string dscResourcesPath = Path.Combine(module.ModuleBase, "DscResources"); @@ -3333,12 +3333,12 @@ public static bool ImportScriptKeywordsFromModule(PSModuleInfo module, string re { if (module == null) { - throw PSTraceSource.NewArgumentNullException("module"); + throw PSTraceSource.NewArgumentNullException(nameof(module)); } if (resourceName == null) { - throw PSTraceSource.NewArgumentNullException("resourceName"); + throw PSTraceSource.NewArgumentNullException(nameof(resourceName)); } schemaFilePath = Path.Combine(Path.Combine(Path.Combine(module.ModuleBase, "DscResources"), resourceName), resourceName + ".Schema.psm1"); @@ -3713,6 +3713,7 @@ private static ScriptBlock CimKeywordImplementationFunction } private static ScriptBlock s_cimKeywordImplementationFunction; + private const string CimKeywordImplementationFunctionText = @" param ( [Parameter(Mandatory)] @@ -4073,4 +4074,3 @@ function Test-DependsOn "; } } - diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Certificate_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Certificate_format_ps1xml.cs index 66093a82912..22945778c12 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Certificate_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Certificate_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Diagnostics_Format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Diagnostics_Format_ps1xml.cs index 6c6bc97793e..e08c7357e63 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Diagnostics_Format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Diagnostics_Format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs index 040de0994c8..6407a2d7012 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/DotNetTypes_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Event_Format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Event_Format_ps1xml.cs index a68c82024ba..8b92e3ac391 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Event_Format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Event_Format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs index 0346a094189..374cadf31d8 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs index 508afa56e1f..987ed33fb4a 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs index 35d8818ac25..d18de013397 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; 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 67d6da5d551..dfd610e4750 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -46,6 +46,10 @@ internal static IEnumerable GetFormatData() "Microsoft.PowerShell.Commands.MatchInfo", ViewsOf_Microsoft_PowerShell_Commands_MatchInfo()); + yield return new ExtendedTypeDefinition( + "Deserialized.Microsoft.PowerShell.Commands.MatchInfo", + ViewsOf_Deserialized_Microsoft_PowerShell_Commands_MatchInfo()); + yield return new ExtendedTypeDefinition( "System.Management.Automation.PSVariable", ViewsOf_System_Management_Automation_PSVariable()); @@ -382,6 +386,16 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co .EndControl()); } + private static IEnumerable ViewsOf_Deserialized_Microsoft_PowerShell_Commands_MatchInfo() + { + yield return new FormatViewDefinition("MatchInfo", + CustomControl.Create() + .StartEntry() + .AddScriptBlockExpressionBinding(@"$_.Line") + .EndEntry() + .EndControl()); + } + private static IEnumerable ViewsOf_System_Management_Automation_PSVariable() { yield return new FormatViewDefinition("Variable", @@ -752,14 +766,14 @@ private static IEnumerable ViewsOf_System_Management_Autom $maxDepth = 10 $ellipsis = ""`u{2026}"" $resetColor = '' - if ($Host.UI.SupportsVirtualTerminal -and !(Test-Path env:__SuppressAnsiEscapeSequences)) { + if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { $resetColor = [System.Management.Automation.VTUtility]::GetEscapeSequence( [System.Management.Automation.VTUtility+VT]::Reset ) } function Get-VT100Color([ConsoleColor] $color) { - if (!$Host.UI.SupportsVirtualTerminal -or (Test-Path env:__SuppressAnsiEscapeSequences)) { + if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { return '' } @@ -999,14 +1013,14 @@ private static IEnumerable ViewsOf_System_Management_Autom function Get-ConciseViewPositionMessage { $resetColor = '' - if ($Host.UI.SupportsVirtualTerminal -and !(Test-Path env:__SuppressAnsiEscapeSequences)) { + if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { $resetColor = [System.Management.Automation.VTUtility]::GetEscapeSequence( [System.Management.Automation.VTUtility+VT]::Reset ) } function Get-VT100Color([ConsoleColor] $color) { - if (!$Host.UI.SupportsVirtualTerminal -or (Test-Path env:__SuppressAnsiEscapeSequences)) { + if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { return '' } @@ -1151,18 +1165,32 @@ function Get-ConciseViewPositionMessage { # replace newlines in message so it lines up correct $message = $message.Replace($newline, ' ').Replace(""`t"", ' ') - if ([Console]::WindowWidth -gt 0 -and ($message.Length - $prefixVTLength) -gt [Console]::WindowWidth) { + + $windowWidth = 120 + if ($Host.UI.RawUI -ne $null) { + $windowWidth = $Host.UI.RawUI.WindowSize.Width + } + + if ($windowWidth -gt 0 -and ($message.Length - $prefixVTLength) -gt $windowWidth) { $sb = [Text.StringBuilder]::new() - $substring = Get-TruncatedString -string $message -length ([Console]::WindowWidth + $prefixVTLength) + $substring = Get-TruncatedString -string $message -length ($windowWidth + $prefixVTLength) $null = $sb.Append($substring) $remainingMessage = $message.Substring($substring.Length).Trim() $null = $sb.Append($newline) - while (($remainingMessage.Length + $prefixLength) -gt [Console]::WindowWidth) { + while (($remainingMessage.Length + $prefixLength) -gt $windowWidth) { $subMessage = $prefix + $remainingMessage - $substring = Get-TruncatedString -string $subMessage -length ([Console]::WindowWidth + $prefixVtLength) - $null = $sb.Append($substring) - $null = $sb.Append($newline) - $remainingMessage = $remainingMessage.Substring($substring.Length - $prefix.Length).Trim() + $substring = Get-TruncatedString -string $subMessage -length ($windowWidth + $prefixVtLength) + + if ($substring.Length - $prefix.Length -gt 0) + { + $null = $sb.Append($substring) + $null = $sb.Append($newline) + $remainingMessage = $remainingMessage.Substring($substring.Length - $prefix.Length).Trim() + } + else + { + break + } } $null = $sb.Append($prefix + $remainingMessage.Trim()) $message = $sb.ToString() @@ -1618,6 +1646,14 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Co .EndTable()); } + private const string PreReleaseStringScriptBlock = @" + if ($_.PrivateData -and + $_.PrivateData.ContainsKey('PSData') -and + $_.PrivateData.PSData.ContainsKey('PreRelease')) + { + $_.PrivateData.PSData.PreRelease + }"; + private static IEnumerable ViewsOf_ModuleInfoGrouping(CustomControl[] sharedControls) { yield return new FormatViewDefinition("Module", @@ -1632,11 +1668,7 @@ private static IEnumerable ViewsOf_ModuleInfoGrouping(Cust .StartRowDefinition() .AddPropertyColumn("ModuleType") .AddPropertyColumn("Version") - .AddScriptBlockColumn(@" - if ($_.PrivateData -and $_.PrivateData.PSData) - { - $_.PrivateData.PSData.PreRelease - }") + .AddScriptBlockColumn(PreReleaseStringScriptBlock) .AddPropertyColumn("Name") .AddScriptBlockColumn(@" $result = [System.Collections.ArrayList]::new() @@ -1669,11 +1701,7 @@ private static IEnumerable ViewsOf_System_Management_Autom .StartRowDefinition() .AddPropertyColumn("ModuleType") .AddPropertyColumn("Version") - .AddScriptBlockColumn(@" - if ($_.PrivateData -and $_.PrivateData.PSData) - { - $_.PrivateData.PSData.PreRelease - }") + .AddScriptBlockColumn(PreReleaseStringScriptBlock) .AddPropertyColumn("Name") .AddScriptBlockColumn("$_.ExportedCommands.Keys") .EndRowDefinition() @@ -1693,11 +1721,7 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemProperty(@"ModuleType") .AddItemProperty(@"Version") .AddItemScriptBlock( - @" - if ($_.PrivateData -and $_.PrivateData.PSData) - { - $_.PrivateData.PSData.PreRelease - }", + PreReleaseStringScriptBlock, label: "PreRelease") .AddItemProperty(@"NestedModules") .AddItemScriptBlock(@"$_.ExportedFunctions.Keys", label: "ExportedFunctions") diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellTrace_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellTrace_format_ps1xml.cs index ef0a79e12a6..c958ac9f49d 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellTrace_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellTrace_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs index caab800c85c..c1498af0bf1 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Registry_format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/WSMan_Format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/WSMan_Format_ps1xml.cs index d11b1538edb..3ac1cdf35b1 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/WSMan_Format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/WSMan_Format_ps1xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs index b2e5a64caf0..e03b4ae61eb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -18,7 +18,7 @@ internal sealed class TerminatingErrorContext internal TerminatingErrorContext(PSCmdlet command) { if (command == null) - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); _command = command; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index cd9b6afeff5..ffccf13f4e1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -262,6 +262,9 @@ private void ProcessObject(PSObject so) } else if (transition == GroupTransition.startNew) { + // Add newline before each group except first + WriteNewLineObject(); + // double transition PopGroup(); // exit the current one PushGroup(so); // start a sibling group @@ -273,6 +276,23 @@ private void ProcessObject(PSObject so) } } + private void WriteNewLineObject() + { + FormatEntryData fed = new FormatEntryData(); + fed.outOfBand = true; + + ComplexViewEntry cve = new ComplexViewEntry(); + FormatEntry fe = new FormatEntry(); + cve.formatValueList.Add(fe); + + // Formating system writes newline before each object + // so no need to add newline here like: + // fe.formatValueList.Add(new FormatNewLine()); + fed.formatEntryInfo = cve; + + this.WriteObject(fed); + } + private bool ShouldProcessOutOfBand { get diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 8614896384f..cdd60637a7a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -171,7 +171,7 @@ internal override object Verify(object val, { if (val == null) { - throw PSTraceSource.NewArgumentNullException("val"); + throw PSTraceSource.NewArgumentNullException(nameof(val)); } // need to check the type: @@ -201,7 +201,7 @@ internal override object Verify(object val, return ex; } - PSTraceSource.NewArgumentException("val"); + PSTraceSource.NewArgumentException(nameof(val)); return null; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index be70dc9714b..bb8305b2fdc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -18,7 +18,7 @@ internal class OutCommandInner : ImplementationCommandBase { #region tracer [TraceSource("format_out_OutCommandInner", "OutCommandInner")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutCommandInner", "OutCommandInner"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutCommandInner", "OutCommandInner"); #endregion tracer internal override void BeginProcessing() @@ -476,8 +476,6 @@ private void ProcessGroupStart(FormatMessagesContextManager.OutputContext c) if (goc.Data.groupingEntry != null) { - _lo.WriteLine(string.Empty); - ComplexWriter writer = new ComplexWriter(); writer.Initialize(_lo, _lo.ColumnNumber); writer.WriteObject(goc.Data.groupingEntry.formatValueList); @@ -510,7 +508,7 @@ private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.Ou // we assume FormatEntryData as a standard wrapper if (fed == null) { - PSTraceSource.NewArgumentNullException("fed"); + PSTraceSource.NewArgumentNullException(nameof(fed)); } if (fed.formatEntryInfo == null) @@ -950,7 +948,9 @@ private sealed class TableOutputContext : TableOutputContextBase private int _rowCount = 0; private int _consoleHeight = -1; private int _consoleWidth = -1; + private const int WhitespaceAndPagerLineCount = 2; + private bool _repeatHeader = false; /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs b/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs index 28357039d18..d2e44c4ad60 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ColumnWidthManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index d43e42ebb2d..74031dc515c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index af8ef63e9fc..6b647bd0912 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -87,7 +87,7 @@ protected FormatTableLoadException(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } int errorCount = info.GetInt32("ErrorCount"); @@ -114,7 +114,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -207,7 +207,7 @@ public FormatTable(IEnumerable formatFiles) : this(formatFiles, null, nu public void AppendFormatData(IEnumerable formatData) { if (formatData == null) - throw PSTraceSource.NewArgumentNullException("formatData"); + throw PSTraceSource.NewArgumentNullException(nameof(formatData)); _formatDBMgr.AddFormatData(formatData, false); } @@ -226,7 +226,7 @@ public void AppendFormatData(IEnumerable formatData) public void PrependFormatData(IEnumerable formatData) { if (formatData == null) - throw PSTraceSource.NewArgumentNullException("formatData"); + throw PSTraceSource.NewArgumentNullException(nameof(formatData)); _formatDBMgr.AddFormatData(formatData, true); } @@ -253,7 +253,7 @@ internal FormatTable(IEnumerable formatFiles, AuthorizationManager autho { if (formatFiles == null) { - throw PSTraceSource.NewArgumentNullException("formatFiles"); + throw PSTraceSource.NewArgumentNullException(nameof(formatFiles)); } _formatDBMgr = new TypeInfoDataBaseManager(formatFiles, true, authorizationManager, host); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index 0e77a143e02..02d60731e43 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs index 721db4264fa..1402fbbbc8a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/commands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index beb774bfe51..64af2244fb8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // this file contains the data structures for the in memory database @@ -376,22 +376,22 @@ internal static string GetControlShapeName(ControlBase control) { if (control is TableControlBody) { - return FormatShape.Table.ToString(); + return nameof(FormatShape.Table); } if (control is ListControlBody) { - return FormatShape.List.ToString(); + return nameof(FormatShape.List); } if (control is WideControlBody) { - return FormatShape.Wide.ToString(); + return nameof(FormatShape.Wide); } if (control is ComplexControlBody) { - return FormatShape.Complex.ToString(); + return nameof(FormatShape.Complex); } return string.Empty; @@ -635,9 +635,9 @@ public override string ToString() public ExtendedTypeDefinition(string typeName, IEnumerable viewDefinitions) : this() { if (string.IsNullOrEmpty(typeName)) - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); if (viewDefinitions == null) - throw PSTraceSource.NewArgumentNullException("viewDefinitions"); + throw PSTraceSource.NewArgumentNullException(nameof(viewDefinitions)); TypeNames.Add(typeName); foreach (FormatViewDefinition definition in viewDefinitions) @@ -653,7 +653,7 @@ public ExtendedTypeDefinition(string typeName, IEnumerable public ExtendedTypeDefinition(string typeName) : this() { if (string.IsNullOrEmpty(typeName)) - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); TypeNames.Add(typeName); } @@ -691,12 +691,13 @@ internal FormatViewDefinition(string name, PSControl control, Guid instanceid) public FormatViewDefinition(string name, PSControl control) { if (string.IsNullOrEmpty(name)) - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); if (control == null) - throw PSTraceSource.NewArgumentNullException("control"); + throw PSTraceSource.NewArgumentNullException(nameof(control)); Name = name; Control = control; + InstanceId = Guid.NewGuid(); } } @@ -799,7 +800,7 @@ public DisplayEntry(string value, DisplayEntryValueType type) { if (string.IsNullOrEmpty(value)) if (value == null || type == DisplayEntryValueType.Property) - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); Value = value; ValueType = type; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs index d4ed74e97cf..fd321e14b80 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionDataMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands.Internal.Format diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index 76a6fe55a21..d3290c18752 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // this file contains the data structures for the in memory database @@ -420,13 +420,13 @@ public CustomEntryBuilder StartFrame(uint leftIndent = 0, uint rightIndent = 0, // Mutually exclusive if (leftIndent != 0 && rightIndent != 0) { - throw PSTraceSource.NewArgumentException("leftIndent"); + throw PSTraceSource.NewArgumentException(nameof(leftIndent)); } // Mutually exclusive if (firstLineHanging != 0 && firstLineIndent != 0) { - throw PSTraceSource.NewArgumentException("firstLineHanging"); + throw PSTraceSource.NewArgumentException(nameof(firstLineHanging)); } var frame = new CustomItemFrame diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index fba42c25522..6025acfff44 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // this file contains the data structures for the in memory database @@ -173,7 +173,7 @@ public ListControl(IEnumerable entries) : this() { if (entries == null) - throw PSTraceSource.NewArgumentNullException("entries"); + throw PSTraceSource.NewArgumentNullException(nameof(entries)); foreach (ListControlEntry entry in entries) { this.Entries.Add(entry); @@ -242,7 +242,7 @@ public ListControlEntry(IEnumerable listItems) : this() { if (listItems == null) - throw PSTraceSource.NewArgumentNullException("listItems"); + throw PSTraceSource.NewArgumentNullException(nameof(listItems)); foreach (ListControlEntryItem item in listItems) { this.Items.Add(item); @@ -253,9 +253,9 @@ public ListControlEntry(IEnumerable listItems) public ListControlEntry(IEnumerable listItems, IEnumerable selectedBy) { if (listItems == null) - throw PSTraceSource.NewArgumentNullException("listItems"); + throw PSTraceSource.NewArgumentNullException(nameof(listItems)); if (selectedBy == null) - throw PSTraceSource.NewArgumentNullException("selectedBy"); + throw PSTraceSource.NewArgumentNullException(nameof(selectedBy)); EntrySelectedBy = new EntrySelectedBy { TypeNames = new List(selectedBy) }; foreach (ListControlEntryItem item in listItems) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs index 09a27be3473..cb1cc5cbf30 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Misc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // this file contains the data structures for the in memory database diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index 6ca0967b10f..b9d1e897068 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // this file contains the data structures for the in memory database @@ -306,7 +306,7 @@ public TableControl(TableControlRow tableControlRow, IEnumerable columns) : this() { if (columns == null) - throw PSTraceSource.NewArgumentNullException("columns"); + throw PSTraceSource.NewArgumentNullException(nameof(columns)); foreach (TableControlColumn column in columns) { Columns.Add(column); @@ -507,7 +507,7 @@ internal TableRowDefinitionBuilder(TableControlBuilder tcb, TableControlRow tcr) private TableRowDefinitionBuilder AddItem(string value, DisplayEntryValueType entryType, Alignment alignment, string format) { if (string.IsNullOrEmpty(value)) - throw PSTraceSource.NewArgumentException("value"); + throw PSTraceSource.NewArgumentException(nameof(value)); var tableControlColumn = new TableControlColumn(alignment, new DisplayEntry(value, entryType)) { @@ -547,6 +547,7 @@ public TableControlBuilder EndRowDefinition() public sealed class TableControlBuilder { internal readonly TableControl _table; + internal TableControlBuilder(TableControl table) { _table = table; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index 63438583bee..05e3e79923b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // this file contains the data structures for the in memory database @@ -145,7 +145,7 @@ internal WideControl(WideControlBody widecontrolbody, ViewDefinition viewDefinit public WideControl(IEnumerable wideEntries) : this() { if (wideEntries == null) - throw PSTraceSource.NewArgumentNullException("wideEntries"); + throw PSTraceSource.NewArgumentNullException(nameof(wideEntries)); foreach (WideControlEntryItem entryItem in wideEntries) { @@ -157,7 +157,7 @@ public WideControl(IEnumerable wideEntries) : this() public WideControl(IEnumerable wideEntries, uint columns) : this() { if (wideEntries == null) - throw PSTraceSource.NewArgumentNullException("wideEntries"); + throw PSTraceSource.NewArgumentNullException(nameof(wideEntries)); foreach (WideControlEntryItem entryItem in wideEntries) { @@ -224,7 +224,7 @@ internal WideControlEntryItem(WideControlEntryDefinition definition) : this() public WideControlEntryItem(DisplayEntry entry) : this() { if (entry == null) - throw PSTraceSource.NewArgumentNullException("entry"); + throw PSTraceSource.NewArgumentNullException(nameof(entry)); this.DisplayEntry = entry; } @@ -234,9 +234,9 @@ public WideControlEntryItem(DisplayEntry entry) : this() public WideControlEntryItem(DisplayEntry entry, IEnumerable selectedBy) : this() { if (entry == null) - throw PSTraceSource.NewArgumentNullException("entry"); + throw PSTraceSource.NewArgumentNullException(nameof(entry)); if (selectedBy == null) - throw PSTraceSource.NewArgumentNullException("selectedBy"); + throw PSTraceSource.NewArgumentNullException(nameof(selectedBy)); this.DisplayEntry = entry; this.EntrySelectedBy = EntrySelectedBy.Get(selectedBy, null); @@ -259,6 +259,7 @@ internal bool CompatibleWithOldPowerShell() public sealed class WideControlBuilder { private readonly WideControl _control; + internal WideControlBuilder(WideControl control) { _control = control; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index 73cb10b98af..52e1043cb2c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -81,7 +81,7 @@ private string GetStringHelper(StringResourceReference resourceReference, out Lo else { resourceReference.assemblyLocation = loadResult.a.Location; - }; + } // load now the resource from the resource manager cache try diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index 37cf6b9de93..985561670f8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -79,7 +79,7 @@ internal TypeInfoDataBaseManager( { if (string.IsNullOrEmpty(formatFile) || (!Path.IsPathRooted(formatFile))) { - throw PSTraceSource.NewArgumentException("formatFiles", FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); + throw PSTraceSource.NewArgumentException(nameof(formatFiles), FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); } PSSnapInTypeAndFormatErrors fileToLoad = new PSSnapInTypeAndFormatErrors(string.Empty, formatFile); @@ -122,7 +122,7 @@ internal void Add(string formatFile, bool shouldPrepend) { if (string.IsNullOrEmpty(formatFile) || (!Path.IsPathRooted(formatFile))) { - throw PSTraceSource.NewArgumentException("formatFile", FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); + throw PSTraceSource.NewArgumentException(nameof(formatFile), FormatAndOutXmlLoadingStrings.FormatFileNotRooted, formatFile); } lock (_formatFileList) @@ -473,6 +473,7 @@ private static void LoadFormatDataHelper( } private delegate IEnumerable TypeGenerator(); + private static Dictionary> s_builtinGenerators; private static Tuple GetBuiltin(bool isForHelp, TypeGenerator generator) diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 6edc79f2595..470832670a9 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 5c0d209a5ec..79bcbd61dca 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -193,16 +193,16 @@ internal bool LoadXmlFile( bool preValidated) { if (info == null) - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); if (info.filePath == null) throw PSTraceSource.NewArgumentNullException("info.filePath"); if (db == null) - throw PSTraceSource.NewArgumentNullException("db"); + throw PSTraceSource.NewArgumentNullException(nameof(db)); if (expressionFactory == null) - throw PSTraceSource.NewArgumentNullException("expressionFactory"); + throw PSTraceSource.NewArgumentNullException(nameof(expressionFactory)); if (SecuritySupport.IsProductBinary(info.filePath)) { @@ -288,13 +288,13 @@ internal bool LoadFormattingData( bool isForHelp) { if (typeDefinition == null) - throw PSTraceSource.NewArgumentNullException("typeDefinition"); + throw PSTraceSource.NewArgumentNullException(nameof(typeDefinition)); if (typeDefinition.TypeName == null) throw PSTraceSource.NewArgumentNullException("typeDefinition.TypeName"); if (db == null) - throw PSTraceSource.NewArgumentNullException("db"); + throw PSTraceSource.NewArgumentNullException(nameof(db)); if (expressionFactory == null) - throw PSTraceSource.NewArgumentNullException("expressionFactory"); + throw PSTraceSource.NewArgumentNullException(nameof(expressionFactory)); this.expressionFactory = expressionFactory; this.ReportTrace("loading ExtendedTypeDefinition started"); @@ -337,10 +337,10 @@ internal bool LoadFormattingData( private void LoadData(XmlDocument doc, TypeInfoDataBase db) { if (doc == null) - throw PSTraceSource.NewArgumentNullException("doc"); + throw PSTraceSource.NewArgumentNullException(nameof(doc)); if (db == null) - throw PSTraceSource.NewArgumentNullException("db"); + throw PSTraceSource.NewArgumentNullException(nameof(db)); // create a new instance of the database to be loaded XmlElement documentElement = doc.DocumentElement; @@ -428,7 +428,7 @@ private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db throw PSTraceSource.NewArgumentNullException("viewDefinition"); if (db == null) - throw PSTraceSource.NewArgumentNullException("db"); + throw PSTraceSource.NewArgumentNullException(nameof(db)); int viewIndex = 0; foreach (FormatViewDefinition formatView in typeDefinition.FormatViewDefinition) @@ -2054,7 +2054,7 @@ internal ViewEntryNodeMatch(TypeInfoDataBaseLoader loader) internal bool ProcessExpressionDirectives(XmlNode containerNode, List unprocessedNodes) { if (containerNode == null) - throw PSTraceSource.NewArgumentNullException("containerNode"); + throw PSTraceSource.NewArgumentNullException(nameof(containerNode)); string formatString = null; TextToken textToken = null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs index 38efdf7923e..3c9cecaed1b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Complex.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs index 031672a9b27..323c94454b2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_List.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs index 68ac9fb5e2e..acc60a3e3e5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Table.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index ab1453f7d79..8b960e32297 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -98,7 +98,6 @@ private ViewDefinition LoadView(XmlNode viewNode, int index) mainControlFound = true; view.mainControl = LoadListControl(n); } - else if (MatchNodeName(n, XmlTags.WideControlNode)) { if (mainControlFound) @@ -201,10 +200,10 @@ private bool LoadMainControlDependentData(List unprocessedNodes, ViewDe private bool LoadCommonViewData(XmlNode viewNode, ViewDefinition view, List unprocessedNodes) { if (viewNode == null) - throw PSTraceSource.NewArgumentNullException("viewNode"); + throw PSTraceSource.NewArgumentNullException(nameof(viewNode)); if (view == null) - throw PSTraceSource.NewArgumentNullException("view"); + throw PSTraceSource.NewArgumentNullException(nameof(view)); // set loading information view.loadingInfo = this.LoadingInfo; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs index 2a53a7d0d66..07ea8ae69e1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Wide.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs index 3710e82139f..92eb3708d16 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatGroupManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 374897f8a6c..0aaf16a9a28 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index 5596987d50b..cf6a4d2eb88 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index d41a119dde6..c9cd80bbee8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -93,7 +93,7 @@ internal void GenerateFormatEntries(int maxTreeDepth, ControlBase control, { if (control == null) { - throw PSTraceSource.NewArgumentNullException("control"); + throw PSTraceSource.NewArgumentNullException(nameof(control)); } ExecuteFormatControl(new TraversalInfo(0, maxTreeDepth), control, @@ -190,7 +190,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, { if (so == null) { - throw PSTraceSource.NewArgumentNullException("so"); + throw PSTraceSource.NewArgumentNullException(nameof(so)); } // guard against infinite loop diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs index 95ce0d71fff..2ded68cd510 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index ec261cc305d..ab4912c8838 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs index 213ccb4fedf..9d378eaf9cc 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index 49425d7854d..aca38f8994b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -344,7 +344,7 @@ private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.NonExistingViewNameError, formatTypeName, so.BaseObject.GetType())); } - msg = unKnowViewFormatStringBuilder.ToString(); ; + msg = unKnowViewFormatStringBuilder.ToString(); } ErrorRecord errorRecord = new ErrorRecord( @@ -516,7 +516,7 @@ internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext er } // we must check we have enough properties for a list view - if (new PSPropertyExpression("*").ResolveNames(so).Count <= 0) + if (new PSPropertyExpression("*").ResolveNames(so).Count == 0) { return null; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs index 11f214c9cdb..bb2c8ff93e7 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs index bc9cc0565a0..f4ac55d1feb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // This file contains the definitions for the objects diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index ce2c2ef7a81..3e8c320390b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -142,7 +142,7 @@ private void ProcessUnknownInvalidClassId(string classId, object obj, string err string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_ClassIdInvalid, classId); ErrorRecord errorRecord = new ErrorRecord( - PSTraceSource.NewArgumentException("classId"), + PSTraceSource.NewArgumentException(nameof(classId)), errorId, ErrorCategory.InvalidData, obj); @@ -217,7 +217,7 @@ internal FormatInfoData DeserializeMemberObject(PSObject so, string property) string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_RecursiveProperty, property); ErrorRecord errorRecord = new ErrorRecord( - PSTraceSource.NewArgumentException("property"), + PSTraceSource.NewArgumentException(nameof(property)), "FormatObjectDeserializerRecursiveProperty", ErrorCategory.InvalidData, so); @@ -247,7 +247,7 @@ private object DeserializeMemberVariable(PSObject so, string property, System.Ty string msg = StringUtil.Format(FormatAndOut_format_xxx.FOD_InvalidPropertyType, t.Name, property); ErrorRecord errorRecord = new ErrorRecord( - PSTraceSource.NewArgumentException("property"), + PSTraceSource.NewArgumentException(nameof(property)), "FormatObjectDeserializerInvalidPropertyType", ErrorCategory.InvalidData, so); @@ -392,7 +392,7 @@ internal static FormatInfoData CreateInstance(PSObject so, FormatObjectDeseriali { if (so == null) { - throw PSTraceSource.NewArgumentNullException("so"); + throw PSTraceSource.NewArgumentNullException(nameof(so)); } // look for the property that defines the type of object @@ -421,7 +421,7 @@ private static FormatInfoData CreateInstance(string clsid, FormatObjectDeseriali Func ctor; if (!s_constructors.TryGetValue(clsid, out ctor)) { - CreateInstanceError(PSTraceSource.NewArgumentException("clsid"), clsid, deserializer); + CreateInstanceError(PSTraceSource.NewArgumentException(nameof(clsid)), clsid, deserializer); return null; } @@ -504,7 +504,7 @@ internal static void ReadList(PSObject so, string property, List lst, FormatO { if (lst == null) { - throw PSTraceSource.NewArgumentNullException("lst"); + throw PSTraceSource.NewArgumentNullException(nameof(lst)); } object memberRaw = FormatObjectDeserializer.GetProperty(so, property); diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 880a1c9f5cc..09432253e33 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; @@ -282,9 +282,9 @@ internal class WriteLineHelper internal WriteLineHelper(bool lineWrap, WriteCallback wlc, WriteCallback wc, DisplayCells displayCells) { if (wlc == null) - throw PSTraceSource.NewArgumentNullException("wlc"); + throw PSTraceSource.NewArgumentNullException(nameof(wlc)); if (displayCells == null) - throw PSTraceSource.NewArgumentNullException("displayCells"); + throw PSTraceSource.NewArgumentNullException(nameof(displayCells)); _displayCells = displayCells; _writeLineCall = wlc; @@ -474,7 +474,7 @@ internal StreamingTextWriter(WriteLineCallback writeCall, CultureInfo culture) : base(culture) { if (writeCall == null) - throw PSTraceSource.NewArgumentNullException("writeCall"); + throw PSTraceSource.NewArgumentNullException(nameof(writeCall)); _writeCall = writeCall; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index 03742dc79ff..91a7b8698a6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index a5bf1c9bf22..b07731c3e04 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -20,7 +20,7 @@ internal sealed class OutputManagerInner : ImplementationCommandBase { #region tracer [TraceSource("format_out_OutputManagerInner", "OutputManagerInner")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner"); #endregion tracer #region LineOutput @@ -213,10 +213,10 @@ private void InitializeCommandsHardWired(ExecutionContext context) additional types. Adding a handler here would cause a new sub-pipeline to be created. - For example, the following line would add a new handler named "out-foobar" - to be invoked when the incoming object type is "MyNamespace.Whatever.FooBar" + For example, the following line would add a new handler named "out-example" + to be invoked when the incoming object type is "MyNamespace.Whatever.Example" - RegisterCommandForTypes (context, "out-foobar", new string[] { "MyNamespace.Whatever.FooBar" }); + RegisterCommandForTypes (context, "out-example", new string[] { "MyNamespace.Whatever.Example" }); And the method can be like this: private void RegisterCommandForTypes (ExecutionContext context, string commandName, Type commandType, string[] types) diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index b4714d0e429..1545f456e12 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index f01cc9b8499..e01be6f5b8c 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -40,8 +40,10 @@ private class ScreenInfo } private ScreenInfo _si; + private const char ESC = '\u001b'; private const string ResetConsoleVt100Code = "\u001b[m"; + private List _header; internal static int ComputeWideViewBestItemsPerRowFit(int stringLen, int screenColumns) @@ -436,7 +438,7 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display } sb.Append(GenerateRowField(values[k], _si.columnInfo[k].width, alignment[k], dc, addPadding)); - if (values[k].IndexOf(ESC) != -1) + if (values[k].Contains(ESC)) { // Reset the console output if the content of this column contains ESC sb.Append(ResetConsoleVt100Code); diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index a2de347af9a..c890599cb1e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -173,7 +173,7 @@ private static string GetObjectName(object x, PSPropertyExpressionFactory expres PSPropertyExpressionResult r = PSObjectHelper.GetDisplayName(PSObjectHelper.AsPSObject(x), expressionFactory); if ((r != null) && (r.Exception == null)) { - objName = PSObjectHelper.AsPSObject(r.Result).ToString(); ; + objName = PSObjectHelper.AsPSObject(r.Result).ToString(); } else { diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs index c037fa29df8..d04008a1f9a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -32,6 +32,7 @@ internal object GetEntry(string key) internal class NameEntryDefinition : HashtableEntryDefinition { internal const string NameEntryKey = "name"; + internal NameEntryDefinition() : base(NameEntryKey, new string[] { FormatParameterDefinitionKeys.LabelEntryKey }, new Type[] { typeof(string) }, false) { @@ -140,7 +141,7 @@ internal CommandParameterDefinition() internal HashtableEntryDefinition MatchEntry(string keyName, TerminatingErrorContext invocationContext) { if (string.IsNullOrEmpty(keyName)) - PSTraceSource.NewArgumentNullException("keyName"); + PSTraceSource.NewArgumentNullException(nameof(keyName)); HashtableEntryDefinition matchingEntry = null; for (int k = 0; k < this.hashEntries.Count; k++) @@ -177,7 +178,7 @@ internal static bool FindPartialMatch(string key, string normalizedKey) if (key.Length < normalizedKey.Length) { // shorter, could be an abbreviation - if (string.Equals(key, normalizedKey.Substring(0, key.Length), StringComparison.OrdinalIgnoreCase)) + if (key.AsSpan().Equals(normalizedKey.AsSpan(0, key.Length), StringComparison.OrdinalIgnoreCase)) { // found abbreviation return true; @@ -227,7 +228,7 @@ internal sealed class ParameterProcessor { #region tracer [TraceSource("ParameterProcessor", "ParameterProcessor")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("ParameterProcessor", "ParameterProcessor"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ParameterProcessor", "ParameterProcessor"); #endregion tracer internal static void ThrowParameterBindingException(TerminatingErrorContext invocationContext, diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs index 7a04c4537cb..22b4c47ee40 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshParameterAssociation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -16,14 +16,14 @@ internal sealed class MshResolvedExpressionParameterAssociation { #region tracer [TraceSource("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("MshResolvedExpressionParameterAssociation", + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("MshResolvedExpressionParameterAssociation", "MshResolvedExpressionParameterAssociation"); #endregion tracer internal MshResolvedExpressionParameterAssociation(MshParameter parameter, PSPropertyExpression expression) { if (expression == null) - throw PSTraceSource.NewArgumentNullException("expression"); + throw PSTraceSource.NewArgumentNullException(nameof(expression)); OriginatingParameter = parameter; ResolvedExpression = expression; @@ -159,9 +159,8 @@ internal static List ExpandAll(PSObje List retVal = new List(); foreach (string property in displayedProperties) { - if (!duplicatesFinder.ContainsKey(property)) + if (duplicatesFinder.TryAdd(property, null)) { - duplicatesFinder.Add(property, null); PSPropertyExpression expr = new PSPropertyExpression(property, true); retVal.Add(new MshResolvedExpressionParameterAssociation(null, expr)); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 5125283df5b..bf3acfab2a1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -71,7 +71,7 @@ public PSPropertyExpression(string s, bool isResolved) { if (string.IsNullOrEmpty(s)) { - throw PSTraceSource.NewArgumentNullException("s"); + throw PSTraceSource.NewArgumentNullException(nameof(s)); } _stringValue = s; @@ -87,7 +87,7 @@ public PSPropertyExpression(ScriptBlock scriptBlock) { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentNullException("scriptBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } Script = scriptBlock; @@ -110,7 +110,7 @@ public override string ToString() } /// - /// Resolve the names matched by this the expression. + /// Resolve the names matched by the expression. /// /// The object to apply the expression against. public List ResolveNames(PSObject target) @@ -133,7 +133,7 @@ public bool HasWildCardCharacters } /// - /// Resolve the names matched by this the expression. + /// Resolve the names matched by the expression. /// /// The object to apply the expression against. /// If the matched properties are property sets, expand them. diff --git a/src/System.Management.Automation/FormatAndOutput/format-default/format-default.cs b/src/System.Management.Automation/FormatAndOutput/format-default/format-default.cs index 2cd756ad772..4a6540afb4d 100644 --- a/src/System.Management.Automation/FormatAndOutput/format-default/format-default.cs +++ b/src/System.Management.Automation/FormatAndOutput/format-default/format-default.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index fb6402b1ec7..b6cde18fb65 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // NOTE: define this if you want to test the output on US machine and ASCII @@ -153,7 +153,7 @@ internal sealed class ConsoleLineOutput : LineOutput { #region tracer [TraceSource("ConsoleLineOutput", "ConsoleLineOutput")] - internal static PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); + internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); #endregion tracer #region LineOutput implementation @@ -252,9 +252,9 @@ internal override DisplayCells DisplayCells internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) { if (hostConsole == null) - throw PSTraceSource.NewArgumentNullException("hostConsole"); + throw PSTraceSource.NewArgumentNullException(nameof(hostConsole)); if (errorContext == null) - throw PSTraceSource.NewArgumentNullException("errorContext"); + throw PSTraceSource.NewArgumentNullException(nameof(errorContext)); _console = hostConsole; _errorContext = errorContext; @@ -474,7 +474,7 @@ private class PromptHandler internal PromptHandler(string s, ConsoleLineOutput cmdlet) { if (string.IsNullOrEmpty(s)) - throw PSTraceSource.NewArgumentNullException("s"); + throw PSTraceSource.NewArgumentNullException(nameof(s)); _promptString = s; _callingCmdlet = cmdlet; diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 53f5c09e86b..e7afeda5e15 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs b/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs index 2956889bc29..5a6f2bd0683 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-textInterface/OutTextInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index cda0fcbe6d8..9a036a28249 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -14,21 +14,21 @@ - + - - - - - - - - - - + + + + + + + + + + - + diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index 87c7fc991ac..23c7a09c4f2 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index f1643c7777d..81a4c33062f 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -21,8 +21,8 @@ public sealed class MethodInvocationInfo /// Return value of the method (ok to pass null if the method doesn't return anything). public MethodInvocationInfo(string name, IEnumerable parameters, MethodParameter returnValue) { - if (name == null) throw new ArgumentNullException("name"); - if (parameters == null) throw new ArgumentNullException("parameters"); + if (name == null) throw new ArgumentNullException(nameof(name)); + if (parameters == null) throw new ArgumentNullException(nameof(parameters)); // returnValue can be null MethodName = name; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs index 70a6a4a87a4..d9b08b27179 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodParameter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs index 098303c2118..f52021fb2b0 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodParametersCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index 90a4c3a0836..289ad0c3a76 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -19,22 +19,22 @@ internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, { if (cmdlet == null) { - throw new ArgumentNullException("cmdlet"); + throw new ArgumentNullException(nameof(cmdlet)); } if (string.IsNullOrEmpty(className)) { - throw new ArgumentNullException("className"); + throw new ArgumentNullException(nameof(className)); } if (classVersion == null) // possible and ok to have classVersion==string.Empty { - throw new ArgumentNullException("classVersion"); + throw new ArgumentNullException(nameof(classVersion)); } if (privateData == null) { - throw new ArgumentNullException("privateData"); + throw new ArgumentNullException(nameof(privateData)); } _cmdlet = cmdlet; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs b/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs index e6d7751a566..a1ce1d726ec 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index e32cd1ee2a9..3757319c9ab 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -2101,6 +2101,7 @@ private void WriteGetCmdlet(TextWriter output) } private static object s_enumCompilationLock = new object(); + private static void CompileEnum(EnumMetadataEnum enumMetadata) { try diff --git a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs index e9de925e3da..4ce8a854487 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/cim/WildcardPatternToCimQueryParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index e6425a51056..8614c6a3994 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Xml.Serialization; diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 1c9a66549ad..9c53032284e 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if CORECLR diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs index 43f0817c92c..e2b87d4adf9 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // PLEASE DO NOT EDIT THIS FILE BY HAND!!! diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs index 3711ad54ced..f4892b51bc1 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // PLEASE DO NOT EDIT THIS FILE BY HAND!!! diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd index f96c261d9c0..0766b785451 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd @@ -1,6 +1,6 @@ @@ -224,7 +224,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) { if (adaptedProperty == null) { - throw new ArgumentNullException("adaptedProperty"); + throw new ArgumentNullException(nameof(adaptedProperty)); } CimProperty cimProperty = adaptedProperty.Tag as CimProperty; @@ -239,7 +239,7 @@ public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) return cimInstance.GetCimSessionComputerName(); } - throw new ArgumentNullException("adaptedProperty"); + throw new ArgumentNullException(nameof(adaptedProperty)); } private void AddTypeNameHierarchy(IList typeNamesWithNamespace, IList typeNamesWithoutNamespace, string namespaceName, string className) @@ -288,7 +288,7 @@ public override Collection GetTypeNameHierarchy(object baseObject) var cimInstance = baseObject as CimInstance; if (cimInstance == null) { - throw new ArgumentNullException("baseObject"); + throw new ArgumentNullException(nameof(baseObject)); } var typeNamesWithNamespace = new List(); @@ -381,7 +381,7 @@ public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object { if (adaptedProperty == null) { - throw new ArgumentNullException("adaptedProperty"); + throw new ArgumentNullException(nameof(adaptedProperty)); } if (!IsSettable(adaptedProperty)) diff --git a/src/System.Management.Automation/engine/AliasInfo.cs b/src/System.Management.Automation/engine/AliasInfo.cs index b6caa6b7598..bd209c6afe8 100644 --- a/src/System.Management.Automation/engine/AliasInfo.cs +++ b/src/System.Management.Automation/engine/AliasInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index 106696a28ef..9e785aee935 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -39,12 +39,12 @@ internal ApplicationInfo(string name, string path, ExecutionContext context) : b { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } Path = path; diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index 746d2f82df3..e9b6be3caff 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 8d3eaa08343..99433b32d0f 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index 0f04d99057f..1254e4027e1 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Linq; diff --git a/src/System.Management.Automation/engine/AutomationNull.cs b/src/System.Management.Automation/engine/AutomationNull.cs index e74258bf354..6dec6aeabb7 100644 --- a/src/System.Management.Automation/engine/AutomationNull.cs +++ b/src/System.Management.Automation/engine/AutomationNull.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Internal diff --git a/src/System.Management.Automation/engine/COM/ComAdapter.cs b/src/System.Management.Automation/engine/COM/ComAdapter.cs index 257638f7645..75e95b6082a 100644 --- a/src/System.Management.Automation/engine/COM/ComAdapter.cs +++ b/src/System.Management.Automation/engine/COM/ComAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/COM/ComDispatch.cs b/src/System.Management.Automation/engine/COM/ComDispatch.cs index 0daeea783aa..9199ef9f48f 100644 --- a/src/System.Management.Automation/engine/COM/ComDispatch.cs +++ b/src/System.Management.Automation/engine/COM/ComDispatch.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.InteropServices; diff --git a/src/System.Management.Automation/engine/COM/ComInvoker.cs b/src/System.Management.Automation/engine/COM/ComInvoker.cs index f315b36b7b8..3834be3de8e 100644 --- a/src/System.Management.Automation/engine/COM/ComInvoker.cs +++ b/src/System.Management.Automation/engine/COM/ComInvoker.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Linq; @@ -352,12 +352,16 @@ internal struct TypeUnion { [FieldOffset(0)] internal ushort _vt; + [FieldOffset(2)] internal ushort _wReserved1; + [FieldOffset(4)] internal ushort _wReserved2; + [FieldOffset(6)] internal ushort _wReserved3; + [FieldOffset(8)] internal UnionTypes _unionTypes; } @@ -374,46 +378,67 @@ internal struct UnionTypes { [FieldOffset(0)] internal sbyte _i1; + [FieldOffset(0)] internal Int16 _i2; + [FieldOffset(0)] internal Int32 _i4; + [FieldOffset(0)] internal Int64 _i8; + [FieldOffset(0)] internal byte _ui1; + [FieldOffset(0)] internal UInt16 _ui2; + [FieldOffset(0)] internal UInt32 _ui4; + [FieldOffset(0)] internal UInt64 _ui8; + [FieldOffset(0)] internal Int32 _int; + [FieldOffset(0)] internal UInt32 _uint; + [FieldOffset(0)] internal Int16 _bool; + [FieldOffset(0)] internal Int32 _error; + [FieldOffset(0)] internal Single _r4; + [FieldOffset(0)] internal double _r8; + [FieldOffset(0)] internal Int64 _cy; + [FieldOffset(0)] internal double _date; + [FieldOffset(0)] internal IntPtr _bstr; + [FieldOffset(0)] internal IntPtr _unknown; + [FieldOffset(0)] internal IntPtr _dispatch; + [FieldOffset(0)] internal IntPtr _pvarVal; + [FieldOffset(0)] internal IntPtr _byref; + [FieldOffset(0)] internal Record _record; } diff --git a/src/System.Management.Automation/engine/COM/ComMethod.cs b/src/System.Management.Automation/engine/COM/ComMethod.cs index 9dd28fe3911..32552c6bd14 100644 --- a/src/System.Management.Automation/engine/COM/ComMethod.cs +++ b/src/System.Management.Automation/engine/COM/ComMethod.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/engine/COM/ComProperty.cs b/src/System.Management.Automation/engine/COM/ComProperty.cs index c4b19e8a87e..2de108a872e 100644 --- a/src/System.Management.Automation/engine/COM/ComProperty.cs +++ b/src/System.Management.Automation/engine/COM/ComProperty.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index 64d07872c61..6a03f31c9ac 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/COM/ComUtil.cs b/src/System.Management.Automation/engine/COM/ComUtil.cs index 44e307a69b5..4d5a9964339 100644 --- a/src/System.Management.Automation/engine/COM/ComUtil.cs +++ b/src/System.Management.Automation/engine/COM/ComUtil.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -411,41 +411,7 @@ internal static ComEnumerator Create(object comObject) // The passed-in COM object could already be a IEnumVARIANT interface. // e.g. user call '_NewEnum()' on a COM collection interface. var enumVariant = comObject as COM.IEnumVARIANT; - if (enumVariant != null) - { - return new ComEnumerator(enumVariant); - } - - // The passed-in COM object could be a collection. - var enumerable = comObject as IEnumerable; - var target = comObject as IDispatch; - if (enumerable != null && target != null) - { - try - { - var comTypeInfo = ComTypeInfo.GetDispatchTypeInfo(comObject); - if (comTypeInfo != null && comTypeInfo.NewEnumInvokeKind.HasValue) - { - // The COM object is a collection and also a IDispatch interface, so we try to get a - // IEnumVARIANT interface out of it by invoking its '_NewEnum (DispId: -4)' function. - var result = ComInvoker.Invoke(target, ComTypeInfo.DISPID_NEWENUM, - args: Array.Empty(), byRef: null, - invokeKind: comTypeInfo.NewEnumInvokeKind.Value); - enumVariant = result as COM.IEnumVARIANT; - if (enumVariant != null) - { - return new ComEnumerator(enumVariant); - } - } - } - catch (Exception) - { - // Ignore exceptions. In case of exception, no enumerator can be created - // for the passed-in COM object, and we will return null eventually. - } - } - - return null; + return enumVariant != null ? new ComEnumerator(enumVariant) : null; } } } diff --git a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs index 46c8f40d06a..85cff4c8efb 100644 --- a/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ChildrenCmdletProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -35,7 +35,7 @@ internal ChildItemCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } _cmdlet = cmdlet; @@ -55,7 +55,7 @@ internal ChildItemCmdletProviderIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs index 9d40f77b6b1..27537b21601 100644 --- a/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/CmdletFamilyProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -38,7 +38,7 @@ internal ProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } _cmdlet = cmdlet; @@ -59,7 +59,7 @@ internal ProviderIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } Item = new ItemCmdletProviderIntrinsics(sessionState); diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 8cfec82613d..2861fa3a8b6 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -44,7 +44,7 @@ internal CmdletInfo( { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } // Get the verb and noun from the name @@ -52,7 +52,7 @@ internal CmdletInfo( { throw PSTraceSource.NewArgumentException( - "name", + nameof(name), DiscoveryExceptions.InvalidCmdletNameFormat, name); } @@ -105,12 +105,12 @@ public CmdletInfo(string name, Type implementingType) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (implementingType == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (!typeof(Cmdlet).IsAssignableFrom(implementingType)) @@ -123,7 +123,7 @@ public CmdletInfo(string name, Type implementingType) { throw PSTraceSource.NewArgumentException( - "name", + nameof(name), DiscoveryExceptions.InvalidCmdletNameFormat, name); } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 4991d2623b1..069201589af 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -54,12 +54,12 @@ internal CmdletParameterBinderController( { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } if (commandMetadata == null) { - throw PSTraceSource.NewArgumentNullException("commandMetadata"); + throw PSTraceSource.NewArgumentNullException(nameof(commandMetadata)); } this.Command = cmdlet; @@ -3173,7 +3173,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys for (int i = 0; i < parameterName.Length; i++) { // try Upper case - if (char.IsUpper(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1)) + if (char.IsUpper(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i])) { label.Insert(i, hotKeyPrefix); usedHotKeys.Append(parameterName[i]); @@ -3187,7 +3187,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys // try Lower case for (int i = 0; i < parameterName.Length; i++) { - if (char.IsLower(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1)) + if (char.IsLower(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i])) { label.Insert(i, hotKeyPrefix); usedHotKeys.Append(parameterName[i]); @@ -3202,7 +3202,7 @@ private static string BuildLabel(string parameterName, StringBuilder usedHotKeys // try non-letters for (int i = 0; i < parameterName.Length; i++) { - if (!char.IsLetter(parameterName[i]) && (usedHotKeysStr.IndexOf(parameterName[i]) == -1)) + if (!char.IsLetter(parameterName[i]) && usedHotKeysStr.Contains(parameterName[i])) { label.Insert(i, hotKeyPrefix); usedHotKeys.Append(parameterName[i]); @@ -4275,7 +4275,7 @@ private void RestoreDefaultParameterValues(IEnumerable diff --git a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs index 8adc529cbbd..bf16a2f2c5d 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs index 44bdaa91316..79ba5d8f2a4 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComObject.cs b/src/System.Management.Automation/engine/ComInterop/ComObject.cs index ae8eacd1ad9..65ac238a06c 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs index c0c6e0b113c..e98f23cdc93 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComParamDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs index 8f709624b73..c421fe09ac9 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComType.cs b/src/System.Management.Automation/engine/ComInterop/ComType.cs index 7adb8026dad..fe76e682495 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComType.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComType.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs index 6e375983270..fcd9fc51bcc 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index 474efd75881..12375c978fb 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject @@ -192,10 +192,7 @@ internal string[] GetMemberNames(bool dataOnly) { foreach (string name in Events.Keys) { - if (!names.ContainsKey(name)) - { - names.Add(name, null); - } + names.TryAdd(name, null); } } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs index d3454fe2ab1..c873a1f8d5e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 48a3276cb21..5bded65e70a 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs index e2ae7ab65e6..5863424275d 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs index 5e8ce696cb1..494425213b0 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibMemberDesc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs index a9dc572b1bd..caff255c02a 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConversionArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs index 08f6be519a5..e177898e6d1 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConvertArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs index 66f60c94754..4c446b7ac95 100644 --- a/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ConvertibleArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs index 68c4ecfc260..3ad1264b2d0 100644 --- a/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/CurrencyArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs index 39e18316b3d..a69037ab3f7 100644 --- a/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/DateTimeArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs index c2da035a4be..aba2fc5f6f2 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs index d83025aca0e..130eaa524c2 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallableMetaObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs index ebfdb4868a6..1c0c0b23dc5 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispatchArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs index 784401399f9..e0a95e37bce 100644 --- a/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ErrorArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/Errors.cs b/src/System.Management.Automation/engine/ComInterop/Errors.cs index abe1775e6e8..0756a1f5312 100644 --- a/src/System.Management.Automation/engine/ComInterop/Errors.cs +++ b/src/System.Management.Automation/engine/ComInterop/Errors.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.ComInterop diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index ff73c782036..c1a937fd318 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 908c5a18c2a..d29462d235c 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !CLR2 diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index f2ee582089a..bb8a2eeb5a8 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index 2f7859a067c..9a4c9693c27 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs b/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs index 6ad943edcc7..9ab6c1aae65 100644 --- a/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IPseudoComObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !CLR2 diff --git a/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs index fda43e814be..d5747f6fc68 100644 --- a/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/NullArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs index 1050f0695f5..1df83daf12b 100644 --- a/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/SimpleArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs index a5b772373a2..07ad10f6bac 100644 --- a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs +++ b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !CLR2 diff --git a/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs index 89291cd5cfa..437407baf7d 100644 --- a/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/StringArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs index e43956280d6..4a07e275836 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeEnumMetaObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs index cd9d2501c5b..88035265236 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibInfoMetaObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs index 72032d65b66..a4eab6f7ad5 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeLibMetaObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT diff --git a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs index 0b406c56cd5..ab82f854f28 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !CLR2 diff --git a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs index 2b10d677250..552e262c859 100644 --- a/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/UnknownArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index fd8d156e8da..4a5bbe746a1 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.cs b/src/System.Management.Automation/engine/ComInterop/Variant.cs index 5e5e1d49c8b..0e1561fbe17 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs index 980f239f23f..b8a2b8c5e27 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArgBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs index d8c0a90384b..0277e03f191 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject @@ -77,7 +77,7 @@ internal static Type GetStructType(int args) // See if we can find an existing type foreach (Type t in s_generatedTypes) { - int arity = int.Parse(t.Name.Substring("VariantArray".Length), CultureInfo.InvariantCulture); + int arity = int.Parse(t.Name.AsSpan("VariantArray".Length), NumberStyles.Integer, CultureInfo.InvariantCulture); if (size == arity) { return t; diff --git a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs index 216bc443a54..06d449ece27 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !SILVERLIGHT // ComObject diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index c192ac3ffbf..720a93ab85d 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -484,7 +484,7 @@ public PathInfo CurrentProviderLocation(string providerId) { if (providerId == null) { - throw PSTraceSource.NewArgumentNullException("providerId"); + throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } PathInfo result = SessionState.Path.CurrentProviderLocation(providerId); diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 3297f8bf15c..7af3fb62fb4 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -56,6 +56,7 @@ public CommandCompletion(Collection matches, int currentMatchI public Collection CompletionMatches { get; set; } internal static readonly IList EmptyCompletionResult = Array.Empty(); + private static readonly CommandCompletion s_emptyCommandCompletion = new CommandCompletion( new Collection(EmptyCompletionResult), -1, -1, -1); @@ -72,7 +73,7 @@ public static Tuple MapStringInputToParsedInput(s { if (cursorIndex > input.Length) { - throw PSTraceSource.NewArgumentException("cursorIndex"); + throw PSTraceSource.NewArgumentException(nameof(cursorIndex)); } Token[] tokens; @@ -112,17 +113,17 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo { if (ast == null) { - throw PSTraceSource.NewArgumentNullException("ast"); + throw PSTraceSource.NewArgumentNullException(nameof(ast)); } if (tokens == null) { - throw PSTraceSource.NewArgumentNullException("tokens"); + throw PSTraceSource.NewArgumentNullException(nameof(tokens)); } if (positionOfCursor == null) { - throw PSTraceSource.NewArgumentNullException("positionOfCursor"); + throw PSTraceSource.NewArgumentNullException(nameof(positionOfCursor)); } return CompleteInputImpl(ast, tokens, positionOfCursor, options); @@ -147,12 +148,12 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has if (cursorIndex > input.Length) { - throw PSTraceSource.NewArgumentException("cursorIndex"); + throw PSTraceSource.NewArgumentException(nameof(cursorIndex)); } if (powershell == null) { - throw PSTraceSource.NewArgumentNullException("powershell"); + throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } // If we are in a debugger stop, let the debugger do the command completion. @@ -216,22 +217,22 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo { if (ast == null) { - throw PSTraceSource.NewArgumentNullException("ast"); + throw PSTraceSource.NewArgumentNullException(nameof(ast)); } if (tokens == null) { - throw PSTraceSource.NewArgumentNullException("tokens"); + throw PSTraceSource.NewArgumentNullException(nameof(tokens)); } if (cursorPosition == null) { - throw PSTraceSource.NewArgumentNullException("cursorPosition"); + throw PSTraceSource.NewArgumentNullException(nameof(cursorPosition)); } if (powershell == null) { - throw PSTraceSource.NewArgumentNullException("powershell"); + throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } // If we are in a debugger stop, let the debugger do the command completion. @@ -334,12 +335,12 @@ internal static CommandCompletion CompleteInputInDebugger(string input, int curs if (cursorIndex > input.Length) { - throw PSTraceSource.NewArgumentException("cursorIndex"); + throw PSTraceSource.NewArgumentException(nameof(cursorIndex)); } if (debugger == null) { - throw PSTraceSource.NewArgumentNullException("debugger"); + throw PSTraceSource.NewArgumentNullException(nameof(debugger)); } Command cmd = new Command("TabExpansion2"); @@ -363,22 +364,22 @@ internal static CommandCompletion CompleteInputInDebugger(Ast ast, Token[] token { if (ast == null) { - throw PSTraceSource.NewArgumentNullException("ast"); + throw PSTraceSource.NewArgumentNullException(nameof(ast)); } if (tokens == null) { - throw PSTraceSource.NewArgumentNullException("tokens"); + throw PSTraceSource.NewArgumentNullException(nameof(tokens)); } if (cursorPosition == null) { - throw PSTraceSource.NewArgumentNullException("cursorPosition"); + throw PSTraceSource.NewArgumentNullException(nameof(cursorPosition)); } if (debugger == null) { - throw PSTraceSource.NewArgumentNullException("debugger"); + throw PSTraceSource.NewArgumentNullException(nameof(debugger)); } // For remote debugging just pass string input. diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index 8d533edc3e5..1a5f0989b8f 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -1514,19 +1514,18 @@ private List GetResultForString(CompletionContext completionCo var analysis = new CompletionAnalysis(_ast, _tokens, _cursorPosition, _options); var subContext = analysis.CreateCompletionContext(completionContext.TypeInferenceContext); - int subReplaceIndex, subReplaceLength; - var subResult = analysis.GetResultHelper(subContext, out subReplaceIndex, out subReplaceLength, true); + var subResult = analysis.GetResultHelper(subContext, out int subReplaceIndex, out _, true); if (subResult != null && subResult.Count > 0) { result = new List(); replacementIndex = stringStartIndex + 1 + (cursorIndexInString - subInput.Length); replacementLength = subInput.Length; - string prefix = subInput.Substring(0, subReplaceIndex); + ReadOnlySpan prefix = subInput.AsSpan(0, subReplaceIndex); foreach (CompletionResult entry in subResult) { - string completionText = prefix + entry.CompletionText; + string completionText = string.Concat(prefix, entry.CompletionText.AsSpan()); if (entry.ResultType == CompletionResultType.Property) { completionText = TokenKind.DollarParen.Text() + completionText + TokenKind.RParen.Text(); @@ -1565,7 +1564,7 @@ private List GetResultForString(CompletionContext completionCo result = new List(CompletionCompleters.CompleteFilename(completionContext)); // Try command name completion only if the text contains '-' - if (wordToComplete.IndexOf('-') != -1) + if (wordToComplete.Contains('-')) { var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); if (commandNameResult != null && commandNameResult.Count > 0) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index f52e9f79b28..e00302a1eb4 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -207,7 +207,8 @@ List ExecuteGetCommandCommand(bool useModulePrefix) } private static readonly HashSet s_keywordsToExcludeFromAddingAmpersand - = new HashSet(StringComparer.OrdinalIgnoreCase) { TokenKind.InlineScript.ToString(), TokenKind.Configuration.ToString() }; + = new HashSet(StringComparer.OrdinalIgnoreCase) { nameof(TokenKind.InlineScript), nameof(TokenKind.Configuration) }; + internal static CompletionResult GetCommandNameCompletionResult(string name, object command, bool addAmpersandIfNecessary, string quote) { string syntax = name, listItem = name; @@ -1164,7 +1165,7 @@ internal static List CompleteCommandArgument(CompletionContext var tryCmdletCompletion = false; var clearLiteralPathsKey = TurnOnLiteralPathOption(context); - if (context.WordToComplete.IndexOf('-') != -1) + if (context.WordToComplete.Contains('-')) { tryCmdletCompletion = true; } @@ -1224,7 +1225,7 @@ internal static List CompleteCommandArgument(CompletionContext } // Handle member completion with wildcard: echo $a.* - if (pathAst.Value.IndexOf('*') != -1 && secondToLastMemberAst != null && + if (pathAst.Value.Contains('*') && secondToLastMemberAst != null && secondToLastMemberAst.Extent.EndLineNumber == pathAst.Extent.StartLineNumber && secondToLastMemberAst.Extent.EndColumnNumber == pathAst.Extent.StartColumnNumber) { @@ -1328,7 +1329,7 @@ internal static List CompleteCommandArgument(CompletionContext context.Options.Remove("LiteralPaths"); } - if (context.WordToComplete != string.Empty && context.WordToComplete.IndexOf('-') != -1) + if (context.WordToComplete != string.Empty && context.WordToComplete.Contains('-')) { var commandResults = CompleteCommand(context); if (commandResults != null) @@ -1687,7 +1688,7 @@ private static void ProcessParameter( string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(parameterType); string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries); + string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); string wordToComplete = context.WordToComplete; string quote = HandleDoubleAndSingleQuote(ref wordToComplete); @@ -3844,7 +3845,7 @@ private static void NativeCompletionTypeName(CompletionContext context, List CompleteVariable(string variableName } private static readonly string[] s_variableScopes = new string[] { "Global:", "Local:", "Script:", "Private:" }; + private static readonly char[] s_charactersRequiringQuotes = new char[] { '-', '`', '&', '@', '\'', '"', '#', '{', '}', '(', ')', '$', ',', ';', '|', '<', '>', ' ', '.', '\\', '/', '\t', '^', }; @@ -5632,7 +5635,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string // If the completion included a namespace and ToStringCodeMethods.Type found // an accelerator, then just use the type's FullName instead because the user // probably didn't want the accelerator. - if (keyMatched.IndexOf('.') != -1 && completion.IndexOf('.') == -1) + if (keyMatched.Contains('.') && !completion.Contains('.')) { completion = Type.FullName; } @@ -5720,6 +5723,7 @@ private class TypeCompletionMapping } private static TypeCompletionMapping[][] s_typeCache; + private static TypeCompletionMapping[][] InitializeTypeCache() { #region Process_TypeAccelerators @@ -6151,7 +6155,7 @@ internal static List CompleteStatementFlags(TokenKind kind, st string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(SwitchFlags)); string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries); + string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var enumList = new List(); @@ -6624,9 +6628,9 @@ internal static void CompleteMemberHelper( } string tooltip = memberInfo.ToString(); - if (tooltip.IndexOf("),", StringComparison.Ordinal) != -1) + if (tooltip.Contains("),", StringComparison.Ordinal)) { - var overloads = tooltip.Split(new[] { ")," }, StringSplitOptions.RemoveEmptyEntries); + var overloads = tooltip.Split("),", StringSplitOptions.RemoveEmptyEntries); var newTooltip = new StringBuilder(); foreach (var overload in overloads) { diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index 50f3e946d3f..3fe4a54e023 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -170,22 +170,22 @@ public CompletionResult(string completionText, string listItemText, CompletionRe { if (string.IsNullOrEmpty(completionText)) { - throw PSTraceSource.NewArgumentNullException("completionText"); + throw PSTraceSource.NewArgumentNullException(nameof(completionText)); } if (string.IsNullOrEmpty(listItemText)) { - throw PSTraceSource.NewArgumentNullException("listItemText"); + throw PSTraceSource.NewArgumentNullException(nameof(listItemText)); } if (resultType < CompletionResultType.Text || resultType > CompletionResultType.DynamicKeyword) { - throw PSTraceSource.NewArgumentOutOfRangeException("resultType", resultType); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(resultType), resultType); } if (string.IsNullOrEmpty(toolTip)) { - throw PSTraceSource.NewArgumentNullException("toolTip"); + throw PSTraceSource.NewArgumentNullException(nameof(toolTip)); } _completionText = completionText; diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 0689647185f..9bb33ef56ba 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -34,7 +34,7 @@ public ArgumentCompleterAttribute(Type type) { if (type == null || (type.GetInterfaces().All(t => t != typeof(IArgumentCompleter)))) { - throw PSTraceSource.NewArgumentException("type"); + throw PSTraceSource.NewArgumentException(nameof(type)); } Type = type; @@ -48,7 +48,7 @@ public ArgumentCompleterAttribute(ScriptBlock scriptBlock) { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentNullException("scriptBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } ScriptBlock = scriptBlock; @@ -176,12 +176,12 @@ public ArgumentCompletionsAttribute(params string[] completions) { if (completions == null) { - throw PSTraceSource.NewArgumentNullException("completions"); + throw PSTraceSource.NewArgumentNullException(nameof(completions)); } if (completions.Length == 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("completions", completions); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(completions), completions); } _completions = completions; diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 2b13ccf56a6..d19a4b9bddb 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -75,7 +75,7 @@ internal sealed class PipeObjectPair : AstParameterArgumentPair internal PipeObjectPair(string parameterName, Type pipeObjType) { if (parameterName == null) - throw PSTraceSource.NewArgumentNullException("parameterName"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); Parameter = null; ParameterArgumentType = AstParameterArgumentType.PipeObject; @@ -96,9 +96,9 @@ internal sealed class AstArrayPair : AstParameterArgumentPair internal AstArrayPair(string parameterName, ICollection arguments) { if (parameterName == null) - throw PSTraceSource.NewArgumentNullException("parameterName"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); if (arguments == null || arguments.Count == 0) - throw PSTraceSource.NewArgumentNullException("arguments"); + throw PSTraceSource.NewArgumentNullException(nameof(arguments)); Parameter = null; ParameterArgumentType = AstParameterArgumentType.AstArray; @@ -125,7 +125,7 @@ internal sealed class FakePair : AstParameterArgumentPair internal FakePair(CommandParameterAst parameterAst) { if (parameterAst == null) - throw PSTraceSource.NewArgumentNullException("parameterAst"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterAst)); Parameter = parameterAst; ParameterArgumentType = AstParameterArgumentType.Fake; @@ -145,7 +145,7 @@ internal sealed class SwitchPair : AstParameterArgumentPair internal SwitchPair(CommandParameterAst parameterAst) { if (parameterAst == null) - throw PSTraceSource.NewArgumentNullException("parameterAst"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterAst)); Parameter = parameterAst; ParameterArgumentType = AstParameterArgumentType.Switch; @@ -175,7 +175,7 @@ internal sealed class AstPair : AstParameterArgumentPair internal AstPair(CommandParameterAst parameterAst) { if (parameterAst == null || parameterAst.Argument == null) - throw PSTraceSource.NewArgumentException("parameterAst"); + throw PSTraceSource.NewArgumentException(nameof(parameterAst)); Parameter = parameterAst; ParameterArgumentType = AstParameterArgumentType.AstPair; @@ -192,10 +192,10 @@ internal AstPair(CommandParameterAst parameterAst) internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) { if (parameterAst != null && parameterAst.Argument != null) - throw PSTraceSource.NewArgumentException("parameterAst"); + throw PSTraceSource.NewArgumentException(nameof(parameterAst)); if (parameterAst == null && argumentAst == null) - throw PSTraceSource.NewArgumentNullException("argumentAst"); + throw PSTraceSource.NewArgumentNullException(nameof(argumentAst)); Parameter = parameterAst; ParameterArgumentType = AstParameterArgumentType.AstPair; @@ -212,10 +212,10 @@ internal AstPair(CommandParameterAst parameterAst, ExpressionAst argumentAst) internal AstPair(CommandParameterAst parameterAst, CommandElementAst argumentAst) { if (parameterAst != null && parameterAst.Argument != null) - throw PSTraceSource.NewArgumentException("parameterAst"); + throw PSTraceSource.NewArgumentException(nameof(parameterAst)); if (parameterAst == null || argumentAst == null) - throw PSTraceSource.NewArgumentNullException("argumentAst"); + throw PSTraceSource.NewArgumentNullException(nameof(argumentAst)); Parameter = parameterAst; ParameterArgumentType = AstParameterArgumentType.AstPair; @@ -332,17 +332,17 @@ public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolv { // Handle static binding from a non-PowerShell / C# application // DefaultRunspace is a thread static field, so race condition will not happen because different threads will access different instances of "DefaultRunspace" - if (s_bindCommandRunspace == null) + if (t_bindCommandRunspace == null) { // Create a mini runspace by remove the types and formats InitialSessionState minimalState = InitialSessionState.CreateDefault2(); minimalState.Types.Clear(); minimalState.Formats.Clear(); - s_bindCommandRunspace = RunspaceFactory.CreateRunspace(minimalState); - s_bindCommandRunspace.Open(); + t_bindCommandRunspace = RunspaceFactory.CreateRunspace(minimalState); + t_bindCommandRunspace.Open(); } - Runspace.DefaultRunspace = s_bindCommandRunspace; + Runspace.DefaultRunspace = t_bindCommandRunspace; // Static binding always does argument binding (not argument or parameter completion). pseudoBinding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentBinding); Runspace.DefaultRunspace = null; @@ -357,7 +357,7 @@ public static StaticBindingResult BindCommand(CommandAst commandAst, bool resolv } [ThreadStatic] - static Runspace s_bindCommandRunspace = null; + private static Runspace t_bindCommandRunspace = null; } /// @@ -949,7 +949,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } // initialize/reset the private members diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index 3333a3f81f8..4737fe18d78 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -115,7 +115,7 @@ public enum PSModuleAutoLoadingPreference internal class CommandDiscovery { [TraceSource("CommandDiscovery", "Traces the discovery of cmdlets, scripts, functions, applications, etc.")] - internal static PSTraceSource discoveryTracer = + internal static readonly PSTraceSource discoveryTracer = PSTraceSource.GetTracer( "CommandDiscovery", "Traces the discovery of cmdlets, scripts, functions, applications, etc.", @@ -133,7 +133,7 @@ internal CommandDiscovery(ExecutionContext context) { if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } Context = context; @@ -202,7 +202,7 @@ internal CmdletInfo AddCmdletInfoToCache(string name, CmdletInfo newCmdletInfo, { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (newCmdletInfo == null) @@ -1525,7 +1525,7 @@ internal static PSModuleAutoLoadingPreference GetCommandDiscoveryPreference(Exec if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } // check the PSVariable @@ -1687,7 +1687,7 @@ internal Collection IndexOfRelativePath() { if (string.IsNullOrEmpty(item)) { - throw PSTraceSource.NewArgumentException("item"); + throw PSTraceSource.NewArgumentException(nameof(item)); } int result = -1; @@ -1710,7 +1710,7 @@ internal Collection IndexOfRelativePath() [EventSource(Name = "Microsoft-PowerShell-CommandDiscovery")] internal class CommandDiscoveryEventSource : EventSource { - internal static CommandDiscoveryEventSource Log = new CommandDiscoveryEventSource(); + internal static readonly CommandDiscoveryEventSource Log = new CommandDiscoveryEventSource(); public void CommandLookupStart(string CommandName) { WriteEvent(1, CommandName); } diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 4587707b150..1090a3fbb86 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -112,7 +112,7 @@ internal CommandInfo(string name, CommandTypes type) if (name == null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Name = name; @@ -287,7 +287,7 @@ internal void Rename(string newName) { if (string.IsNullOrEmpty(newName)) { - throw new ArgumentNullException("newName"); + throw new ArgumentNullException(nameof(newName)); } Name = newName; @@ -800,7 +800,7 @@ public PSTypeName(TypeDefinitionAst typeDefinitionAst) { if (typeDefinitionAst == null) { - throw PSTraceSource.NewArgumentNullException("typeDefinitionAst"); + throw PSTraceSource.NewArgumentNullException(nameof(typeDefinitionAst)); } TypeDefinitionAst = typeDefinitionAst; @@ -814,7 +814,7 @@ public PSTypeName(ITypeName typeName) { if (typeName == null) { - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } _type = typeName.GetReflectionType(); diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index 2548d05bc57..edcd9a9cd66 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -105,7 +105,7 @@ public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParamet { if (commandInfo == null) { - throw PSTraceSource.NewArgumentNullException("commandInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } while (commandInfo is AliasInfo) { @@ -162,7 +162,7 @@ public CommandMetadata(CommandMetadata other) { if (other == null) { - throw PSTraceSource.NewArgumentNullException("other"); + throw PSTraceSource.NewArgumentNullException(nameof(other)); } Name = other.Name; @@ -315,7 +315,7 @@ internal static CommandMetadata Get(string commandName, Type cmdletType, Executi { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentException("commandName"); + throw PSTraceSource.NewArgumentException(nameof(commandName)); } CommandMetadata result = null; @@ -369,7 +369,7 @@ internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext c { if (string.IsNullOrEmpty(commandName)) { - throw PSTraceSource.NewArgumentException("commandName"); + throw PSTraceSource.NewArgumentException(nameof(commandName)); } Name = commandName; @@ -412,7 +412,7 @@ internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionC { if (scriptblock == null) { - throw PSTraceSource.NewArgumentException("scriptblock"); + throw PSTraceSource.NewArgumentException(nameof(scriptblock)); } CmdletBindingAttribute cmdletBindingAttribute = scriptblock.CmdletBindingAttribute; @@ -647,6 +647,7 @@ internal uint DefaultParameterSetFlag // The CommandType for a script cmdlet is not CommandTypes.Cmdlet, yet // proxy generation needs to know the difference between script and script cmdlet. private bool _wrappedAnyCmdlet; + internal bool WrappedAnyCmdlet { get { return _wrappedAnyCmdlet; } @@ -725,7 +726,7 @@ private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute) { if (attribute == null) { - throw PSTraceSource.NewArgumentNullException("attribute"); + throw PSTraceSource.NewArgumentNullException(nameof(attribute)); } // Process the default parameter set name diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index 2a93440ff10..0ee5f7855f1 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics; diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index 2a43bb1a834..96c6c8c1953 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -1,14 +1,14 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; -#nullable enable - namespace System.Management.Automation { /// @@ -18,7 +18,7 @@ namespace System.Management.Automation internal class CommandPathSearch : IEnumerable, IEnumerator { [TraceSource("CommandSearch", "CommandSearch")] - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandSearch", "CommandSearch"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CommandSearch", "CommandSearch"); /// /// Constructs a command searching enumerator that resolves the location @@ -44,7 +44,7 @@ internal CommandPathSearch( string commandName, LookupPathCollection lookupPaths, ExecutionContext context, - Collection acceptableCommandNames, + Collection? acceptableCommandNames, bool useFuzzyMatch) { _useFuzzyMatch = useFuzzyMatch; diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index 40fb3eff83f..4433d75ca99 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -104,7 +104,7 @@ internal ParameterBinderController NewParameterBinderController(InternalCommand Cmdlet cmdlet = command as Cmdlet; if (cmdlet == null) { - throw PSTraceSource.NewArgumentException("command"); + throw PSTraceSource.NewArgumentException(nameof(command)); } ParameterBinderBase parameterBinder; @@ -667,6 +667,7 @@ private bool ProcessInputPipelineObject(object inputObject) } private static readonly ConcurrentDictionary> s_constructInstanceCache; + private static Cmdlet ConstructInstance(Type type) { // Call the default constructor if type derives from Cmdlet. diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index 042a69489ca..87fd4606c9f 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -35,7 +35,7 @@ internal CommandProcessorBase(CommandInfo commandInfo) { if (commandInfo == null) { - throw PSTraceSource.NewArgumentNullException("commandInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } if (commandInfo is IScriptCommandInfo scriptCommand) @@ -156,6 +156,7 @@ internal virtual ObsoleteAttribute ObsoleteAttribute /// The command runtime used for this instance of a command processor. /// protected MshCommandRuntime commandRuntime; + internal MshCommandRuntime CommandRuntime { get { return commandRuntime; } @@ -230,6 +231,7 @@ protected static void ValidateCompatibleLanguageMode( /// The execution context used by the system. /// protected ExecutionContext _context; + internal ExecutionContext Context { get { return _context; } @@ -278,12 +280,12 @@ internal static CommandProcessorBase CreateGetHelpCommandProcessor( { if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(helpTarget)) { - throw PSTraceSource.NewArgumentNullException("helpTarget"); + throw PSTraceSource.NewArgumentNullException(nameof(helpTarget)); } CommandProcessorBase helpCommandProcessor = context.CreateCommand("get-help", false); diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 4967024aef4..d3a1033c932 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -1,9 +1,12 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation.Internal; @@ -242,9 +245,9 @@ public bool MoveNext() return false; } - private CommandInfo SearchForAliases() + private CommandInfo? SearchForAliases() { - CommandInfo currentMatch = null; + CommandInfo? currentMatch = null; if (_context.EngineSessionState != null && (_commandTypes & CommandTypes.Alias) != 0) @@ -255,9 +258,9 @@ private CommandInfo SearchForAliases() return currentMatch; } - private CommandInfo SearchForFunctions() + private CommandInfo? SearchForFunctions() { - CommandInfo currentMatch = null; + CommandInfo? currentMatch = null; if (_context.EngineSessionState != null && (_commandTypes & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0) @@ -268,9 +271,9 @@ private CommandInfo SearchForFunctions() return currentMatch; } - private CommandInfo SearchForCmdlets() + private CommandInfo? SearchForCmdlets() { - CommandInfo currentMatch = null; + CommandInfo? currentMatch = null; if ((_commandTypes & CommandTypes.Cmdlet) != 0) { @@ -280,9 +283,9 @@ private CommandInfo SearchForCmdlets() return currentMatch; } - private CommandInfo ProcessBuiltinScriptState() + private CommandInfo? ProcessBuiltinScriptState() { - CommandInfo currentMatch = null; + CommandInfo? currentMatch = null; // Check to see if the path is qualified @@ -296,9 +299,9 @@ private CommandInfo ProcessBuiltinScriptState() return currentMatch; } - private CommandInfo ProcessPathResolutionState() + private CommandInfo? ProcessPathResolutionState() { - CommandInfo currentMatch = null; + CommandInfo? currentMatch = null; try { @@ -338,7 +341,7 @@ private CommandInfo ProcessPathResolutionState() return currentMatch; } - private CommandInfo ProcessQualifiedFileSystemState() + private CommandInfo? ProcessQualifiedFileSystemState() { try { @@ -355,13 +358,14 @@ private CommandInfo ProcessQualifiedFileSystemState() throw; } - CommandInfo currentMatch = null; + CommandInfo? currentMatch = null; _currentState = SearchState.PathSearch; if (_canDoPathLookup) { try { - while (currentMatch == null && _pathSearcher.MoveNext()) + // the previous call to setupPathSearcher ensures _pathSearcher != null + while (currentMatch == null && _pathSearcher!.MoveNext()) { currentMatch = GetInfoFromPath(((IEnumerator)_pathSearcher).Current); } @@ -375,10 +379,10 @@ private CommandInfo ProcessQualifiedFileSystemState() return currentMatch; } - private CommandInfo ProcessPathSearchState() + private CommandInfo? ProcessPathSearchState() { - CommandInfo currentMatch = null; - string path = DoPowerShellRelativePathLookup(); + CommandInfo? currentMatch = null; + string? path = DoPowerShellRelativePathLookup(); if (!string.IsNullOrEmpty(path)) { @@ -443,9 +447,9 @@ public void Dispose() /// /// A CommandInfo for the next command if it exists as a path, or null otherwise. /// - private CommandInfo GetNextFromPath() + private CommandInfo? GetNextFromPath() { - CommandInfo result = null; + CommandInfo? result = null; do // false loop { @@ -478,7 +482,7 @@ private CommandInfo GetNextFromPath() if (!_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns) && resolvedPaths.Count == 0) { - string path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _); + string? path = GetNextLiteralPathThatExistsAndHandleExceptions(_commandName, out _); if (path != null) { @@ -520,7 +524,7 @@ private CommandInfo GetNextFromPath() /// /// A collection of full paths to the commands which were found. /// - private Collection GetNextFromPathUsingWildcards(string command, out ProviderInfo provider) + private Collection GetNextFromPathUsingWildcards(string? command, out ProviderInfo? provider) { try { @@ -594,9 +598,9 @@ private static bool checkPath(string path, string commandName) /// If refers to a cmdlet file that /// contains invalid metadata. /// - private CommandInfo GetInfoFromPath(string path) + private CommandInfo? GetInfoFromPath(string path) { - CommandInfo result = null; + CommandInfo? result = null; do // false loop { @@ -607,7 +611,7 @@ private CommandInfo GetInfoFromPath(string path) } // Now create the appropriate CommandInfo using the extension - string extension = null; + string? extension = null; try { @@ -681,9 +685,9 @@ private CommandInfo GetInfoFromPath(string path) /// /// A CommandInfo representing the next matching alias if found, otherwise null. /// - private CommandInfo GetNextAlias() + private CommandInfo? GetNextAlias() { - CommandInfo result = null; + CommandInfo? result = null; if ((_commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != 0) { @@ -709,7 +713,7 @@ private CommandInfo GetNextAlias() } // Process alias from modules - AliasInfo c = GetAliasFromModules(_commandName); + AliasInfo? c = GetAliasFromModules(_commandName); if (c != null) { matchingAliases.Add(c); @@ -762,15 +766,15 @@ private CommandInfo GetNextAlias() /// /// A CommandInfo representing the next matching function if found, otherwise null. /// - private CommandInfo GetNextFunction() + private CommandInfo? GetNextFunction() { - CommandInfo result = null; + CommandInfo? result = null; if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveFunctionPatterns)) { if (_matchingFunctionEnumerator == null) { - Collection matchingFunction = new Collection(); + Collection matchingFunction = new Collection(); // Generate the enumerator of matching function names WildcardPattern functionMatcher = @@ -778,25 +782,25 @@ private CommandInfo GetNextFunction() _commandName, WildcardOptions.IgnoreCase); - foreach (DictionaryEntry functionEntry in _context.EngineSessionState.GetFunctionTable()) + foreach ((string functionName, FunctionInfo functionInfo) in _context.EngineSessionState.GetFunctionTable()) { - if (functionMatcher.IsMatch((string)functionEntry.Key) || + if (functionMatcher.IsMatch(functionName) || (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(functionEntry.Key.ToString(), _commandName))) + FuzzyMatcher.IsFuzzyMatch(functionName, _commandName))) { - matchingFunction.Add((CommandInfo)functionEntry.Value); + matchingFunction.Add(functionInfo); } else if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion)) { - if (_commandName.Equals(ModuleUtils.AbbreviateName((string)functionEntry.Key), StringComparison.OrdinalIgnoreCase)) + if (_commandName.Equals(ModuleUtils.AbbreviateName(functionName), StringComparison.OrdinalIgnoreCase)) { - matchingFunction.Add((CommandInfo)functionEntry.Value); + matchingFunction.Add(functionInfo); } } } // Process functions from modules - CommandInfo cmdInfo = GetFunctionFromModules(_commandName); + CommandInfo? cmdInfo = GetFunctionFromModules(_commandName); if (cmdInfo != null) { matchingFunction.Add(cmdInfo); @@ -838,7 +842,7 @@ private CommandInfo GetNextFunction() // 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 bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo? result, ExecutionContext executionContext) { if (result == null) { @@ -870,60 +874,54 @@ private bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInfo resul return false; } - private AliasInfo GetAliasFromModules(string command) + private AliasInfo? GetAliasFromModules(string command) { - AliasInfo result = null; + AliasInfo? result = null; if (command.IndexOf('\\') > 0) { // See if it's a module qualified alias... - PSSnapinQualifiedName qualifiedName = PSSnapinQualifiedName.GetInstance(command); + PSSnapinQualifiedName? qualifiedName = PSSnapinQualifiedName.GetInstance(command); if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) { - PSModuleInfo module = GetImportedModuleByName(qualifiedName.PSSnapInName); + PSModuleInfo? module = GetImportedModuleByName(qualifiedName.PSSnapInName); - if (module != null) - { - module.ExportedAliases.TryGetValue(qualifiedName.ShortName, out result); - } + module?.ExportedAliases.TryGetValue(qualifiedName.ShortName, out result); } } return result; } - private CommandInfo GetFunctionFromModules(string command) + private CommandInfo? GetFunctionFromModules(string command) { - FunctionInfo result = null; + FunctionInfo? result = null; if (command.IndexOf('\\') > 0) { // See if it's a module qualified function call... - PSSnapinQualifiedName qualifiedName = PSSnapinQualifiedName.GetInstance(command); + PSSnapinQualifiedName? qualifiedName = PSSnapinQualifiedName.GetInstance(command); if (qualifiedName != null && !string.IsNullOrEmpty(qualifiedName.PSSnapInName)) { - PSModuleInfo module = GetImportedModuleByName(qualifiedName.PSSnapInName); + PSModuleInfo? module = GetImportedModuleByName(qualifiedName.PSSnapInName); - if (module != null) - { - module.ExportedFunctions.TryGetValue(qualifiedName.ShortName, out result); - } + module?.ExportedFunctions.TryGetValue(qualifiedName.ShortName, out result); } } return result; } - private PSModuleInfo GetImportedModuleByName(string moduleName) + private PSModuleInfo? GetImportedModuleByName(string moduleName) { - PSModuleInfo module = null; + PSModuleInfo? module = null; List modules = _context.Modules.GetModules(new string[] { moduleName }, false); if (modules != null && modules.Count > 0) { foreach (PSModuleInfo m in modules) { - if (_context.previousModuleImported.ContainsKey(m.Name) && ((string)_context.previousModuleImported[m.Name] == m.Path)) + if (_context.previousModuleImported.ContainsKey(m.Name) && ((string?)_context.previousModuleImported[m.Name] == m.Path)) { module = m; break; @@ -949,9 +947,9 @@ private PSModuleInfo GetImportedModuleByName(string moduleName) /// A FunctionInfo if the function name exists and is a function, a FilterInfo if /// the filter name exists and is a filter, or null otherwise. /// - private CommandInfo GetFunction(string function) + private CommandInfo? GetFunction(string function) { - CommandInfo result = _context.EngineSessionState.GetFunction(function); + CommandInfo? result = _context.EngineSessionState.GetFunction(function); if (result != null) { @@ -991,9 +989,9 @@ private CommandInfo GetFunction(string function) /// A CmdletInfo for the next matching Cmdlet or null if there are /// no more matches. /// - private CmdletInfo GetNextCmdlet() + private CmdletInfo? GetNextCmdlet() { - CmdletInfo result = null; + CmdletInfo? result = null; bool useAbbreviationExpansion = _commandResolutionOptions.HasFlag(SearchResolutionOptions.UseAbbreviationExpansion); if (_matchingCmdlet == null) @@ -1002,7 +1000,7 @@ private CmdletInfo GetNextCmdlet() { Collection matchingCmdletInfo = new Collection(); - PSSnapinQualifiedName PSSnapinQualifiedCommandName = + PSSnapinQualifiedName? PSSnapinQualifiedCommandName = PSSnapinQualifiedName.GetInstance(_commandName); if (!useAbbreviationExpansion && PSSnapinQualifiedCommandName == null) @@ -1010,10 +1008,12 @@ private CmdletInfo GetNextCmdlet() return null; } - WildcardPattern cmdletMatcher = - WildcardPattern.Get( - PSSnapinQualifiedCommandName.ShortName, - WildcardOptions.IgnoreCase); + string? moduleName = PSSnapinQualifiedCommandName?.PSSnapInName; + + var cmdletShortName = PSSnapinQualifiedCommandName?.ShortName; + WildcardPattern? cmdletMatcher = cmdletShortName != null + ? WildcardPattern.Get(cmdletShortName, WildcardOptions.IgnoreCase) + : null; SessionStateInternal ss = _context.EngineSessionState; @@ -1021,13 +1021,12 @@ private CmdletInfo GetNextCmdlet() { foreach (CmdletInfo cmdlet in cmdletList) { - if (cmdletMatcher.IsMatch(cmdlet.Name) || + if (cmdletMatcher != null && + cmdletMatcher.IsMatch(cmdlet.Name) || (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) + FuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) { - if (string.IsNullOrEmpty(PSSnapinQualifiedCommandName.PSSnapInName) || - (PSSnapinQualifiedCommandName.PSSnapInName.Equals( - cmdlet.ModuleName, StringComparison.OrdinalIgnoreCase))) + if (string.IsNullOrEmpty(moduleName) || moduleName.Equals(cmdlet.ModuleName, StringComparison.OrdinalIgnoreCase)) { // If PSSnapin is specified, make sure they match matchingCmdletInfo.Add(cmdlet); @@ -1067,9 +1066,10 @@ private CmdletInfo GetNextCmdlet() return traceResult(result); } - private IEnumerator _matchingCmdlet; + private IEnumerator? _matchingCmdlet; - private static CmdletInfo traceResult(CmdletInfo result) + [return: NotNullIfNotNull("result")] + private static CmdletInfo? traceResult(CmdletInfo? result) { if (result != null) { @@ -1082,9 +1082,9 @@ private static CmdletInfo traceResult(CmdletInfo result) return result; } - private string DoPowerShellRelativePathLookup() + private string? DoPowerShellRelativePathLookup() { - string result = null; + string? result = null; if (_context.EngineSessionState != null && _context.EngineSessionState.ProviderCount > 0) @@ -1124,14 +1124,14 @@ private string DoPowerShellRelativePathLookup() /// The path that was resolved. Null if the path couldn't be resolved or was /// not resolved by the FileSystemProvider. /// - private string ResolvePSPath(string path) + private string? ResolvePSPath(string? path) { - string result = null; + string? result = null; try { - ProviderInfo provider = null; - string resolvedPath = null; + ProviderInfo? provider = null; + string? resolvedPath = null; // Try literal path resolution if it is set to run first if (_commandResolutionOptions.HasFlag(SearchResolutionOptions.ResolveLiteralThenPathPatterns)) @@ -1234,7 +1234,7 @@ private string ResolvePSPath(string path) /// /// Full path to the command. /// - private string GetNextLiteralPathThatExistsAndHandleExceptions(string command, out ProviderInfo provider) + private string? GetNextLiteralPathThatExistsAndHandleExceptions(string command, out ProviderInfo? provider) { try { @@ -1296,7 +1296,7 @@ private string GetNextLiteralPathThatExistsAndHandleExceptions(string command, o /// /// Full path to the command. /// - private string GetNextLiteralPathThatExists(string command, out ProviderInfo provider) + private string? GetNextLiteralPathThatExists(string? command, out ProviderInfo? provider) { string resolvedPath = _context.LocationGlobber.GetProviderPath(command, out provider); @@ -1483,7 +1483,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) /// /// Determines which command types will be globbed. /// - private SearchResolutionOptions _commandResolutionOptions; + private readonly SearchResolutionOptions _commandResolutionOptions; /// /// Determines which types of commands to look for. @@ -1494,12 +1494,12 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) /// The enumerator that uses the Path to /// search for commands. /// - private CommandPathSearch _pathSearcher; + private CommandPathSearch? _pathSearcher; /// /// The execution context instance for the current engine... /// - private ExecutionContext _context; + private readonly ExecutionContext _context; /// /// A routine to initialize the path searcher... @@ -1555,7 +1555,7 @@ private void setupPathSearcher() { _canDoPathLookup = true; - string directory = Path.GetDirectoryName(_commandName); + string? directory = Path.GetDirectoryName(_commandName); var directoryCollection = new LookupPathCollection { directory }; CommandDiscovery.discoveryTracer.WriteLine( @@ -1587,7 +1587,7 @@ private void setupPathSearcher() // We must try to resolve the path as an PSPath or else we can't do // path lookup for relative paths. - string directory = Path.GetDirectoryName(_commandName); + string? directory = Path.GetDirectoryName(_commandName); directory = ResolvePSPath(directory); CommandDiscovery.discoveryTracer.WriteLine( @@ -1640,10 +1640,7 @@ public void Reset() _commandTypes &= ~CommandTypes.ExternalScript; } - if (_pathSearcher != null) - { - _pathSearcher.Reset(); - } + _pathSearcher?.Reset(); _currentMatch = null; _currentState = SearchState.SearchingAliases; @@ -1663,17 +1660,17 @@ internal CommandOrigin CommandOrigin /// /// An enumerator of the matching aliases. /// - private IEnumerator _matchingAlias; + private IEnumerator? _matchingAlias; /// /// An enumerator of the matching functions. /// - private IEnumerator _matchingFunctionEnumerator; + private IEnumerator? _matchingFunctionEnumerator; /// /// The CommandInfo that references the command that matches the pattern. /// - private CommandInfo _currentMatch; + private CommandInfo? _currentMatch; private bool _canDoPathLookup; private CanDoPathLookupResult _canDoPathLookupResult = CanDoPathLookupResult.Yes; diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 4ae05ac878b..9cc0b2ad899 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -28,7 +28,7 @@ internal CommonParameters(MshCommandRuntime commandRuntime) { if (commandRuntime == null) { - throw PSTraceSource.NewArgumentNullException("commandRuntime"); + throw PSTraceSource.NewArgumentNullException(nameof(commandRuntime)); } _commandRuntime = commandRuntime; diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index a507fef10eb..a9e85f43280 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -37,7 +37,7 @@ internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParamete { if (runtimeDefinedParameter == null) { - throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter"); + throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameter)); } this.Name = runtimeDefinedParameter.Name; @@ -123,7 +123,7 @@ internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParam { if (member == null) { - throw PSTraceSource.NewArgumentNullException("member"); + throw PSTraceSource.NewArgumentNullException(nameof(member)); } this.Name = member.Name; @@ -146,7 +146,7 @@ internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParam { ArgumentException e = PSTraceSource.NewArgumentException( - "member", + nameof(member), DiscoveryExceptions.CompiledCommandParameterMemberMustBeFieldOrProperty); throw e; diff --git a/src/System.Management.Automation/engine/ConfigurationInfo.cs b/src/System.Management.Automation/engine/ConfigurationInfo.cs index 4fb39fb145d..28b6dbbc52f 100644 --- a/src/System.Management.Automation/engine/ConfigurationInfo.cs +++ b/src/System.Management.Automation/engine/ConfigurationInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs index e2f94d077a6..382f6b7e46a 100644 --- a/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ContentCmdletProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -39,7 +39,7 @@ internal ContentCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } _cmdlet = cmdlet; @@ -59,7 +59,7 @@ internal ContentCmdletProviderIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 438af05dbac..2fd5e1868c5 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -1856,7 +1856,7 @@ internal static object MethodArgumentConvertTo(object valueToConvert, { if (resultType == null) { - throw PSTraceSource.NewArgumentNullException("resultType"); + throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } bool isArgumentByRef; @@ -1911,7 +1911,7 @@ internal static object PropertySetAndMethodArgumentConvertTo(object valueToConve { if (resultType == null) { - throw PSTraceSource.NewArgumentNullException("resultType"); + throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } PSObject mshObj = valueToConvert as PSObject; @@ -2080,6 +2080,7 @@ internal class MethodInformation { internal MethodBase method; private string _cachedMethodDefinition; + internal string methodDefinition { get @@ -2101,7 +2102,9 @@ internal string methodDefinition internal bool isGeneric; private bool _useReflection; + private delegate object MethodInvoker(object target, object[] arguments); + private MethodInvoker _methodInvoker; /// @@ -2555,8 +2558,10 @@ internal class DotNetAdapter : Adapter private const BindingFlags instanceBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance); + private const BindingFlags staticBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Static); + private bool _isStatic; internal DotNetAdapter() { } @@ -2626,6 +2631,7 @@ internal MethodInformation this[int i] } private bool? _isHidden; + internal override bool IsHidden { get @@ -2980,6 +2986,7 @@ internal SetterDelegate setterDelegate internal Type propertyType; private bool? _isHidden; + internal override bool IsHidden { get @@ -2994,6 +3001,7 @@ internal override bool IsHidden } private AttributeCollection _attributes; + internal AttributeCollection Attributes { get @@ -4749,6 +4757,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate internal class DotNetAdapterWithComTypeName : DotNetAdapter { private ComTypeInfo _comTypeInfo; + internal DotNetAdapterWithComTypeName(ComTypeInfo comTypeInfo) { _comTypeInfo = comTypeInfo; diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index f42b11b95ed..6b9c4be8d4d 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -219,7 +219,7 @@ public PSCredential(string userName, SecureString password) public PSCredential(PSObject pso) { if (pso == null) - throw PSTraceSource.NewArgumentNullException("pso"); + throw PSTraceSource.NewArgumentNullException(nameof(pso)); if (pso.Properties["UserName"] != null) { diff --git a/src/System.Management.Automation/engine/CultureVariable.cs b/src/System.Management.Automation/engine/CultureVariable.cs index d365278a6eb..2de72aa96c1 100644 --- a/src/System.Management.Automation/engine/CultureVariable.cs +++ b/src/System.Management.Automation/engine/CultureVariable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index ce6e1dfb5a0..c7db11bf081 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -127,7 +127,7 @@ internal void SetRoot(string path) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!DriveBeingCreated) @@ -271,7 +271,7 @@ protected PSDriveInfo(PSDriveInfo driveInfo) { if (driveInfo == null) { - throw PSTraceSource.NewArgumentNullException("driveInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(driveInfo)); } _name = driveInfo.Name; @@ -326,17 +326,17 @@ public PSDriveInfo( if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } if (root == null) { - throw PSTraceSource.NewArgumentNullException("root"); + throw PSTraceSource.NewArgumentNullException(nameof(root)); } // Copy the parameters to the local members @@ -508,7 +508,7 @@ internal void SetName(string newName) { if (string.IsNullOrEmpty(newName)) { - throw PSTraceSource.NewArgumentException("newName"); + throw PSTraceSource.NewArgumentException(nameof(newName)); } _name = newName; @@ -534,7 +534,7 @@ internal void SetProvider(ProviderInfo newProvider) { if (newProvider == null) { - throw PSTraceSource.NewArgumentNullException("newProvider"); + throw PSTraceSource.NewArgumentNullException(nameof(newProvider)); } _provider = newProvider; @@ -602,7 +602,7 @@ public int CompareTo(PSDriveInfo drive) if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } return string.Compare(Name, drive.Name, StringComparison.OrdinalIgnoreCase); @@ -631,7 +631,7 @@ public int CompareTo(object obj) { ArgumentException e = PSTraceSource.NewArgumentException( - "obj", + nameof(obj), SessionStateStrings.OnlyAbleToComparePSDriveInfo); throw e; } @@ -817,6 +817,7 @@ public override int GetHashCode() } private PSNoteProperty _noteProperty; + internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { if (_noteProperty == null) diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 453cba6a0e9..f1e798c0edf 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -37,6 +37,7 @@ public class ProviderInfo private SessionState _sessionState; private string _fullName; + private string _cachedModuleName; /// /// Gets the name of the provider. @@ -44,7 +45,7 @@ public class ProviderInfo public string Name { get; } /// - /// Gets the full name of the provider including the pssnapin name if available. + /// Gets the full name of the provider including the module name if available. /// internal string FullName { @@ -77,7 +78,13 @@ string GetFullName(string name, string psSnapInName, string moduleName) return result; } - return _fullName ?? (_fullName = GetFullName(Name, PSSnapInName, ModuleName)); + if (_fullName != null && ModuleName.Equals(_cachedModuleName, StringComparison.Ordinal)) + { + return _fullName; + } + + _cachedModuleName = ModuleName; + return _fullName = GetFullName(Name, PSSnapInName, ModuleName); } } @@ -290,7 +297,7 @@ protected ProviderInfo(ProviderInfo providerInfo) { if (providerInfo == null) { - throw PSTraceSource.NewArgumentNullException("providerInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInfo)); } Name = providerInfo.Name; @@ -387,17 +394,17 @@ internal ProviderInfo( // Verify parameters if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } if (implementingType == null) { - throw PSTraceSource.NewArgumentNullException("implementingType"); + throw PSTraceSource.NewArgumentNullException(nameof(implementingType)); } if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } _sessionState = sessionState; @@ -666,6 +673,7 @@ internal void GetOutputTypes(string cmdletname, List listToAppend) private Dictionary> _providerOutputType; private PSNoteProperty _noteProperty; + internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { if (_noteProperty == null) diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index ff398c9bdbb..95e7572810f 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -21,7 +21,7 @@ internal class DefaultCommandRuntime : ICommandRuntime2 public DefaultCommandRuntime(List outputList) { if (outputList == null) - throw new System.ArgumentNullException("outputList"); + throw new System.ArgumentNullException(nameof(outputList)); _output = outputList; } @@ -36,7 +36,7 @@ public DefaultCommandRuntime(List outputList) /// Implementation of WriteDebug - just discards the input. /// /// Text to write. - public void WriteDebug(string text) {; } + public void WriteDebug(string text) { } /// /// Default implementation of WriteError - if the error record contains @@ -97,38 +97,38 @@ public void WriteObject(object sendToPipeline, bool enumerateCollection) /// Default implementation - just discards it's arguments. /// /// Progress record to write. - public void WriteProgress(ProgressRecord progressRecord) {; } + public void WriteProgress(ProgressRecord progressRecord) { } /// /// Default implementation - just discards it's arguments. /// /// Source ID to write for. /// Record to write. - public void WriteProgress(Int64 sourceId, ProgressRecord progressRecord) {; } + public void WriteProgress(Int64 sourceId, ProgressRecord progressRecord) { } /// /// Default implementation - just discards it's arguments. /// /// Text to write. - public void WriteVerbose(string text) {; } + public void WriteVerbose(string text) { } /// /// Default implementation - just discards it's arguments. /// /// Text to write. - public void WriteWarning(string text) {; } + public void WriteWarning(string text) { } /// /// Default implementation - just discards it's arguments. /// /// Text to write. - public void WriteCommandDetail(string text) {; } + public void WriteCommandDetail(string text) { } /// /// Default implementation - just discards it's arguments. /// /// Record to write. - public void WriteInformation(InformationRecord informationRecord) {; } + public void WriteInformation(InformationRecord informationRecord) { } #endregion Write diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index 9d86fda58a2..36bfc73c573 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -38,7 +38,7 @@ internal DriveManagementIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/DriveNames.cs b/src/System.Management.Automation/engine/DriveNames.cs index bc5a89a01da..2f737bbc53d 100644 --- a/src/System.Management.Automation/engine/DriveNames.cs +++ b/src/System.Management.Automation/engine/DriveNames.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/DscResourceInfo.cs b/src/System.Management.Automation/engine/DscResourceInfo.cs index a94cef1eb1b..93f7be37323 100644 --- a/src/System.Management.Automation/engine/DscResourceInfo.cs +++ b/src/System.Management.Automation/engine/DscResourceInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/DscResourceSearcher.cs b/src/System.Management.Automation/engine/DscResourceSearcher.cs index bf1bfe4be52..8bb4f5bd267 100644 --- a/src/System.Management.Automation/engine/DscResourceSearcher.cs +++ b/src/System.Management.Automation/engine/DscResourceSearcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index a2405ab08d2..d0bc7a2f100 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; @@ -37,7 +37,7 @@ internal EngineIntrinsics(ExecutionContext context) { if (context == null) { - throw new ArgumentNullException("context"); + throw new ArgumentNullException(nameof(context)); } _context = context; diff --git a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs index 978eda0cef9..092500c0af7 100644 --- a/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs +++ b/src/System.Management.Automation/engine/EnumExpressionEvaluator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs index 710261bd29f..543d920418f 100644 --- a/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs +++ b/src/System.Management.Automation/engine/EnumMinimumDisambiguation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index ff1df35ad0b..fc346e2ee96 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -420,7 +420,7 @@ public string GetMessage(CultureInfo uiCultureInfo) if (string.IsNullOrEmpty(errorCategoryString)) { // this probably indicates an invalid ErrorCategory value - errorCategoryString = ErrorCategory.NotSpecified.ToString(); + errorCategoryString = nameof(ErrorCategory.NotSpecified); } string templateText = ErrorCategoryStrings.ResourceManager.GetString(errorCategoryString, uiCultureInfo); @@ -1470,6 +1470,7 @@ public Exception Exception public object TargetObject { get => _target; } private object _target /* = null */; + internal void SetTargetObject(object target) { _target = target; diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index 2071ee444db..a962f745eac 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -641,6 +641,7 @@ private void EnableTimer() #endregion OnIdleProcessing private static Dictionary s_generatedEventHandlers = new Dictionary(); + private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, string eventName, string sourceIdentifier, PSObject data, bool supportEvent, bool forwardEvent) { Delegate handlerDelegate = null; @@ -666,7 +667,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s { string errorMessage = StringUtil.Format(EventingResources.ReservedIdentifier, sourceIdentifier); - throw new ArgumentException(errorMessage, "sourceIdentifier"); + throw new ArgumentException(errorMessage, nameof(sourceIdentifier)); } EventInfo eventInfo = null; @@ -686,7 +687,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s if (eventInfo == null) { string errorMessage = StringUtil.Format(EventingResources.CouldNotFindEvent, eventName); - throw new ArgumentException(errorMessage, "eventName"); + throw new ArgumentException(errorMessage, nameof(eventName)); } // Try to set the EnableRaisingEvents property if it defines one @@ -722,7 +723,7 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s if (invokeMethod.ReturnType != typeof(void)) { string errorMessage = EventingResources.NonVoidDelegateNotSupported; - throw new ArgumentException(errorMessage, "eventName"); + throw new ArgumentException(errorMessage, nameof(eventName)); } // Cache generated event handlers (by type and event name) so that they don't bloat our @@ -818,7 +819,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) { if (subscriber == null) { - throw new ArgumentNullException("subscriber"); + throw new ArgumentNullException(nameof(subscriber)); } Delegate existingSubscriber = null; @@ -2349,6 +2350,7 @@ public class PSEventArgsCollection : IEnumerable /// The event generated when a new event is received. /// public event PSEventReceivedEventHandler PSEventReceived; + private List _eventCollection = new List(); /// @@ -2362,7 +2364,7 @@ internal void Add(PSEventArgs eventToAdd) { if (eventToAdd == null) { - throw new ArgumentNullException("eventToAdd"); + throw new ArgumentNullException(nameof(eventToAdd)); } _eventCollection.Add(eventToAdd); @@ -2479,9 +2481,9 @@ public PSEventJob(PSEventManager eventManager, PSEventSubscriber subscriber, Scr base(action == null ? null : action.ToString(), name) { if (eventManager == null) - throw new ArgumentNullException("eventManager"); + throw new ArgumentNullException(nameof(eventManager)); if (subscriber == null) - throw new ArgumentNullException("subscriber"); + throw new ArgumentNullException(nameof(subscriber)); UsesResultsCollection = true; ScriptBlock = action; diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 118ff82a899..98f0b3deb5a 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -492,7 +492,7 @@ internal bool UseFullLanguageModeInDebugger } } - internal static List ModulesWithJobSourceAdapters = new List + internal static readonly List ModulesWithJobSourceAdapters = new List { Utils.ScheduledJobModuleName, }; diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs index 35a404b675e..c15d8628cb9 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index dad066f2bf1..f6993a03a0a 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -120,6 +120,9 @@ static ExperimentalFeature() new ExperimentalFeature( name: "PSCultureInvariantReplaceOperator", description: "Use culture invariant to-string convertor for lval in replace operator"), + new ExperimentalFeature( + name: "PSNativePSPathResolution", + description: "Convert PSPath to filesystem path, if possible, for native commands"), }; EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); @@ -208,7 +211,7 @@ private static void LogError(PSEventId eventId, params object[] args) /// internal static bool IsEngineFeatureName(string featureName) { - return featureName.Length > 2 && featureName.IndexOf('.') == -1 && featureName.StartsWith("PS", StringComparison.Ordinal); + return featureName.Length > 2 && !featureName.Contains('.') && featureName.StartsWith("PS", StringComparison.Ordinal); } /// @@ -346,7 +349,7 @@ internal static void ValidateArguments(string experimentName, ExperimentAction e if (experimentAction == ExperimentAction.None) { string paramName = nameof(experimentAction); - string invalidMember = ExperimentAction.None.ToString(); + 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/ExperimentalFeature/GetExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs index 96681e6e6b9..ff1c964fc4c 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index 1a9e02872d8..542ad8bbf7e 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -532,7 +532,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index 18db1edd721..d87e3027f2e 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -44,7 +44,7 @@ internal ExternalScriptInfo(string name, string path, ExecutionContext context) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved."); @@ -71,7 +71,7 @@ internal ExternalScriptInfo(string name, string path) : base(name, CommandTypes. { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved."); diff --git a/src/System.Management.Automation/engine/ExtraAdapter.cs b/src/System.Management.Automation/engine/ExtraAdapter.cs index e44df98a8f2..dd6ba0c0784 100644 --- a/src/System.Management.Automation/engine/ExtraAdapter.cs +++ b/src/System.Management.Automation/engine/ExtraAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/FilterInfo.cs b/src/System.Management.Automation/engine/FilterInfo.cs index 70ad62b4a5a..247aa0d5f6b 100644 --- a/src/System.Management.Automation/engine/FilterInfo.cs +++ b/src/System.Management.Automation/engine/FilterInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/FunctionInfo.cs b/src/System.Management.Automation/engine/FunctionInfo.cs index 0c11badf613..8afe41ece15 100644 --- a/src/System.Management.Automation/engine/FunctionInfo.cs +++ b/src/System.Management.Automation/engine/FunctionInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -55,7 +55,7 @@ internal FunctionInfo(string name, ScriptBlock function, ExecutionContext contex { if (function == null) { - throw PSTraceSource.NewArgumentNullException("function"); + throw PSTraceSource.NewArgumentNullException(nameof(function)); } _scriptBlock = function; diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 06bdf643a5b..eef50f29a24 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -531,9 +531,7 @@ private void OutputResultsHelper(IEnumerable results) { if (!string.IsNullOrEmpty(result.Syntax)) { - PSObject syntax = PSObject.AsPSObject(result.Syntax); - - syntax.IsHelpObject = true; + PSObject syntax = GetSyntaxObject(result); WriteObject(syntax); } @@ -571,6 +569,81 @@ private void OutputResultsHelper(IEnumerable results) #endif } + /// + /// Creates the syntax output based on if the command is an alias, script, application or command. + /// + /// + /// CommandInfo object containing the syntax to be output. + /// + /// + /// Syntax string cast as a PSObject for outputting. + /// + private PSObject GetSyntaxObject(CommandInfo command) + { + PSObject syntax = PSObject.AsPSObject(command.Syntax); + + // This is checking if the command name that's been passed in is one that was specified by a user, + // if not then we have to assume they specified an alias or a wildcard and do some extra formatting for those, + // if it is then just go with the default formatting. + // So if a user runs Get-Command -Name del -Syntax the code will find del and the command it resolves to as Remove-Item + // and attempt to return that, but as the user specified del we want to fiddle with the output a bit to make it clear + // that's an alias but still give the Remove-Item syntax. + if (this.Name != null && !Array.Exists(this.Name, name => name.Equals(command.Name, StringComparison.InvariantCultureIgnoreCase))) + { + string aliasName = _nameContainsWildcard ? command.Name : this.Name[0]; + + IDictionary aliasTable = SessionState.Internal.GetAliasTable(); + foreach (KeyValuePair tableEntry in aliasTable) + { + if ((Array.Exists(this.Name, name => name.Equals(tableEntry.Key, StringComparison.InvariantCultureIgnoreCase)) && + tableEntry.Value.Definition == command.Name) || + (_nameContainsWildcard && tableEntry.Value.Definition == command.Name)) + { + aliasName = tableEntry.Key; + break; + } + } + + string replacedSyntax = string.Empty; + switch (command) + { + case ExternalScriptInfo externalScript: + replacedSyntax = string.Format( + "{0} (alias) -> {1}{2}{3}", + aliasName, + string.Format("{0}{1}", externalScript.Path, Environment.NewLine), + Environment.NewLine, + command.Syntax.Replace(command.Name, aliasName)); + break; + case ApplicationInfo app: + replacedSyntax = app.Path; + break; + default: + if (aliasName.Equals(command.Name)) + { + replacedSyntax = command.Syntax; + } + else + { + replacedSyntax = string.Format( + "{0} (alias) -> {1}{2}{3}", + aliasName, + command.Name, + Environment.NewLine, + command.Syntax.Replace(command.Name, aliasName)); + } + + break; + } + + syntax = PSObject.AsPSObject(replacedSyntax); + } + + syntax.IsHelpObject = true; + + return syntax; + } + /// /// The comparer to sort CommandInfo objects in the result list. /// @@ -1229,33 +1302,37 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) if (isCommandMatch) { - if (ArgumentList != null) + if (Syntax.IsPresent && current is AliasInfo ai) { - AliasInfo ai = current as AliasInfo; - if (ai != null) - { - // If the matching command was an alias, then use the resolved command - // instead of the alias... - current = ai.ResolvedCommand; - if (current == null) - { - return false; - } - } - else if (!(current is CmdletInfo || current is IScriptCommandInfo)) + // If the matching command was an alias, then use the resolved command + // instead of the alias... + current = ai.ResolvedCommand ?? CommandDiscovery.LookupCommandInfo( + ai.UnresolvedCommandName, + this.MyInvocation.CommandOrigin, + this.Context); + + // there are situations where both ResolvedCommand and UnresolvedCommandName + // are both null (often due to multiple versions of modules with aliases) + // therefore we need to exit early. + if (current == null) { - // If current is not a cmdlet or script, we need to throw a terminating error. - ThrowTerminatingError( - new ErrorRecord( - PSTraceSource.NewArgumentException( - "ArgumentList", - DiscoveryExceptions.CommandArgsOnlyForSingleCmdlet), - "CommandArgsOnlyForSingleCmdlet", - ErrorCategory.InvalidArgument, - current)); + return false; } } + if (ArgumentList != null && !(current is CmdletInfo || current is IScriptCommandInfo)) + { + // If current is not a cmdlet or script, we need to throw a terminating error. + ThrowTerminatingError( + new ErrorRecord( + PSTraceSource.NewArgumentException( + "ArgumentList", + DiscoveryExceptions.CommandArgsOnlyForSingleCmdlet), + "CommandArgsOnlyForSingleCmdlet", + ErrorCategory.InvalidArgument, + current)); + } + // If the command implements dynamic parameters // then we must make a copy of the CommandInfo which merges the // dynamic parameter metadata with the statically defined parameter @@ -1367,15 +1444,13 @@ private IEnumerable GetMatchingCommandsFromModules(string commandNa // Look in function table if ((this.CommandType & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0) { - foreach (DictionaryEntry function in module.SessionState.Internal.GetFunctionTable()) + foreach ((string functionName, FunctionInfo functionInfo) in module.SessionState.Internal.GetFunctionTable()) { - FunctionInfo func = (FunctionInfo)function.Value; - - if (matcher.IsMatch((string)function.Key) && func.IsImported) + if (matcher.IsMatch(functionName) && functionInfo.IsImported) { // make sure function doesn't come from the current module's nested module - if (func.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) - yield return (CommandInfo)function.Value; + if (functionInfo.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) + yield return functionInfo; } } } @@ -1583,7 +1658,7 @@ public IEnumerable CompleteArgument(string commandName, string { if (fakeBoundParameters == null) { - throw PSTraceSource.NewArgumentNullException("fakeBoundParameters"); + throw PSTraceSource.NewArgumentNullException(nameof(fakeBoundParameters)); } var commandInfo = new CmdletInfo("Get-Command", typeof(GetCommandCommand)); diff --git a/src/System.Management.Automation/engine/ICommandRuntime.cs b/src/System.Management.Automation/engine/ICommandRuntime.cs index da77f9cdb45..cf5de2b20ab 100644 --- a/src/System.Management.Automation/engine/ICommandRuntime.cs +++ b/src/System.Management.Automation/engine/ICommandRuntime.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index c65123fcf95..81a9789bb81 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index f1994d5a797..0d2e1274aa6 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -1517,9 +1517,9 @@ public static InitialSessionState CreateDefault() { ss.ImportPSSnapIn(si, out warning); } - catch (PSSnapInException pse) + catch (PSSnapInException) { - throw pse; + throw; } #if DEBUG // NOTE: @@ -3826,9 +3826,9 @@ internal PSSnapInInfo ImportCorePSSnapIn() PSSnapInException warning; this.ImportPSSnapIn(coreSnapin, out warning); } - catch (PSSnapInException pse) + catch (PSSnapInException) { - throw pse; + throw; } return coreSnapin; @@ -4435,7 +4435,7 @@ .ForwardHelpCategory Cmdlet internal const bool DefaultWhatIfPreference = false; internal const ConfirmImpact DefaultConfirmPreference = ConfirmImpact.High; - internal static SessionStateVariableEntry[] BuiltInVariables = new SessionStateVariableEntry[] + internal static readonly SessionStateVariableEntry[] BuiltInVariables = new SessionStateVariableEntry[] { // Engine variables that should be precreated before running profile // Bug fix for Win7:2202228 Engine halts if initial command fulls up variable table @@ -4771,10 +4771,12 @@ internal static SessionStateAliasEntry[] BuiltInAliases "; internal const string DefaultSetDriveFunctionText = "Set-Location $MyInvocation.MyCommand.Name"; - internal static ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText, isProductCode: true); + + internal static readonly ScriptBlock SetDriveScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(DefaultSetDriveFunctionText, isProductCode: true); private static PSLanguageMode systemLanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; - internal static SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] + + internal static readonly SessionStateFunctionEntry[] BuiltInFunctions = new SessionStateFunctionEntry[] { // Functions that don't require full language mode SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true, languageMode: systemLanguageMode), @@ -4841,12 +4843,12 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt private static PSTraceSource s_PSSnapInTracer = PSTraceSource.GetTracer("PSSnapInLoadUnload", "Loading and unloading mshsnapins", false); - internal static string CoreSnapin = "Microsoft.PowerShell.Core"; - internal static string CoreModule = "Microsoft.PowerShell.Core"; + internal static readonly string CoreSnapin = "Microsoft.PowerShell.Core"; + internal static readonly string CoreModule = "Microsoft.PowerShell.Core"; internal Collection defaultSnapins = new Collection(); // The list of engine modules to create warnings when you try to remove them - internal static HashSet EngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet EngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) { "Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Management", @@ -4856,7 +4858,7 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt "Microsoft.WSMan.Management" }; - internal static HashSet NestedEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet NestedEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) { "Microsoft.PowerShell.Commands.Utility", "Microsoft.PowerShell.Commands.Management", @@ -4864,14 +4866,15 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt "Microsoft.PowerShell.ConsoleHost" }; - internal static Dictionary EngineModuleNestedModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary EngineModuleNestedModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility"}, { "Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management"}, { "Microsoft.PowerShell.Diagnostics", "Microsoft.PowerShell.Commands.Diagnostics"}, { "Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost"}, }; - internal static Dictionary NestedModuleEngineModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) + + internal static readonly Dictionary NestedModuleEngineModuleMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "Microsoft.PowerShell.Commands.Utility", "Microsoft.PowerShell.Utility"}, { "Microsoft.PowerShell.Commands.Management", "Microsoft.PowerShell.Management"}, @@ -4882,13 +4885,13 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt }; // The list of engine modules that we will not allow users to remove - internal static HashSet ConstantEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet ConstantEngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) { CoreModule, }; // The list of nested engine modules that we will not allow users to remove - internal static HashSet ConstantEngineNestedModules = new HashSet(StringComparer.OrdinalIgnoreCase) + internal static readonly HashSet ConstantEngineNestedModules = new HashSet(StringComparer.OrdinalIgnoreCase) { "System.Management.Automation", }; @@ -5490,7 +5493,7 @@ private static string GetHelpFile(string assemblyPath) [EventSource(Name = "Microsoft-PowerShell-Runspaces")] internal class RunspaceEventSource : EventSource { - internal static RunspaceEventSource Log = new RunspaceEventSource(); + internal static readonly RunspaceEventSource Log = new RunspaceEventSource(); public void OpenRunspaceStart() { WriteEvent(1); } diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 406a9b61768..7c37cc4f0eb 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -260,6 +260,14 @@ public object[] ArgumentList [Parameter(ParameterSetName = ForEachObjectCommand.ParallelParameterSet)] public SwitchParameter AsJob { get; set; } + /// + /// Gets or sets a flag so that a new runspace object is created for each loop iteration, instead of reusing objects + /// from the runspace pool. + /// By default, runspaces are reused from a runspace pool. + /// + [Parameter(ParameterSetName = ForEachObjectCommand.ParallelParameterSet)] + public SwitchParameter UseNewRunspace { get; set; } + #endregion #region Overrides @@ -437,7 +445,8 @@ private void InitParallelParameterSet() _taskJob = new PSTaskJob( Parallel.ToString(), - ThrottleLimit); + ThrottleLimit, + UseNewRunspace); return; } @@ -445,7 +454,7 @@ private void InitParallelParameterSet() // Set up for synchronous processing and data streaming. _taskCollection = new PSDataCollection(); _taskDataStreamWriter = new PSTaskDataStreamWriter(this); - _taskPool = new PSTaskPool(ThrottleLimit); + _taskPool = new PSTaskPool(ThrottleLimit, UseNewRunspace); _taskPool.PoolComplete += (sender, args) => { _taskDataStreamWriter.Close(); @@ -1954,6 +1963,7 @@ public SwitchParameter Not private readonly CallSite> _toBoolSite = CallSite>.Create(PSConvertBinder.Get(typeof(bool))); + private Func _operationDelegate; private static Func GetCallSiteDelegate(ExpressionType expressionType, bool ignoreCase) diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index e636f472086..1871ae3c9cd 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs index b0f83d39214..699d60dafa0 100644 --- a/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ItemCmdletProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -38,7 +38,7 @@ internal ItemCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } _cmdlet = cmdlet; @@ -58,7 +58,7 @@ internal ItemCmdletProviderIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index aa2240bc454..d1ebac8c2ce 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -14,6 +14,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; @@ -412,6 +413,7 @@ private static IEnumerable GetEnumerableFromIEnumerableT(object obj) } private delegate IEnumerable GetEnumerableDelegate(object obj); + private static Dictionary s_getEnumerableCache = new Dictionary(32); private static GetEnumerableDelegate GetOrCalculateEnumerable(Type type) @@ -638,7 +640,7 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP var culture = formatProvider as CultureInfo; if (culture == null) { - throw PSTraceSource.NewArgumentException("formatProvider"); + throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } first = PSObject.Base(first); @@ -786,7 +788,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP var culture = formatProvider as CultureInfo; if (culture == null) { - throw PSTraceSource.NewArgumentException("formatProvider"); + throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } first = PSObject.Base(first); @@ -813,7 +815,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP } catch (PSInvalidCastException e) { - throw PSTraceSource.NewArgumentException("second", ExtendedTypeSystem.ComparisonFailure, + throw PSTraceSource.NewArgumentException(nameof(second), ExtendedTypeSystem.ComparisonFailure, first.ToString(), second.ToString(), e.Message); } } @@ -838,7 +840,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP } catch (PSInvalidCastException e) { - throw PSTraceSource.NewArgumentException("second", ExtendedTypeSystem.ComparisonFailure, + throw PSTraceSource.NewArgumentException(nameof(second), ExtendedTypeSystem.ComparisonFailure, first.ToString(), second.ToString(), e.Message); } @@ -854,7 +856,7 @@ public static int Compare(object first, object second, bool ignoreCase, IFormatP // At this point, we know that they aren't equal but we have no way of // knowing which should compare greater than the other so we throw an exception. - throw PSTraceSource.NewArgumentException("first", ExtendedTypeSystem.NotIcomparable, first.ToString()); + throw PSTraceSource.NewArgumentException(nameof(first), ExtendedTypeSystem.NotIcomparable, first.ToString()); } /// @@ -906,7 +908,7 @@ public static bool TryCompare(object first, object second, bool ignoreCase, IFor if (!(formatProvider is CultureInfo culture)) { - throw PSTraceSource.NewArgumentException("formatProvider"); + throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } first = PSObject.Base(first); @@ -1110,7 +1112,7 @@ internal static int TypeTableIndex(Type type) /// an exception when converted to decimal. /// The order of lines and columns cannot be changed since NumericCompare depends on it. /// - internal static Type[][] LargestTypeTable = new Type[][] + internal static readonly Type[][] LargestTypeTable = new Type[][] { // System.Int16 System.Int32 System.Int64 System.UInt16 System.UInt32 System.UInt64 System.SByte System.Byte System.Single System.Double System.Decimal /* System.Int16 */new Type[] { typeof(System.Int16), typeof(System.Int32), typeof(System.Int64), typeof(System.Int32), typeof(System.Int64), typeof(System.Double), typeof(System.Int16), typeof(System.Int16), typeof(System.Single), typeof(System.Double), typeof(System.Decimal) }, @@ -1421,8 +1423,8 @@ internal static void DoConversionsForSetInGenericDictionary(IDictionary dictiona #region type converter - internal static PSTraceSource typeConversion = PSTraceSource.GetTracer("TypeConversion", "Traces the type conversion algorithm", false); - internal static ConversionData NoConversion = new ConversionData(ConvertNoConversion, ConversionRank.None); + internal static readonly PSTraceSource typeConversion = PSTraceSource.GetTracer("TypeConversion", "Traces the type conversion algorithm", false); + internal static readonly ConversionData NoConversion = new ConversionData(ConvertNoConversion, ConversionRank.None); private static TypeConverter GetIntegerSystemConverter(Type type) { @@ -1921,6 +1923,7 @@ internal EnumHashEntry(string[] names, Array values, UInt64 allValues, bool hasN // This static is thread safe based on the lock in GetEnumHashEntry // It can be shared by Runspaces in different MiniShells private static readonly Dictionary s_enumTable = new Dictionary(); + private const int maxEnumTableSize = 100; private static EnumHashEntry GetEnumHashEntry(Type enumType) @@ -3307,6 +3310,11 @@ private static string ConvertNumericToString(object valueToConvert, return sgl.ToString(SinglePrecision, numberFormat); } + if (valueToConvert is BigInteger b) + { + return b.ToString(numberFormat); + } + return (string)Convert.ChangeType(valueToConvert, resultType, CultureInfo.InvariantCulture.NumberFormat); } catch (Exception e) @@ -3650,6 +3658,7 @@ private class PSMethodToDelegateConverter private readonly int _matchIndex; // Size of the cache. It's rare to have more than 10 overloads for a method. private const int CacheSize = 10; + private static readonly PSMethodToDelegateConverter[] s_converterCache = new PSMethodToDelegateConverter[CacheSize]; private PSMethodToDelegateConverter(int matchIndex) @@ -4380,7 +4389,8 @@ internal static ConversionRank GetConversionRank(Type fromType, Type toType) typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(sbyte), typeof(byte), - typeof(Single), typeof(double), typeof(decimal) + typeof(Single), typeof(double), typeof(decimal), + typeof(BigInteger) }; private static Type[] s_integerTypes = new Type[] { @@ -4693,7 +4703,7 @@ private static string GetAvailableProperties(PSObject pso) } availableProperties.Append("[" + p.Name + " <" + p.TypeNameOfValue + ">]"); - if (first == true) + if (first) { first = false; } @@ -4781,7 +4791,7 @@ internal static object ConvertTo(object valueToConvert, { if (resultType == null) { - throw PSTraceSource.NewArgumentNullException("resultType"); + throw PSTraceSource.NewArgumentNullException(nameof(resultType)); } bool debase; @@ -5051,7 +5061,7 @@ private static IConversionData FigureLanguageConversion(Type fromType, Type toTy private struct SignatureComparator { - enum TypeMatchingContext + private enum TypeMatchingContext { ReturnType, ParameterType, @@ -5240,7 +5250,7 @@ private static PSConverter FigureParseConversion(Type fromType, Type toT internal static Tuple, ConversionRank> FigureIEnumerableConstructorConversion(Type fromType, Type toType) { // Win8: 653180. If toType is an Abstract type then we cannot construct it anyway. So, bailing out fast. - if (toType.IsAbstract == true) + if (toType.IsAbstract) { return null; } @@ -5725,6 +5735,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) } internal class Null { }; + private static IConversionData FigureConversionFromNull(Type toType) { IConversionData data = GetConversionData(typeof(Null), toType); diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index 44788eb1d4c..522a69f11ed 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index a1d5530b658..9efd502badb 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -81,7 +81,7 @@ internal Collection AddMetadataForBinder( { if (parameterMetadata == null) { - throw PSTraceSource.NewArgumentNullException("parameterMetadata"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } Collection result = @@ -443,7 +443,7 @@ internal MergedCompiledCommandParameter GetMatchingParameter( { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } Collection matchingParameters = diff --git a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs index 705319bf327..a85b462abb9 100644 --- a/src/System.Management.Automation/engine/MinishellParameterBinderController.cs +++ b/src/System.Management.Automation/engine/MinishellParameterBinderController.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 0179b45e237..dd188b3ff99 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -35,7 +35,7 @@ internal class AnalysisCache private static ConcurrentDictionary s_modulesBeingAnalyzed = new ConcurrentDictionary( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase); - internal static char[] InvalidCommandNameCharacters = new[] + internal static readonly char[] InvalidCommandNameCharacters = new[] { '#', ',', '(', ')', '{', '}', '[', ']', '&', '/', '\\', '$', '^', ';', ':', '"', '\'', '<', '>', '|', '?', '@', '`', '*', '%', '+', '=', '~' @@ -738,7 +738,7 @@ private static void Write(string val, byte[] bytes, FileStream stream) private void Serialize(string filename) { AnalysisCacheData fromOtherProcess = null; - Diagnostics.Assert(_saveCacheToDisk != false, "Serialize should never be called without going through QueueSerialization which has a check"); + Diagnostics.Assert(_saveCacheToDisk, "Serialize should never be called without going through QueueSerialization which has a check"); try { diff --git a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs index e937f2c12be..7dc91d76776 100644 --- a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 2104142987a..bfecce83e4e 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -440,7 +440,7 @@ private void AssertNameDoesNotResolveToAPath(string[] names, string stringFormat { foreach (var n in names) { - if (n.IndexOf(StringLiterals.DefaultPathSeparator) != -1 || n.IndexOf(StringLiterals.AlternatePathSeparator) != -1) + if (n.Contains(StringLiterals.DefaultPathSeparator) || n.Contains(StringLiterals.AlternatePathSeparator)) { string errorMessage = StringUtil.Format(stringFormat, n); var argumentException = new ArgumentException(errorMessage); diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 745c69bbf64..f6641930bf7 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -591,6 +591,27 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A } } + private PSModuleInfo ImportModule_LocallyViaName_WithTelemetry(ImportModuleOptions importModuleOptions, string name) + { + PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, name); + if (foundModule != null) + { + SetModuleBaseForEngineModules(foundModule.Name, this.Context); + + // report loading of the module in telemetry + // avoid double reporting for WinCompat modules that go through CommandDiscovery\AutoloadSpecifiedModule + if (!foundModule.IsWindowsPowerShellCompatModule) + { + ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, foundModule.Name); +#if LEGACYTELEMETRY + TelemetryAPI.ReportModuleLoad(foundModule); +#endif + } + } + + return foundModule; + } + private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, string name) { try @@ -820,6 +841,24 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul return null; } + private PSModuleInfo ImportModule_LocallyViaFQName(ImportModuleOptions importModuleOptions, ModuleSpecification modulespec) + { + RequiredVersion = modulespec.RequiredVersion; + MinimumVersion = modulespec.Version; + MaximumVersion = modulespec.MaximumVersion; + BaseGuid = modulespec.Guid; + + PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, modulespec.Name); + + if (foundModule != null) + { + ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, foundModule.Name); + SetModuleBaseForEngineModules(foundModule.Name, this.Context); + } + + return foundModule; + } + #endregion Local import #region Remote import @@ -1024,7 +1063,10 @@ private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule { powerShell.AddCommand("Export-PSSession"); powerShell.AddParameter("OutputModule", wildcardEscapedPath); - powerShell.AddParameter("AllowClobber", true); + if (!importModuleOptions.NoClobberExportPSSession) + { + powerShell.AddParameter("AllowClobber", true); + } powerShell.AddParameter("Module", remoteModuleName); // remoteModulePath is currently unsupported by Get-Command and implicit remoting powerShell.AddParameter("Force", true); powerShell.AddParameter("FormatTypeName", "*"); @@ -1667,6 +1709,7 @@ private PSModuleInfo ImportModule_RemotelyViaCimModuleData( #region Cancellation support private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); + private CancellationToken CancellationToken { get @@ -1751,10 +1794,10 @@ protected override void BeginProcessing() /// c:\temp\mdir\mdir # resolve by using extensions. mdir is a directory, mdir.xxx is a file. /// c:\temp\mdir # load default module if mdir is directory /// module # $PSScriptRoot/module/module.psd1 (ps1,psm1,dll) - /// module/foobar.psm1 # $PSScriptRoot/module/module.psm1 - /// module/foobar # $PSScriptRoot/module/foobar.XXX if foobar is not a directory... - /// module/foobar # $PSScriptRoot/module/foobar is a directory and $PSScriptRoot/module/foobar/foobar.XXX exists - /// module/foobar/foobar.XXX + /// module/examplemodule.psm1 # $PSScriptRoot/module/module.psm1 + /// module/examplemodule # $PSScriptRoot/module/examplemodule.XXX if examplemodule is not a directory... + /// module/examplemodule # $PSScriptRoot/module/examplemodule is a directory and $PSScriptRoot/module/examplemodule/examplemodule.XXX exists + /// module/examplemodule/examplemodule.XXX /// protected override void ProcessRecord() { @@ -1816,21 +1859,7 @@ protected override void ProcessRecord() { foreach (string name in Name) { - PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, name); - if (foundModule != null) - { - SetModuleBaseForEngineModules(foundModule.Name, this.Context); - - // report loading of the module in telemetry - // avoid double reporting for WinCompat modules that go through CommandDiscovery\AutoloadSpecifiedModule - if (!foundModule.IsWindowsPowerShellCompatModule) - { - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, foundModule.Name); -#if LEGACYTELEMETRY - TelemetryAPI.ReportModuleLoad(foundModule); -#endif - } - } + ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, name); } } else if (this.ParameterSetName.Equals(ParameterSet_ViaPsrpSession, StringComparison.OrdinalIgnoreCase)) @@ -1845,17 +1874,7 @@ protected override void ProcessRecord() { foreach (var modulespec in FullyQualifiedName) { - RequiredVersion = modulespec.RequiredVersion; - MinimumVersion = modulespec.Version; - MaximumVersion = modulespec.MaximumVersion; - BaseGuid = modulespec.Guid; - - PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, modulespec.Name); - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, modulespec.Name); - if (foundModule != null) - { - SetModuleBaseForEngineModules(foundModule.Name, this.Context); - } + ImportModule_LocallyViaFQName(importModuleOptions, modulespec); } } else if (this.ParameterSetName.Equals(ParameterSet_FQName_ViaPsrpSession, StringComparison.OrdinalIgnoreCase)) @@ -1884,19 +1903,10 @@ private bool IsModuleInDenyList(string[] moduleDenyList, string moduleName, Modu { Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified"); - var exactModuleName = string.Empty; + // moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name + string exactModuleName = ModuleIntrinsics.GetModuleName(moduleSpec == null ? moduleName : moduleSpec.Name); bool match = false; - if (!string.IsNullOrEmpty(moduleName)) - { - // moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name - exactModuleName = Path.GetFileNameWithoutExtension(moduleName); - } - else if (moduleSpec != null) - { - exactModuleName = moduleSpec.Name; - } - foreach (var deniedModuleName in moduleDenyList) { // use case-insensitive module name comparison @@ -1910,7 +1920,7 @@ private bool IsModuleInDenyList(string[] moduleDenyList, string moduleName, Modu break; } } - + return match; } @@ -1941,6 +1951,49 @@ private List FilterModuleCollection(IEnumerable moduleCollection) return filteredModuleCollection; } + private void PrepareNoClobberWinCompatModuleImport(string moduleName, ModuleSpecification moduleSpec, ref ImportModuleOptions importModuleOptions) + { + Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified"); + + // moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name + string coreModuleToLoad = ModuleIntrinsics.GetModuleName(moduleSpec == null ? moduleName : moduleSpec.Name); + + var isModuleToLoadEngineModule = InitialSessionState.IsEngineModule(coreModuleToLoad); + string[] noClobberModuleList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityNoClobberModuleList(); + if (isModuleToLoadEngineModule || ((noClobberModuleList != null) && noClobberModuleList.Contains(coreModuleToLoad, StringComparer.OrdinalIgnoreCase))) + { + // if it is one of engine modules - first try to load it from $PSHOME\Modules + // otherwise rely on $env:PSModulePath (in which WinPS module location has to go after CorePS module location) + if (isModuleToLoadEngineModule) + { + string expectedCoreModulePath = Path.Combine(ModuleIntrinsics.GetPSHomeModulePath(), coreModuleToLoad); + if (Directory.Exists(expectedCoreModulePath)) + { + coreModuleToLoad = expectedCoreModulePath; + } + } + + if (moduleSpec == null) + { + ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, coreModuleToLoad); + } + else + { + ModuleSpecification tmpModuleSpec = new ModuleSpecification() + { + Guid = moduleSpec.Guid, + MaximumVersion = moduleSpec.MaximumVersion, + Version = moduleSpec.Version, + RequiredVersion = moduleSpec.RequiredVersion, + Name = coreModuleToLoad + }; + ImportModule_LocallyViaFQName(importModuleOptions, tmpModuleSpec); + } + + importModuleOptions.NoClobberExportPSSession = true; + } + } + internal override IList ImportModulesUsingWinCompat(IEnumerable moduleNames, IEnumerable moduleFullyQualifiedNames, ImportModuleOptions importModuleOptions) { IList moduleProxyList = new List(); @@ -1968,6 +2021,24 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable(); } + // perform necessary preparations if module has to be imported with NoClobber mode + if (filteredModuleNames != null) + { + foreach(string moduleName in filteredModuleNames) + { + PrepareNoClobberWinCompatModuleImport(moduleName, null, ref importModuleOptions); + } + } + + if (filteredModuleFullyQualifiedNames != null) + { + foreach(var moduleSpec in filteredModuleFullyQualifiedNames) + { + PrepareNoClobberWinCompatModuleImport(null, moduleSpec, ref importModuleOptions); + } + } + + // perform the module import / proxy generation moduleProxyList = ImportModule_RemotelyViaPsrpSession(importModuleOptions, filteredModuleNames, filteredModuleFullyQualifiedNames, WindowsPowerShellCompatRemotingSession, usingWinCompat: true); foreach (PSModuleInfo moduleProxy in moduleProxyList) @@ -1978,6 +2049,22 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable 0) + { + // make sure that we add registration only once to a multicast delegate + SyncCurrentLocationDelegate ??= SyncCurrentLocationHandler; + var alreadyregistered = this.SessionState.InvokeCommand.LocationChangedAction?.GetInvocationList().Contains(SyncCurrentLocationDelegate); + + if (!alreadyregistered ?? true) + { + this.SessionState.InvokeCommand.LocationChangedAction += SyncCurrentLocationDelegate; + + // first sync has to be triggered manually + SyncCurrentLocationHandler(sender: this, args: new LocationChangedEventArgs(sessionState: null, oldPath: null, newPath: this.SessionState.Path.CurrentLocation)); + } + } #endif return moduleProxyList; } diff --git a/src/System.Management.Automation/engine/Modules/ImportProvider.Tests.ps1 b/src/System.Management.Automation/engine/Modules/ImportProvider.Tests.ps1 new file mode 100644 index 00000000000..1bfcb84d0ce --- /dev/null +++ b/src/System.Management.Automation/engine/Modules/ImportProvider.Tests.ps1 @@ -0,0 +1,68 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Import PowerShell provider" -Tags "CI" { + BeforeAll { + $testModulePath = Join-Path $TestDrive "ReproModule" + New-Item -Path $testModulePath -ItemType Directory > $null + + New-ModuleManifest -Path "$testModulePath/ReproModule.psd1" -RootModule 'testmodule.dll' + + $testBinaryModulePath = Join-Path $testModulePath "testmodule.dll" + $binaryModule = @' +using System; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Provider; + +namespace module { + [CmdletProvider( + "SamplePrv", + ProviderCapabilities.ShouldProcess)] + public class SampleProvider : ContainerCmdletProvider { + protected override bool IsValidPath(string path) { + return true; + } + + protected override bool ItemExists(string path) { + return path == "test.txt"; + } + + protected override void GetItem(string path) { + Item resultItem; + if (path == "test.txt") { + resultItem = new Item { Name = "test.txt" }; + } else { + throw new Exception("Item not found."); + } + + WriteItemObject(resultItem, path, false); + } + + protected override Collection InitializeDefaultDrives() { + var drive = new PSDriveInfo( + "defaultSampleDrive", + ProviderInfo, + "/", + "Sample default drive", + null); + var result = new Collection {drive}; + return result; + } + + private class Item { + public string Name { get; set; } + } + } +} +'@ + Add-Type -OutputAssembly $testBinaryModulePath -TypeDefinition $binaryModule + + $pwsh = "$PSHOME\pwsh" + } + + It "Import a PowerShell provider with correct name" { + $result = & $pwsh -NoProfile -Command "Import-Module -Name $testModulePath; Get-Item ReproModule\SamplePrv::test.txt" + $result.PSPath | Should -BeExactly "ReproModule\SamplePrv::test.txt" + } +} diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 6fc4dcd0b14..0a4e51fc743 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -99,6 +99,12 @@ protected internal struct ImportModuleOptions /// This will be allowed when the manifest explicitly exports functions which will limit all visible module functions. /// internal bool AllowNestedModuleFunctionsToExport; + + /// + /// Flag that controls Export-PSSession -AllowClobber parameter in generating proxy modules from remote sessions. + /// Historically -AllowClobber in these scenarios was set as True. + /// + internal bool NoClobberExportPSSession; } /// @@ -231,10 +237,10 @@ internal List MatchAll private List _matchAll; // The list of commands permitted in a module manifest - internal static string[] PermittedCmdlets = new string[] { + internal static readonly string[] PermittedCmdlets = new string[] { "Import-LocalizedData", "ConvertFrom-StringData", "Write-Host", "Out-Host", "Join-Path" }; - internal static string[] ModuleManifestMembers = new string[] { + internal static readonly string[] ModuleManifestMembers = new string[] { "ModuleToProcess", "NestedModules", "GUID", @@ -297,7 +303,7 @@ internal List MatchAll /// /// Synchronization object for creation/cleanup of WindowsPS compat remoting session. /// - internal static object s_WindowsPowerShellCompatSyncObject = new object(); + internal static readonly object s_WindowsPowerShellCompatSyncObject = new object(); private Dictionary _currentlyProcessingModules = new Dictionary(); @@ -780,7 +786,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module } // The rooted files wasn't found, so don't search anymore... - if (found == false && wasRooted == true) + if (found == false && wasRooted) return null; if (searchModulePath && found == false && moduleFileFound == false) @@ -925,7 +931,7 @@ internal List GetModule(string[] names, bool all, bool refresh) { foreach (var n in names) { - if (n.IndexOf(StringLiterals.DefaultPathSeparator) != -1 || n.IndexOf(StringLiterals.AlternatePathSeparator) != -1) + if (n.Contains(StringLiterals.DefaultPathSeparator) || n.Contains(StringLiterals.AlternatePathSeparator)) { modulePaths.Add(n); } @@ -2359,7 +2365,7 @@ internal PSModuleInfo LoadModuleManifest( { if (importingModule) { - IList moduleProxies = ImportModulesUsingWinCompat(new string[] { moduleManifestPath }, null, new ImportModuleOptions()); + IList moduleProxies = ImportModulesUsingWinCompat(new string[] { moduleManifestPath }, null, options); // we are loading by a single ManifestPath so expect max of 1 if (moduleProxies.Count > 0) @@ -3082,7 +3088,7 @@ internal PSModuleInfo LoadModuleManifest( // In that case, the nested module will first be loaded with a different session state, and then when trying to load the RootModule via 'LoadModuleNamedInManifest', // the same loaded nested module will be reused for the RootModule by 'LoadModuleNamedInManifest'. - // Change the module name to match the manifest name, not the original name + // Change the module name to match the manifest name, not the original name. newManifestInfo.SetName(manifestInfo.Name); // Copy in any nested modules... @@ -3156,7 +3162,6 @@ internal PSModuleInfo LoadModuleManifest( newManifestInfo.ExperimentalFeatures = manifestInfo.ExperimentalFeatures; - // If we are in module discovery, then fix the path. if (ss == null) { @@ -4792,13 +4797,14 @@ internal static Collection GetResolvedPathCollection(string filePath, Ex return filePaths; } - internal PSSession GetWindowsPowerShellCompatRemotingSession() + internal static PSSession GetWindowsPowerShellCompatRemotingSession() { PSSession result = null; var commandInfo = new CmdletInfo("Get-PSSession", typeof(GetPSSessionCommand)); using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); ps.AddCommand(commandInfo); ps.AddParameter("Name", WindowsPowerShellCompatRemotingSessionName); + ps.AddParameter("ErrorAction", ActionPreference.Ignore); var results = ps.Invoke(); if (results.Count > 0) { @@ -4807,7 +4813,7 @@ internal PSSession GetWindowsPowerShellCompatRemotingSession() return result; } - internal PSSession CreateWindowsPowerShellCompatResources() + internal static PSSession CreateWindowsPowerShellCompatResources() { PSSession compatSession = null; lock (s_WindowsPowerShellCompatSyncObject) @@ -4832,13 +4838,18 @@ internal PSSession CreateWindowsPowerShellCompatResources() return compatSession; } - internal void CleanupWindowsPowerShellCompatResources() + internal static void CleanupWindowsPowerShellCompatResources(SessionState sessionState) { lock (s_WindowsPowerShellCompatSyncObject) { var compatSession = GetWindowsPowerShellCompatRemotingSession(); if (compatSession != null) { + if (sessionState?.InvokeCommand.LocationChangedAction != null) + { + sessionState.InvokeCommand.LocationChangedAction -= SyncCurrentLocationDelegate; + } + var commandInfo = new CmdletInfo("Remove-PSSession", typeof(RemovePSSessionCommand)); using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); ps.AddCommand(commandInfo); @@ -4848,6 +4859,21 @@ internal void CleanupWindowsPowerShellCompatResources() } } + internal static void SyncCurrentLocationHandler(object sender, LocationChangedEventArgs args) + { + PSSession compatSession = GetWindowsPowerShellCompatRemotingSession(); + if (compatSession?.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) + { + using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); + ps.AddCommand(new CmdletInfo("Invoke-Command", typeof(InvokeCommandCommand))); + ps.AddParameter("Session", compatSession); + ps.AddParameter("ScriptBlock", ScriptBlock.Create(string.Format("Set-Location -Path '{0}'", args.NewPath.Path))); + ps.Invoke(); + } + } + + internal static System.EventHandler SyncCurrentLocationDelegate; + internal virtual IList ImportModulesUsingWinCompat(IEnumerable moduleNames, IEnumerable moduleFullyQualifiedNames, ImportModuleOptions importModuleOptions) { throw new System.NotImplementedException(); } private void RemoveTypesAndFormatting( @@ -4944,7 +4970,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC if (module.IsWindowsPowerShellCompatModule && (System.Threading.Interlocked.Decrement(ref s_WindowsPowerShellCompatUsageCounter) == 0)) { - CleanupWindowsPowerShellCompatResources(); + CleanupWindowsPowerShellCompatResources(this.SessionState); } // First remove cmdlets from the session state @@ -5047,29 +5073,29 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // Remove the imported functions from SessionState... // (can't just go through module.SessionState.Internal.ExportedFunctions, // because the names of the functions might have been changed by the -Prefix parameter of Import-Module) - foreach (DictionaryEntry entry in ss.GetFunctionTable()) + foreach ((var _, FunctionInfo functionInfo) in ss.GetFunctionTable()) { - FunctionInfo func = (FunctionInfo)entry.Value; - if (func.Module == null) + if (functionInfo.Module == null) { continue; } - if (func.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) + if (functionInfo.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) { + string functionName = functionInfo.Name; try { - ss.RemoveFunction(func.Name, true); + ss.RemoveFunction(functionName, true); - string memberMessage = StringUtil.Format(Modules.RemovingImportedFunction, func.Name); + string memberMessage = StringUtil.Format(Modules.RemovingImportedFunction, functionName); WriteVerbose(memberMessage); } catch (SessionStateUnauthorizedAccessException e) { - string message = StringUtil.Format(Modules.UnableToRemoveModuleMember, func.Name, module.Name, e.Message); + string message = StringUtil.Format(Modules.UnableToRemoveModuleMember, functionName, module.Name, e.Message); InvalidOperationException memberNotRemoved = new InvalidOperationException(message, e); ErrorRecord er = new ErrorRecord(memberNotRemoved, "Modules_MemberNotRemoved", - ErrorCategory.PermissionDenied, func.Name); + ErrorCategory.PermissionDenied, functionName); WriteError(er); } } @@ -7121,7 +7147,7 @@ internal static void ImportModuleMembers( ImportModuleOptions options) { if (sourceModule == null) - throw PSTraceSource.NewArgumentNullException("sourceModule"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceModule)); bool isImportModulePrivate = cmdlet.CommandInfo.Visibility == SessionStateEntryVisibility.Private || targetSessionState.DefaultCommandVisibility == SessionStateEntryVisibility.Private; diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index feb511d109e..b20e11e4745 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -32,7 +32,7 @@ public class ModuleIntrinsics /// Tracer for module analysis. /// [TraceSource("Modules", "Module loading and analysis")] - internal static PSTraceSource Tracer = PSTraceSource.GetTracer("Modules", "Module loading and analysis"); + internal static readonly PSTraceSource Tracer = PSTraceSource.GetTracer("Modules", "Module loading and analysis"); // The %WINDIR%\System32\WindowsPowerShell\v1.0\Modules module path, // to load forward compatible Windows PowerShell modules from @@ -420,7 +420,6 @@ internal List GetModules(ModuleSpecification[] fullyQualifiedName, return modulesMatched.OrderBy(m => m.Name).ToList(); } - /// /// Check if a given module info object matches a given module specification. /// @@ -895,7 +894,7 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath } // The extensions of all of the files that can be processed with Import-Module, put the ni.dll in front of .dll to have higher priority to be loaded. - internal static string[] PSModuleProcessableExtensions = new string[] { + internal static readonly string[] PSModuleProcessableExtensions = new string[] { StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellScriptFileExtension, StringLiterals.PowerShellModuleFileExtension, @@ -906,7 +905,7 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath }; // A list of the extensions to check for implicit module loading and discovery, put the ni.dll in front of .dll to have higher priority to be loaded. - internal static string[] PSModuleExtensions = new string[] { + internal static readonly string[] PSModuleExtensions = new string[] { StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellModuleFileExtension, StringLiterals.PowerShellCmdletizationFileExtension, @@ -1234,7 +1233,7 @@ internal static string GetModulePath() #if !UNIX /// - /// Returns a PSModulePath suiteable for Windows PowerShell by removing this PowerShell's specific + /// Returns a PSModulePath suiteable for Windows PowerShell by removing PowerShell's specific /// paths from current PSModulePath. /// /// @@ -1250,7 +1249,7 @@ internal static string GetWindowsPowerShellModulePath() } // PowerShell specific paths including if set in powershell.config.json file we want to exclude - var excludeModulePaths = new HashSet { + var excludeModulePaths = new HashSet(StringComparer.OrdinalIgnoreCase) { GetPersonalModulePath(), GetSharedModulePath(), GetPSHomeModulePath(), @@ -1261,9 +1260,24 @@ internal static string GetWindowsPowerShellModulePath() var modulePathList = new List(); foreach (var path in currentModulePath.Split(';')) { - if (!excludeModulePaths.Contains(path)) + var trimmedPath = path.Trim(); + if (!excludeModulePaths.Contains(trimmedPath)) { - modulePathList.Add(path); + // make sure this module path is Not part of other PS Core installation + var possiblePwshDir = Path.GetDirectoryName(trimmedPath); + + if (string.IsNullOrEmpty(possiblePwshDir)) + { + // i.e. module dir is in the drive root + modulePathList.Add(trimmedPath); + } + else + { + if (!File.Exists(Path.Combine(possiblePwshDir, "pwsh.dll"))) + { + modulePathList.Add(trimmedPath); + } + } } } diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index 488d893b313..5333e364502 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index 41fb0c5c0e1..b825a54fbab 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index 2673c08ea5d..f61d3bb39bb 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 9b4da782d53..8b2e996bd84 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -538,7 +538,7 @@ private string QuoteName(string name) { if (name == null) return "''"; - return ("'" + name.ToString().Replace("'", "''") + "'"); + return ("'" + name.Replace("'", "''") + "'"); } /// diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index 11622e04680..15e2495e4fd 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -130,7 +130,7 @@ public PSModuleInfo(ScriptBlock scriptBlock) { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentException("scriptBlock"); + throw PSTraceSource.NewArgumentException(nameof(scriptBlock)); } // Get the ExecutionContext from the thread. @@ -1093,7 +1093,7 @@ private static void AddModuleToList(PSModuleInfo module, List modu moduleList.Add(module); } - internal static string[] _builtinVariables = new string[] { "_", "this", "input", "args", "true", "false", "null", + internal static readonly string[] _builtinVariables = new string[] { "_", "this", "input", "args", "true", "false", "null", "PSDefaultParameterValues", "Error", "PSScriptRoot", "PSCommandPath", "MyInvocation", "ExecutionContext", "StackTrace" }; /// @@ -1305,7 +1305,7 @@ public PSVariable GetVariableFromCallersModule(string variableName) { if (string.IsNullOrEmpty(variableName)) { - throw new ArgumentNullException("variableName"); + throw new ArgumentNullException(nameof(variableName)); } var context = LocalPipeline.GetExecutionContextFromTLS(); diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index 42584078d2e..4a1c50186eb 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -841,12 +841,14 @@ internal static Hashtable RewriteManifest(Hashtable originalManifest) "Description", "HelpInfoURI", }; + private static readonly string[] s_manifestEntriesToKeepAsStringArray = new[] { "FunctionsToExport", "VariablesToExport", "AliasesToExport", "CmdletsToExport", }; + internal static Hashtable RewriteManifest( Hashtable originalManifest, IEnumerable nestedModules, @@ -970,7 +972,7 @@ private static CimCredential GetCimCredentials(string authentication, PSCredenti } Dbg.Assert(false, "Unrecognized authentication mechanism [ValidateSet should prevent that from happening]"); - throw new ArgumentOutOfRangeException("authentication"); + throw new ArgumentOutOfRangeException(nameof(authentication)); } internal static CimSession CreateCimSession( diff --git a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs index 863c01922d0..64958c9fde6 100644 --- a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index 8893882c80d..6ec64a4cf0f 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -158,6 +158,7 @@ static ExportVisitor() } private readonly bool _forCompletion; + internal List DiscoveredExports { get; set; } internal List DiscoveredModules { get; set; } internal Dictionary DiscoveredFunctions { get; set; } diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index ca0350daa1d..2f6c0fdd5cf 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index c3d070f7030..d6c8d941a04 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -435,7 +435,7 @@ public CmdletInfo GetCmdletByTypeName(string cmdletTypeName) { if (string.IsNullOrEmpty(cmdletTypeName)) { - throw PSTraceSource.NewArgumentNullException("cmdletTypeName"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdletTypeName)); } Exception e = null; @@ -486,7 +486,7 @@ public List GetCmdlets() public List GetCmdlets(string pattern) { if (pattern == null) - throw PSTraceSource.NewArgumentNullException("pattern"); + throw PSTraceSource.NewArgumentNullException(nameof(pattern)); List cmdlets = new List(); @@ -548,7 +548,7 @@ public List GetCommandName(string name, bool nameIsPattern, bool returnF { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } List commands = new List(); @@ -608,7 +608,7 @@ public IEnumerable GetCommands(string name, CommandTypes commandTyp { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } SearchResolutionOptions options = nameIsPattern ? @@ -707,12 +707,12 @@ public Collection InvokeScript( { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentNullException("scriptBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } SessionStateInternal _oldSessionState = _context.EngineSessionState; @@ -745,7 +745,7 @@ public Collection InvokeScript( { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentNullException("scriptBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } // Force the current runspace onto the callers thread - this is needed @@ -784,7 +784,7 @@ public Collection InvokeScript(string script, bool useNewScope, PipelineResultTypes writeToPipeline, IList input, params object[] args) { if (script == null) - throw new ArgumentNullException("script"); + throw new ArgumentNullException(nameof(script)); // Compile the script text into an executable script block. ScriptBlock sb = ScriptBlock.Create(_context, script); diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 19c328785d8..4d07cd3d3a8 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -396,7 +396,7 @@ internal void WriteProgress( { if (progressRecord == null) { - throw PSTraceSource.NewArgumentNullException("progressRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } if (Host == null || Host.UI == null) @@ -926,6 +926,7 @@ private bool InitShouldLogPipelineExecutionDetail() /// the cmdlet. Semantically this is equivalent to : cmd | % { $pipelineVariable = $_; (...) } /// internal string PipelineVariable { get; set; } + private PSVariable _pipelineVarReference = null; internal void SetupOutVariable() @@ -2053,7 +2054,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) ThrowIfStopping(); if (errorRecord == null) { - throw PSTraceSource.NewArgumentNullException("errorRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } errorRecord.SetInvocationInfo(MyInvocation); @@ -2230,7 +2231,7 @@ internal object[] GetResultsAsArray() /// An empty array that is declared statically so we don't keep /// allocating them over and over... /// - internal static object[] StaticEmptyArray = Array.Empty(); + internal static readonly object[] StaticEmptyArray = Array.Empty(); /// /// Gets or sets the error pipe. @@ -2318,7 +2319,7 @@ private class AllowWrite : IDisposable internal AllowWrite(InternalCommand permittedToWrite, bool permittedToWriteToPipeline) { if (permittedToWrite == null) - throw PSTraceSource.NewArgumentNullException("permittedToWrite"); + throw PSTraceSource.NewArgumentNullException(nameof(permittedToWrite)); MshCommandRuntime mcr = permittedToWrite.commandRuntime as MshCommandRuntime; if (mcr == null) throw PSTraceSource.NewArgumentNullException("permittedToWrite.CommandRuntime"); @@ -2368,7 +2369,7 @@ public void Dispose() public Exception ManageException(Exception e) { if (e == null) - throw PSTraceSource.NewArgumentNullException("e"); + throw PSTraceSource.NewArgumentNullException(nameof(e)); if (PipelineProcessor != null) { diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index df4e78eff30..f60aa8f6f3e 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -173,6 +173,7 @@ public abstract class PSMemberInfo { internal object instance; internal string name; + internal bool ShouldSerialize { get; set; } internal virtual void ReplicateInstance(object particularInstance) @@ -228,7 +229,7 @@ protected void SetMemberName(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -375,13 +376,13 @@ public PSAliasProperty(string name, string referencedMemberName) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; if (string.IsNullOrEmpty(referencedMemberName)) { - throw PSTraceSource.NewArgumentException("referencedMemberName"); + throw PSTraceSource.NewArgumentException(nameof(referencedMemberName)); } ReferencedMemberName = referencedMemberName; @@ -400,13 +401,13 @@ public PSAliasProperty(string name, string referencedMemberName, Type conversion { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; if (string.IsNullOrEmpty(referencedMemberName)) { - throw PSTraceSource.NewArgumentException("referencedMemberName"); + throw PSTraceSource.NewArgumentException(nameof(referencedMemberName)); } ReferencedMemberName = referencedMemberName; @@ -772,7 +773,7 @@ internal PSCodeProperty(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -789,13 +790,13 @@ public PSCodeProperty(string name, MethodInfo getterCodeReference) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; if (getterCodeReference == null) { - throw PSTraceSource.NewArgumentNullException("getterCodeReference"); + throw PSTraceSource.NewArgumentNullException(nameof(getterCodeReference)); } SetGetter(getterCodeReference); @@ -818,7 +819,7 @@ public PSCodeProperty(string name, MethodInfo getterCodeReference, MethodInfo se { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -1075,7 +1076,7 @@ internal PSProperty(string name, Adapter adapter, object baseObject, object adap { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -1292,7 +1293,7 @@ public PSNoteProperty(string name, object value) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -1438,7 +1439,7 @@ public override string ToString() public PSVariableProperty(PSVariable variable) : base(variable?.Name, null) { - _variable = variable ?? throw PSTraceSource.NewArgumentException("variable"); + _variable = variable ?? throw PSTraceSource.NewArgumentException(nameof(variable)); } #region virtual implementation @@ -1665,12 +1666,12 @@ public PSScriptProperty(string name, ScriptBlock getterScript) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; - _getterScript = getterScript ?? throw PSTraceSource.NewArgumentNullException("getterScript"); + _getterScript = getterScript ?? throw PSTraceSource.NewArgumentNullException(nameof(getterScript)); } /// @@ -1685,7 +1686,7 @@ public PSScriptProperty(string name, ScriptBlock getterScript, ScriptBlock sette { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -1722,7 +1723,7 @@ internal PSScriptProperty(string name, string getterScript, string setterScript, { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -2156,7 +2157,7 @@ internal PSCodeMethod(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -2173,12 +2174,12 @@ public PSCodeMethod(string name, MethodInfo codeReference) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (codeReference == null) { - throw PSTraceSource.NewArgumentNullException("codeReference"); + throw PSTraceSource.NewArgumentNullException(nameof(codeReference)); } if (!CheckMethodInfo(codeReference)) @@ -2229,7 +2230,7 @@ public override object Invoke(params object[] arguments) { if (arguments == null) { - throw PSTraceSource.NewArgumentNullException("arguments"); + throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } object[] newArguments = new object[arguments.Length + 1]; @@ -2326,12 +2327,12 @@ public PSScriptMethod(string name, ScriptBlock script) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; - _script = script ?? throw PSTraceSource.NewArgumentNullException("script"); + _script = script ?? throw PSTraceSource.NewArgumentNullException(nameof(script)); } /// @@ -2364,7 +2365,7 @@ public override object Invoke(params object[] arguments) { if (arguments == null) { - throw PSTraceSource.NewArgumentNullException("arguments"); + throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } return InvokeScript(Name, _script, this.instance, arguments); @@ -2489,7 +2490,7 @@ internal PSMethod(string name, Adapter adapter, object baseObject, object adapte { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -2559,7 +2560,7 @@ internal object Invoke(PSMethodInvocationConstraints invocationConstraints, para { if (arguments == null) { - throw PSTraceSource.NewArgumentNullException("arguments"); + throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } return _adapter.BaseMethodInvoke(this, invocationConstraints, arguments); @@ -2803,7 +2804,7 @@ public bool MoveNext() return MoveNext(_t, _currentIndex); } - bool MoveNext(Type type, int index) + private bool MoveNext(Type type, int index) { var genericTypeArguments = type.GenericTypeArguments; var length = genericTypeArguments.Length; @@ -2908,7 +2909,7 @@ internal PSParameterizedProperty(string name, Adapter adapter, object baseObject { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -2921,7 +2922,7 @@ internal PSParameterizedProperty(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; @@ -2950,7 +2951,7 @@ public override object Invoke(params object[] arguments) { if (arguments == null) { - throw PSTraceSource.NewArgumentNullException("arguments"); + throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } return this.adapter.BaseParameterizedPropertyGet(this, arguments); @@ -2967,7 +2968,7 @@ public void InvokeSet(object valueToSet, params object[] arguments) { if (arguments == null) { - throw PSTraceSource.NewArgumentNullException("arguments"); + throw PSTraceSource.NewArgumentNullException(nameof(arguments)); } this.adapter.BaseParameterizedPropertySet(this, valueToSet, arguments); @@ -3172,13 +3173,13 @@ internal PSMemberSet(string name, PSObject mshObject) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } this.name = name; if (mshObject == null) { - throw PSTraceSource.NewArgumentNullException("mshObject"); + throw PSTraceSource.NewArgumentNullException(nameof(mshObject)); } _constructorPSObject = mshObject; @@ -3692,12 +3693,12 @@ internal static PSMemberInfoInternalCollection Match(PSMemberInfoInternalC PSMemberInfoInternalCollection returnValue = new PSMemberInfoInternalCollection(); if (memberList == null) { - throw PSTraceSource.NewArgumentNullException("memberList"); + throw PSTraceSource.NewArgumentNullException(nameof(memberList)); } if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (nameMatch == null) @@ -3884,7 +3885,7 @@ internal ReadOnlyPSMemberInfoCollection(PSMemberInfoInternalCollection member { if (members == null) { - throw PSTraceSource.NewArgumentNullException("members"); + throw PSTraceSource.NewArgumentNullException(nameof(members)); } _members = members; @@ -3902,7 +3903,7 @@ public T this[string name] { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return _members[name]; @@ -3919,7 +3920,7 @@ public ReadOnlyPSMemberInfoCollection Match(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return _members.Match(name); @@ -3936,7 +3937,7 @@ public ReadOnlyPSMemberInfoCollection Match(string name, PSMemberTypes member { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return _members.Match(name, memberTypes); @@ -4069,7 +4070,7 @@ public override void Add(T member, bool preValidated) { if (member == null) { - throw PSTraceSource.NewArgumentNullException("member"); + throw PSTraceSource.NewArgumentNullException(nameof(member)); } // Save to a local variable to reduce property access. @@ -4101,7 +4102,7 @@ public override void Remove(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (IsReservedName(name)) @@ -4143,7 +4144,7 @@ public override T this[string name] { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (_members == null) @@ -4168,7 +4169,7 @@ public override ReadOnlyPSMemberInfoCollection Match(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return Match(name, PSMemberTypes.All, MshMemberMatchOptions.None); @@ -4185,7 +4186,7 @@ public override ReadOnlyPSMemberInfoCollection Match(string name, PSMemberTyp { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return Match(name, memberTypes, MshMemberMatchOptions.None); @@ -4203,7 +4204,7 @@ internal override ReadOnlyPSMemberInfoCollection Match(string name, PSMemberT { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } PSMemberInfoInternalCollection internalMembers = GetInternalMembers(matchOptions); @@ -4500,19 +4501,19 @@ internal PSMemberInfoIntegratingCollection(object owner, Collection Match(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return Match(name, PSMemberTypes.All, MshMemberMatchOptions.None); @@ -4925,7 +4926,7 @@ public override ReadOnlyPSMemberInfoCollection Match(string name, PSMemberTyp { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } return Match(name, memberTypes, MshMemberMatchOptions.None); @@ -4945,7 +4946,7 @@ internal override ReadOnlyPSMemberInfoCollection Match(string name, PSMemberT { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (_mshOwner != null) diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 80d5b90e106..cd7a8cf0a14 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -424,6 +424,7 @@ private void CommonInitialization(object obj) #region Adapter Mappings private static readonly ConcurrentDictionary s_adapterMapping = new ConcurrentDictionary(); + private static readonly List> s_adapterSetMappers = new List> { MappedInternalAdapterSet @@ -569,7 +570,7 @@ public PSObject(object obj) { if (obj == null) { - throw PSTraceSource.NewArgumentNullException("obj"); + throw PSTraceSource.NewArgumentNullException(nameof(obj)); } CommonInitialization(obj); @@ -584,14 +585,14 @@ protected PSObject(SerializationInfo info, StreamingContext context) { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } string serializedData = info.GetValue("CliXml", typeof(string)) as string; if (serializedData == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } PSObject result = PSObject.AsPSObject(PSSerializer.Deserialize(serializedData)); @@ -647,6 +648,7 @@ internal static PSObject ConstructPSObjectFromSerializationInfo(SerializationInf private static readonly AdapterSet s_dotNetInstanceAdapterSet = new AdapterSet(DotNetInstanceAdapter, null); private static readonly AdapterSet s_mshMemberSetAdapter = new AdapterSet(new PSMemberSetAdapter(), null); private static readonly AdapterSet s_mshObjectAdapter = new AdapterSet(new PSObjectAdapter(), null); + private static readonly PSObject.AdapterSet s_cimInstanceAdapter = new PSObject.AdapterSet(new ThirdPartyAdapter(typeof(Microsoft.Management.Infrastructure.CimInstance), new Microsoft.PowerShell.Cim.CimInstanceAdapter()), @@ -774,7 +776,6 @@ public PSMemberInfoCollection Properties } } - /// /// Gets the Method collection, or the members that are actually methods. /// @@ -1051,7 +1052,7 @@ internal static PSObject AsPSObject(object obj, bool storeTypeNameAndInstanceMem { if (obj == null) { - throw PSTraceSource.NewArgumentNullException("obj"); + throw PSTraceSource.NewArgumentNullException(nameof(obj)); } if (obj is PSObject so) @@ -1815,7 +1816,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } // We create a wrapper PSObject, so that we can successfully deserialize it @@ -2464,7 +2465,8 @@ public class PSCustomObject /// private PSCustomObject() { } - internal static PSCustomObject SelfInstance = new PSCustomObject(); + internal static readonly PSCustomObject SelfInstance = new PSCustomObject(); + /// /// Returns an empty string. /// diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index f7e6e50be4b..ee54859a1ea 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; @@ -171,7 +171,7 @@ public override object GetValue(object component) { if (component == null) { - throw PSTraceSource.NewArgumentNullException("component"); + throw PSTraceSource.NewArgumentNullException(nameof(component)); } PSObject mshObj = GetComponentPSObject(component); @@ -221,7 +221,7 @@ private static PSObject GetComponentPSObject(object component) PSObjectTypeDescriptor descriptor = component as PSObjectTypeDescriptor; if (descriptor == null) { - throw PSTraceSource.NewArgumentException("component", ExtendedTypeSystem.InvalidComponent, + throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent, "component", typeof(PSObject).Name, typeof(PSObjectTypeDescriptor).Name); @@ -270,7 +270,7 @@ public override void SetValue(object component, object value) { if (component == null) { - throw PSTraceSource.NewArgumentNullException("component"); + throw PSTraceSource.NewArgumentNullException(nameof(component)); } PSObject mshObj = GetComponentPSObject(component); @@ -330,7 +330,7 @@ private void DealWithSetValueException(ExtendedTypeSystemException e, out bool s /// public class PSObjectTypeDescriptor : CustomTypeDescriptor { - internal static PSTraceSource typeDescriptor = PSTraceSource.GetTracer("TypeDescriptor", "Traces the behavior of PSObjectTypeDescriptor, PSObjectTypeDescriptionProvider and PSObjectPropertyDescriptor.", false); + internal static readonly PSTraceSource typeDescriptor = PSTraceSource.GetTracer("TypeDescriptor", "Traces the behavior of PSObjectTypeDescriptor, PSObjectTypeDescriptionProvider and PSObjectPropertyDescriptor.", false); /// /// Occurs when there was an exception setting the value of a property. diff --git a/src/System.Management.Automation/engine/MshReference.cs b/src/System.Management.Automation/engine/MshReference.cs index eeeca79e178..05077708608 100644 --- a/src/System.Management.Automation/engine/MshReference.cs +++ b/src/System.Management.Automation/engine/MshReference.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Dynamic; diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs index b207df2cf52..878de10e2b4 100644 --- a/src/System.Management.Automation/engine/MshSecurityException.cs +++ b/src/System.Management.Automation/engine/MshSecurityException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index 94231ed8654..b23df2202eb 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -1,6 +1,8 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation @@ -62,15 +64,14 @@ private PSSnapinQualifiedName(string[] splitName) /// /// An instance of the Name class. /// - internal static PSSnapinQualifiedName GetInstance(string name) + internal static PSSnapinQualifiedName? GetInstance(string? name) { if (name == null) return null; - PSSnapinQualifiedName result = null; string[] splitName = name.Split(Utils.Separators.Backslash); if (splitName.Length == 0 || splitName.Length > 2) return null; - result = new PSSnapinQualifiedName(splitName); + var result = new PSSnapinQualifiedName(splitName); // If the shortname is empty, then return null... if (string.IsNullOrEmpty(result.ShortName)) { @@ -91,12 +92,12 @@ internal string FullName } } - private string _fullName; + private readonly string _fullName; /// /// Gets the command's PSSnapin name. /// - internal string PSSnapInName + internal string? PSSnapInName { get { @@ -104,7 +105,7 @@ internal string PSSnapInName } } - private string _psSnapinName; + private readonly string? _psSnapinName; /// /// Gets the command's short name. @@ -117,7 +118,7 @@ internal string ShortName } } - private string _shortName; + private readonly string _shortName; /// /// The full name. diff --git a/src/System.Management.Automation/engine/NativeCommand.cs b/src/System.Management.Automation/engine/NativeCommand.cs index 7147ea86a8a..822d4cf82d9 100644 --- a/src/System.Management.Automation/engine/NativeCommand.cs +++ b/src/System.Management.Automation/engine/NativeCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -11,6 +11,7 @@ namespace System.Management.Automation internal sealed class NativeCommand : InternalCommand { private NativeCommandProcessor _myCommandProcessor; + internal NativeCommandProcessor MyCommandProcessor { get { return _myCommandProcessor; } diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index 68d1fd2f191..0091596a443 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -81,8 +81,8 @@ internal void BindParameters(Collection parameters) if (parameter.ParameterNameSpecified) { - Diagnostics.Assert(parameter.ParameterText.IndexOf(' ') == -1, "Parameters cannot have whitespace"); - PossiblyGlobArg(parameter.ParameterText, usedQuotes: false); + Diagnostics.Assert(!parameter.ParameterText.Contains(' '), "Parameters cannot have whitespace"); + PossiblyGlobArg(parameter.ParameterText, StringConstantType.BareWord); if (parameter.SpaceAfterParameter) { @@ -107,23 +107,30 @@ internal void BindParameters(Collection parameters) // windbg -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect // The parser produced an array of strings but marked the parameter so we // can properly reconstruct the correct command line. - bool usedQuotes = false; + StringConstantType stringConstantType = StringConstantType.BareWord; ArrayLiteralAst arrayLiteralAst = null; switch (parameter?.ArgumentAst) { case StringConstantExpressionAst sce: - usedQuotes = sce.StringConstantType != StringConstantType.BareWord; + stringConstantType = sce.StringConstantType; break; case ExpandableStringExpressionAst ese: - usedQuotes = ese.StringConstantType != StringConstantType.BareWord; + stringConstantType = ese.StringConstantType; break; case ArrayLiteralAst ala: arrayLiteralAst = ala; break; } - appendOneNativeArgument(Context, argValue, - arrayLiteralAst, sawVerbatimArgumentMarker, usedQuotes); + // Prior to PSNativePSPathResolution experimental feature, a single quote worked the same as a double quote + // so if the feature is not enabled, we treat any quotes as double quotes. When this feature is no longer + // experimental, this code here needs to be removed. + if (!ExperimentalFeature.IsEnabled("PSNativePSPathResolution") && stringConstantType == StringConstantType.SingleQuoted) + { + stringConstantType = StringConstantType.DoubleQuoted; + } + + AppendOneNativeArgument(Context, argValue, arrayLiteralAst, sawVerbatimArgumentMarker, stringConstantType); } } } @@ -157,14 +164,12 @@ internal string Arguments /// The object to append. /// If the argument was an array literal, the Ast, otherwise null. /// True if the argument occurs after --%. - /// True if the argument was a quoted string (single or double). - private void appendOneNativeArgument(ExecutionContext context, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, bool usedQuotes) + /// Bare, SingleQuoted, or DoubleQuoted. + private void AppendOneNativeArgument(ExecutionContext context, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, StringConstantType stringConstantType) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); - Diagnostics.Assert(argArrayAst == null - || obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count, - "array argument and ArrayLiteralAst differ in number of elements"); + Diagnostics.Assert((argArrayAst == null) || obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count, "array argument and ArrayLiteralAst differ in number of elements"); int currentElement = -1; string separator = string.Empty; @@ -218,9 +223,18 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array if (NeedQuotes(arg)) { _arguments.Append('"'); + + if (stringConstantType == StringConstantType.DoubleQuoted) + { + _arguments.Append(ResolvePath(arg, Context)); + } + else + { + _arguments.Append(arg); + } + // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC - _arguments.Append(arg); for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); @@ -230,11 +244,12 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array } else { - PossiblyGlobArg(arg, usedQuotes); + PossiblyGlobArg(arg, stringConstantType); } } } - } while (list != null); + } + while (list != null); } /// @@ -242,94 +257,168 @@ private void appendOneNativeArgument(ExecutionContext context, object obj, Array /// On Unix, do globbing as appropriate, otherwise just append . /// /// The argument that possibly needs expansion. - /// True if the argument was a quoted string (single or double). - private void PossiblyGlobArg(string arg, bool usedQuotes) + /// Bare, SingleQuoted, or DoubleQuoted. + private void PossiblyGlobArg(string arg, StringConstantType stringConstantType) { var argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against // the file system just like bash, etc. - if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg)) - { - // See if the current working directory is a filesystem provider location - // We won't do the expansion if it isn't since native commands can only access the file system. - var cwdinfo = Context.EngineSessionState.CurrentLocation; - // If it's a filesystem location then expand the wildcards - if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + if (stringConstantType == StringConstantType.BareWord) + { + if (WildcardPattern.ContainsWildcardCharacters(arg)) { - // On UNIX, paths starting with ~ or absolute paths are not normalized - bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/'); + // See if the current working directory is a filesystem provider location + // We won't do the expansion if it isn't since native commands can only access the file system. + var cwdinfo = Context.EngineSessionState.CurrentLocation; - // See if there are any matching paths otherwise just add the pattern as the argument - Collection paths = null; - try - { - paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); - } - catch + // If it's a filesystem location then expand the wildcards + if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - // Fallthrough will append the pattern unchanged. - } + // On UNIX, paths starting with ~ or absolute paths are not normalized + bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/'); - // Expand paths, but only from the file system. - if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo)) - { - var sep = string.Empty; - foreach (var path in paths) + // See if there are any matching paths otherwise just add the pattern as the argument + Collection paths = null; + try { - _arguments.Append(sep); - sep = " "; - var expandedPath = (path.BaseObject as FileSystemInfo).FullName; - if (normalizePath) - { - expandedPath = - Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); - } - // If the path contains spaces, then add quotes around it. - if (NeedQuotes(expandedPath)) - { - _arguments.Append("\""); - _arguments.Append(expandedPath); - _arguments.Append("\""); - } - else + paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); + } + catch + { + // Fallthrough will append the pattern unchanged. + } + + // Expand paths, but only from the file system. + if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo)) + { + var sep = string.Empty; + foreach (var path in paths) { - _arguments.Append(expandedPath); + _arguments.Append(sep); + sep = " "; + var expandedPath = (path.BaseObject as FileSystemInfo).FullName; + if (normalizePath) + { + expandedPath = + Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); + } + // If the path contains spaces, then add quotes around it. + if (NeedQuotes(expandedPath)) + { + _arguments.Append("\""); + _arguments.Append(expandedPath); + _arguments.Append("\""); + } + else + { + _arguments.Append(expandedPath); + } + + argExpanded = true; } - - argExpanded = true; } } } - } - else if (!usedQuotes) - { - // Even if there are no wildcards, we still need to possibly - // expand ~ into the filesystem provider home directory path - ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); - string home = fileSystemProvider.Home; - if (string.Equals(arg, "~")) - { - _arguments.Append(home); - argExpanded = true; - } - else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) + else { - var replacementString = home + arg.Substring(1); - _arguments.Append(replacementString); - argExpanded = true; + // Even if there are no wildcards, we still need to possibly + // expand ~ into the filesystem provider home directory path + ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); + string home = fileSystemProvider.Home; + if (string.Equals(arg, "~")) + { + _arguments.Append(home); + argExpanded = true; + } + else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) + { + var replacementString = home + arg.Substring(1); + _arguments.Append(replacementString); + argExpanded = true; + } } } #endif // UNIX + if (stringConstantType != StringConstantType.SingleQuoted) + { + arg = ResolvePath(arg, Context); + } + if (!argExpanded) { _arguments.Append(arg); } } + /// + /// Check if string is prefixed by psdrive, if so, expand it if filesystem path. + /// + /// The potential PSPath to resolve. + /// The current ExecutionContext. + /// Resolved PSPath if applicable otherwise the original path + internal static string ResolvePath(string path, ExecutionContext context) + { + if (ExperimentalFeature.IsEnabled("PSNativePSPathResolution")) + { +#if !UNIX + // on Windows, we need to expand ~ to point to user's home path + if (string.Equals(path, "~", StringComparison.Ordinal) || path.StartsWith(TildeDirectorySeparator, StringComparison.Ordinal) || path.StartsWith(TildeAltDirectorySeparator, StringComparison.Ordinal)) + { + try + { + ProviderInfo fileSystemProvider = context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); + return new StringBuilder(fileSystemProvider.Home) + .Append(path.Substring(1)) + .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + .ToString(); + } + catch + { + return path; + } + } + + // check if the driveName is an actual disk drive on Windows, if so, no expansion + if (path.Length >= 2 && path[1] == ':') + { + foreach (var drive in DriveInfo.GetDrives()) + { + if (drive.Name.StartsWith(new string(path[0], 1), StringComparison.OrdinalIgnoreCase)) + { + return path; + } + } + } +#endif + + if (path.Contains(':')) + { + LocationGlobber globber = new LocationGlobber(context.SessionState); + try + { + ProviderInfo providerInfo; + + // replace the argument with resolved path if it's a filesystem path + string pspath = globber.GetProviderPath(path, out providerInfo); + if (string.Equals(providerInfo.Name, FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + { + path = pspath; + } + } + catch + { + // if it's not a provider path, do nothing + } + } + } + + return path; + } + /// /// Check to see if the string contains spaces and therefore must be quoted. /// @@ -384,6 +473,9 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, /// The native command to bind to. /// private NativeCommand _nativeCommand; + private static readonly string TildeDirectorySeparator = $"~{Path.DirectorySeparatorChar}"; + private static readonly string TildeAltDirectorySeparator = $"~{Path.AltDirectorySeparatorChar}"; + #endregion private members } } diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs index 9fddd2cc827..5acdf199637 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index c41cd9a055b..3a12dab6295 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -161,7 +161,7 @@ internal NativeCommandProcessor(ApplicationInfo applicationInfo, ExecutionContex { if (applicationInfo == null) { - throw PSTraceSource.NewArgumentNullException("applicationInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(applicationInfo)); } _applicationInfo = applicationInfo; @@ -817,6 +817,7 @@ internal struct ProcessWithParentId { public Process OriginalProcessInstance; private int _parentId; + public int ParentId { get @@ -1245,7 +1246,7 @@ private void CalculateIORedirection(out bool redirectOutput, out bool redirectEr // In minishell scenario, if output is redirected // then error should also be redirected. - if (redirectError == false && redirectOutput == true && _isMiniShell) + if (redirectError == false && redirectOutput && _isMiniShell) { redirectError = true; } @@ -1407,8 +1408,10 @@ private struct SHFILEINFO public IntPtr hIcon; public int iIcon; public uint dwAttributes; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szDisplayName; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string szTypeName; }; @@ -1484,7 +1487,7 @@ public ProcessOutputHandler(Process process, BlockingCollection /// Stop writing input to process. @@ -2139,6 +2142,7 @@ protected RemoteException(SerializationInfo info, StreamingContext context) [NonSerialized] private PSObject _serializedRemoteException; + [NonSerialized] private PSObject _serializedRemoteInvocationInfo; diff --git a/src/System.Management.Automation/engine/NullString.cs b/src/System.Management.Automation/engine/NullString.cs index 31c6f803526..9ac2ebe7c7e 100644 --- a/src/System.Management.Automation/engine/NullString.cs +++ b/src/System.Management.Automation/engine/NullString.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Language diff --git a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs index 3a81a9c3d2e..3c385a6f7bf 100644 --- a/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs +++ b/src/System.Management.Automation/engine/ObjectEventRegistrationBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/PSClassInfo.cs b/src/System.Management.Automation/engine/PSClassInfo.cs index 2b999c9a3fb..199f7f1b2b7 100644 --- a/src/System.Management.Automation/engine/PSClassInfo.cs +++ b/src/System.Management.Automation/engine/PSClassInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -62,7 +62,7 @@ public sealed class PSClassMemberInfo internal PSClassMemberInfo(string name, string memberType, string defaultValue) { if (string.IsNullOrEmpty(name)) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); this.Name = name; this.TypeName = memberType; diff --git a/src/System.Management.Automation/engine/PSClassSearcher.cs b/src/System.Management.Automation/engine/PSClassSearcher.cs index aa7ae80d604..613035820d0 100644 --- a/src/System.Management.Automation/engine/PSClassSearcher.cs +++ b/src/System.Management.Automation/engine/PSClassSearcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index c25eb20e1b6..aacf5c50e32 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -51,6 +51,7 @@ internal sealed class PowerShellConfig private const string ExecutionPolicyDefaultShellKey = "Microsoft.PowerShell:ExecutionPolicy"; private const string DisableImplicitWinCompatKey = "DisableImplicitWinCompat"; private const string WindowsPowerShellCompatibilityModuleDenyListKey = "WindowsPowerShellCompatibilityModuleDenyList"; + private const string WindowsPowerShellCompatibilityNoClobberModuleListKey = "WindowsPowerShellCompatibilityNoClobberModuleList"; // Provide a singleton internal static readonly PowerShellConfig Instance = new PowerShellConfig(); @@ -218,26 +219,23 @@ internal void SetExperimentalFeatures(ConfigScope scope, string featureName, boo internal bool IsImplicitWinCompatEnabled() { - bool? settingValue = ReadValueFromFile(ConfigScope.CurrentUser, DisableImplicitWinCompatKey); - if (!settingValue.HasValue) - { - // if the setting is not mentioned in configuration files, then the default DisableImplicitWinCompat value is False - settingValue = ReadValueFromFile(ConfigScope.AllUsers, DisableImplicitWinCompatKey, defaultValue: false); - } + bool settingValue = ReadValueFromFile(ConfigScope.CurrentUser, DisableImplicitWinCompatKey) + ?? ReadValueFromFile(ConfigScope.AllUsers, DisableImplicitWinCompatKey) + ?? false; - return !settingValue.Value; + return !settingValue; } internal string[] GetWindowsPowerShellCompatibilityModuleDenyList() { - string[] settingValue = ReadValueFromFile(ConfigScope.CurrentUser, WindowsPowerShellCompatibilityModuleDenyListKey); - if (settingValue == null) - { - // if the setting is not mentioned in configuration files, then the default WindowsPowerShellCompatibilityModuleDenyList value is null - settingValue = ReadValueFromFile(ConfigScope.AllUsers, WindowsPowerShellCompatibilityModuleDenyListKey); - } + return ReadValueFromFile(ConfigScope.CurrentUser, WindowsPowerShellCompatibilityModuleDenyListKey) + ?? ReadValueFromFile(ConfigScope.AllUsers, WindowsPowerShellCompatibilityModuleDenyListKey); + } - return settingValue; + internal string[] GetWindowsPowerShellCompatibilityNoClobberModuleList() + { + return ReadValueFromFile(ConfigScope.CurrentUser, WindowsPowerShellCompatibilityNoClobberModuleListKey) + ?? ReadValueFromFile(ConfigScope.AllUsers, WindowsPowerShellCompatibilityNoClobberModuleListKey); } /// diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 7ac1c4b94ba..1378f0f0c5e 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -39,6 +39,7 @@ public class PSVersionInfo internal const string PSOSName = "OS"; internal const string SerializationVersionName = "SerializationVersion"; internal const string WSManStackVersionName = "WSManStackVersion"; + private static readonly PSVersionHashTable s_psVersionTable; /// @@ -108,12 +109,12 @@ static PSVersionInfo() s_psVersionTable[PSVersionInfo.PSVersionName] = s_psSemVersion; s_psVersionTable[PSVersionInfo.PSEditionName] = PSEditionValue; s_psVersionTable[PSGitCommitIdName] = rawGitCommitId; - s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psVersion }; + s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psVersion }; s_psVersionTable[PSVersionInfo.SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); s_psVersionTable[PSVersionInfo.PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; s_psVersionTable[PSVersionInfo.WSManStackVersionName] = GetWSManStackVersion(); s_psVersionTable[PSPlatformName] = Environment.OSVersion.Platform.ToString(); - s_psVersionTable[PSOSName] = Runtime.InteropServices.RuntimeInformation.OSDescription.ToString(); + s_psVersionTable[PSOSName] = Runtime.InteropServices.RuntimeInformation.OSDescription; } internal static PSVersionHashTable GetPSVersionTable() @@ -350,6 +351,7 @@ internal static SemanticVersion PSCurrentVersion public sealed class PSVersionHashTable : Hashtable, IEnumerable { private static readonly PSVersionTableComparer s_keysComparer = new PSVersionTableComparer(); + internal PSVersionHashTable(IEqualityComparer equalityComparer) : base(equalityComparer) { } @@ -429,6 +431,7 @@ public sealed class SemanticVersion : IComparable, IComparable, private const string PreLabelPropertyName = "PSSemVerPreReleaseLabel"; private const string BuildLabelPropertyName = "PSSemVerBuildLabel"; private const string TypeNameForVersionWithLabel = "System.Version#IncludeLabel"; + private string versionString; /// diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index 8edc637b3cf..4dcb5488041 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -61,7 +61,7 @@ internal abstract class ParameterBinderBase private static PSTraceSource s_tracer = PSTraceSource.GetTracer("ParameterBinderBase", "A abstract helper class for the CommandProcessor that binds parameters to the specified object."); [TraceSource("ParameterBinding", "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.")] - internal static PSTraceSource bindingTracer = + internal static readonly PSTraceSource bindingTracer = PSTraceSource.GetTracer( "ParameterBinding", "Traces the process of binding the arguments to the parameters of cmdlets, scripts, and applications.", @@ -243,7 +243,7 @@ private void ValidatePSTypeName( if (!psTypeNamesOfArgumentValue.Contains(psTypeNameRequestedByParameter, StringComparer.OrdinalIgnoreCase)) { // win8: 228176..The callers know when to ignore and when not to ignore invalid cast exceptions. - PSInvalidCastException e = new PSInvalidCastException(ErrorCategory.InvalidArgument.ToString(), + PSInvalidCastException e = new PSInvalidCastException(nameof(ErrorCategory.InvalidArgument), null, ParameterBinderStrings.MismatchedPSTypeName, (_invocationInfo != null) && (_invocationInfo.MyCommand != null) ? _invocationInfo.MyCommand.Name : string.Empty, @@ -337,12 +337,12 @@ internal virtual bool BindParameter( if (parameter == null) { - throw PSTraceSource.NewArgumentNullException("parameter"); + throw PSTraceSource.NewArgumentNullException(nameof(parameter)); } if (parameterMetadata == null) { - throw PSTraceSource.NewArgumentNullException("parameterMetadata"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } using (bindingTracer.TraceScope( @@ -904,6 +904,7 @@ private bool ShouldContinueUncoercedBind( /// The invocation information for the code that is being bound. /// private InvocationInfo _invocationInfo; + internal InvocationInfo InvocationInfo { get @@ -916,6 +917,7 @@ internal InvocationInfo InvocationInfo /// The context of the currently running engine. /// private ExecutionContext _context; + internal ExecutionContext Context { get @@ -928,6 +930,7 @@ internal ExecutionContext Context /// An instance of InternalCommand that the binder is binding to. /// private InternalCommand _command; + internal InternalCommand Command { get @@ -986,12 +989,12 @@ private object CoerceTypeAsNeeded( { if (argument == null) { - throw PSTraceSource.NewArgumentNullException("argument"); + throw PSTraceSource.NewArgumentNullException(nameof(argument)); } if (toType == null) { - throw PSTraceSource.NewArgumentNullException("toType"); + throw PSTraceSource.NewArgumentNullException(nameof(toType)); } // Construct the collection type information if it wasn't passed in. @@ -1798,7 +1801,7 @@ private object EncodeCollection( if (coerceElementTypeIfNeeded) { bindingTracer.WriteLine( - "Coercing scalar arg value to type {1}", + "Coercing scalar arg value to type {0}", collectionElementType); // Coerce the scalar type into the collection diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index 6bad34823ba..a68192c7a90 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -345,7 +345,7 @@ internal static void AddArgumentsToCommandProcessor(CommandProcessorBase command { param = CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, paramText.Substring(1, colonIndex - 1), paramText, - /*argumentAst*/null, paramText.Substring(colonIndex + 1).Trim(), + /*argumentAst*/null, paramText.AsSpan(colonIndex + 1).Trim().ToString(), false); } else if (argIndex == arguments.Length - 1 || paramText[paramText.Length - 1] != ':') @@ -872,7 +872,7 @@ protected void ThrowElaboratedBindingException(ParameterBindingException pbex) { if (pbex == null) { - throw PSTraceSource.NewArgumentNullException("pbex"); + throw PSTraceSource.NewArgumentNullException(nameof(pbex)); } Diagnostics.Assert(pbex.ErrorRecord != null, "ErrorRecord should not be null in a ParameterBindingException"); diff --git a/src/System.Management.Automation/engine/ParameterInfo.cs b/src/System.Management.Automation/engine/ParameterInfo.cs index 84ac0165e04..cf1784a7b62 100644 --- a/src/System.Management.Automation/engine/ParameterInfo.cs +++ b/src/System.Management.Automation/engine/ParameterInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -32,7 +32,7 @@ internal CommandParameterInfo( { if (parameter == null) { - throw PSTraceSource.NewArgumentNullException("parameter"); + throw PSTraceSource.NewArgumentNullException(nameof(parameter)); } Name = parameter.Name; diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index 240a242fcd1..c166f749b1c 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -52,12 +52,12 @@ internal CommandParameterSetInfo( Name = string.Empty; if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (parameterMetadata == null) { - throw PSTraceSource.NewArgumentNullException("parameterMetadata"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata)); } this.Name = name; @@ -292,7 +292,7 @@ internal static string GetParameterTypeString(Type type, IEnumerable } // If the type is really an array, but the typename didn't include [], then add it. - if (type.IsArray && (parameterTypeString.IndexOf("[]", StringComparison.Ordinal) == -1)) + if (type.IsArray && !parameterTypeString.Contains("[]", StringComparison.Ordinal)) { var t = type; while (t.IsArray) diff --git a/src/System.Management.Automation/engine/ParameterSetPromptingData.cs b/src/System.Management.Automation/engine/ParameterSetPromptingData.cs index d34e3e332c1..0f7889f8d0b 100644 --- a/src/System.Management.Automation/engine/ParameterSetPromptingData.cs +++ b/src/System.Management.Automation/engine/ParameterSetPromptingData.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs index 14c8e07b490..4cc4ca7540e 100644 --- a/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs +++ b/src/System.Management.Automation/engine/ParameterSetSpecificMetadata.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation @@ -21,7 +21,7 @@ internal ParameterSetSpecificMetadata(ParameterAttribute attribute) { if (attribute == null) { - throw PSTraceSource.NewArgumentNullException("attribute"); + throw PSTraceSource.NewArgumentNullException(nameof(attribute)); } _attribute = attribute; diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 612411fc70e..d11a225797e 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -40,7 +40,7 @@ internal PathIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index a2473d1e44b..ac9350487a0 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/PositionalCommandParameter.cs b/src/System.Management.Automation/engine/PositionalCommandParameter.cs index 879b96c4649..1370d8c9a2f 100644 --- a/src/System.Management.Automation/engine/PositionalCommandParameter.cs +++ b/src/System.Management.Automation/engine/PositionalCommandParameter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/engine/PowerShellStreamType.cs b/src/System.Management.Automation/engine/PowerShellStreamType.cs new file mode 100644 index 00000000000..6afbb79be51 --- /dev/null +++ b/src/System.Management.Automation/engine/PowerShellStreamType.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace System.Management.Automation +{ + /// + /// Enumeration of the possible PowerShell stream types. + /// This enumeration is obsolete. + /// + /// + /// This enumeration is a public type formerly used in PowerShell Workflow, + /// but kept due to its generic name and public accessibility. + /// It is not used by any other PowerShell API, and is now obsolete + /// and should not be used if possible. + /// + [Obsolete("This enum type was used only in PowerShell Workflow and is now obsolete.", error: true)] + public enum PowerShellStreamType + { + /// + /// PSObject. + /// + Input = 0, + + /// + /// PSObject. + /// + Output = 1, + + /// + /// ErrorRecord. + /// + Error = 2, + + /// + /// WarningRecord. + /// + Warning = 3, + + /// + /// VerboseRecord. + /// + Verbose = 4, + + /// + /// DebugRecord. + /// + Debug = 5, + + /// + /// ProgressRecord. + /// + Progress = 6, + + /// + /// InformationRecord. + /// + Information = 7 + } +} diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 298bd0d1f1e..604ac3787ad 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell /// public static class ProcessCodeMethods { - const int InvalidProcessId = -1; + private const int InvalidProcessId = -1; internal static Process GetParent(this Process process) { @@ -69,7 +69,7 @@ internal static int GetParentPid(Process process) } [StructLayout(LayoutKind.Sequential)] - struct PROCESS_BASIC_INFORMATION + private struct PROCESS_BASIC_INFORMATION { public IntPtr ExitStatus; public IntPtr PebBaseAddress; @@ -80,7 +80,7 @@ struct PROCESS_BASIC_INFORMATION } [DllImport("ntdll.dll", SetLastError = true)] - static extern int NtQueryInformationProcess( + private static extern int NtQueryInformationProcess( IntPtr processHandle, int processInformationClass, out PROCESS_BASIC_INFORMATION processInformation, diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index 4483ed81f94..f040e24e416 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -43,17 +43,17 @@ class ProgressRecord { // negative Ids are reserved to indicate "no id" for parent Ids. - throw PSTraceSource.NewArgumentOutOfRangeException("activityId", activityId, ProgressRecordStrings.ArgMayNotBeNegative, "activityId"); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(activityId), activityId, ProgressRecordStrings.ArgMayNotBeNegative, "activityId"); } if (string.IsNullOrEmpty(activity)) { - throw PSTraceSource.NewArgumentException("activity", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "activity"); + throw PSTraceSource.NewArgumentException(nameof(activity), ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "activity"); } if (string.IsNullOrEmpty(statusDescription)) { - throw PSTraceSource.NewArgumentException("activity", ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "statusDescription"); + throw PSTraceSource.NewArgumentException(nameof(activity), ProgressRecordStrings.ArgMayNotBeNullOrEmpty, "statusDescription"); } this.id = activityId; @@ -373,12 +373,12 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD if (startTime > now) { - throw new ArgumentOutOfRangeException("startTime"); + throw new ArgumentOutOfRangeException(nameof(startTime)); } if (expectedDuration <= TimeSpan.Zero) { - throw new ArgumentOutOfRangeException("expectedDuration"); + throw new ArgumentOutOfRangeException(nameof(expectedDuration)); } /* @@ -474,7 +474,7 @@ internal static ProgressRecord FromPSObjectForRemoting(PSObject progressAsPSObje { if (progressAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("progressAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(progressAsPSObject)); } string activity = RemotingDecoder.GetPropertyValue(progressAsPSObject, RemoteDataNameStrings.ProgressRecord_Activity); diff --git a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs index 2e7a4cd4bc4..9c1f9379190 100644 --- a/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/PropertyCmdletProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -38,7 +38,7 @@ internal PropertyCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } _cmdlet = cmdlet; @@ -58,7 +58,7 @@ internal PropertyCmdletProviderIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/ProviderInterfaces.cs b/src/System.Management.Automation/engine/ProviderInterfaces.cs index da270626875..27e2680af5c 100644 --- a/src/System.Management.Automation/engine/ProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/ProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -40,7 +40,7 @@ internal CmdletProviderManagementIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/ProviderNames.cs b/src/System.Management.Automation/engine/ProviderNames.cs index c4915dd7773..0ae3e63edec 100644 --- a/src/System.Management.Automation/engine/ProviderNames.cs +++ b/src/System.Management.Automation/engine/ProviderNames.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 3ea9c5a58f2..1bb3d15baf3 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -354,7 +354,7 @@ public static string GetHelpComments(PSObject help) { if (help == null) { - throw new ArgumentNullException("help"); + throw new ArgumentNullException(nameof(help)); } bool isHelpObject = false; @@ -434,7 +434,7 @@ public static string GetHelpComments(PSObject help) foreach (PSObject remark in remarks) { string remarkText = GetProperty(remark, "text"); - exsb.Append(remarkText.ToString()); + exsb.Append(remarkText); } } diff --git a/src/System.Management.Automation/engine/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/PseudoParameterBinder.cs index 3fbe1c4f7a2..bddbe643f59 100644 --- a/src/System.Management.Automation/engine/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/PseudoParameterBinder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -124,7 +124,7 @@ internal override void BindParameter(string name, object value, CompiledCommandP { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } Target[name].Value = value; diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index d0dd98a32ae..78ef034cf5b 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -53,12 +53,12 @@ public RuntimeDefinedParameter(string name, Type parameterType, Collection public object Data { get; set; } - internal static RuntimeDefinedParameter[] EmptyParameterArray = new RuntimeDefinedParameter[0]; + internal static readonly RuntimeDefinedParameter[] EmptyParameterArray = new RuntimeDefinedParameter[0]; } } diff --git a/src/System.Management.Automation/engine/QuestionMarkVariable.cs b/src/System.Management.Automation/engine/QuestionMarkVariable.cs index f530bf533cc..af2436c2f2a 100644 --- a/src/System.Management.Automation/engine/QuestionMarkVariable.cs +++ b/src/System.Management.Automation/engine/QuestionMarkVariable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs index 5336b3ec57e..3e5dcab2502 100644 --- a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs +++ b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -189,9 +189,21 @@ static ReflectionParameterBinder() s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "ListAvailable"), (o, v) => ((GetModuleCommand)o).ListAvailable = (SwitchParameter)v); s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "FullyQualifiedName"), (o, v) => ((GetModuleCommand)o).FullyQualifiedName = (ModuleSpecification[])v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorAction"), (o, v) => ((CommonParameters)o).ErrorAction = (ActionPreference)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningAction"), (o, v) => ((CommonParameters)o).WarningAction = (ActionPreference)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationAction"), (o, v) => ((CommonParameters)o).InformationAction = (ActionPreference)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorAction"), + (o, v) => { + v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); + ((CommonParameters)o).ErrorAction = (ActionPreference)v; + }); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningAction"), + (o, v) => { + v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); + ((CommonParameters)o).WarningAction = (ActionPreference)v; + }); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationAction"), + (o, v) => { + v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); + ((CommonParameters)o).InformationAction = (ActionPreference)v; + }); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Verbose"), (o, v) => ((CommonParameters)o).Verbose = (SwitchParameter)v); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Debug"), (o, v) => ((CommonParameters)o).Debug = (SwitchParameter)v); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorVariable"), (o, v) => ((CommonParameters)o).ErrorVariable = (string)v); @@ -204,6 +216,7 @@ static ReflectionParameterBinder() private static readonly ConcurrentDictionary, Func> s_getterMethods = new ConcurrentDictionary, Func>(); + private static readonly ConcurrentDictionary, Action> s_setterMethods = new ConcurrentDictionary, Action>(); diff --git a/src/System.Management.Automation/engine/ScopedItemSearcher.cs b/src/System.Management.Automation/engine/ScopedItemSearcher.cs index 58a5a9cd58f..4d5f2f1107f 100644 --- a/src/System.Management.Automation/engine/ScopedItemSearcher.cs +++ b/src/System.Management.Automation/engine/ScopedItemSearcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -35,12 +35,12 @@ internal ScopedItemSearcher( { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } if (lookupPath == null) { - throw PSTraceSource.NewArgumentNullException("lookupPath"); + throw PSTraceSource.NewArgumentNullException(nameof(lookupPath)); } this.sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/ScriptCommand.cs b/src/System.Management.Automation/engine/ScriptCommand.cs index 50811477c5f..d64d6112171 100644 --- a/src/System.Management.Automation/engine/ScriptCommand.cs +++ b/src/System.Management.Automation/engine/ScriptCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index 5a5b2df239c..89e898a5532 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -66,6 +66,7 @@ protected ScriptCommandProcessorBase(IScriptCommandInfo commandInfo, ExecutionCo protected ScriptBlock _scriptBlock; private ScriptParameterBinderController _scriptParameterBinderController; + internal ScriptParameterBinderController ScriptParameterBinderController { get diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index d12230f1273..7a5112a341d 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -33,7 +33,7 @@ internal ScriptInfo(string name, ScriptBlock script, ExecutionContext context) { if (script == null) { - throw PSTraceSource.NewArgumentException("script"); + throw PSTraceSource.NewArgumentException(nameof(script)); } this.ScriptBlock = script; diff --git a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs index 591d306a638..826fff642c3 100644 --- a/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs +++ b/src/System.Management.Automation/engine/SecurityDescriptorCmdletProviderInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -36,7 +36,7 @@ internal SecurityDescriptorCmdletProviderIntrinsics(Cmdlet cmdlet) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } _cmdlet = cmdlet; @@ -54,7 +54,7 @@ internal SecurityDescriptorCmdletProviderIntrinsics(SessionStateInternal session { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index c03797ba2e0..3cb4c9e7a70 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; diff --git a/src/System.Management.Automation/engine/SerializationStrings.cs b/src/System.Management.Automation/engine/SerializationStrings.cs index 0bc8e998e40..c3a1c8a46dc 100644 --- a/src/System.Management.Automation/engine/SerializationStrings.cs +++ b/src/System.Management.Automation/engine/SerializationStrings.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index fbf4a774204..e11b018daf2 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -56,7 +56,7 @@ internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, Ex { if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } ExecutionContext = context; diff --git a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs index 48cd7eca09f..17ed891f862 100644 --- a/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateAliasAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -255,12 +255,12 @@ internal AliasInfo SetAliasValue(string aliasName, string value, bool force, Com { if (string.IsNullOrEmpty(aliasName)) { - throw PSTraceSource.NewArgumentException("aliasName"); + throw PSTraceSource.NewArgumentException(nameof(aliasName)); } if (string.IsNullOrEmpty(value)) { - throw PSTraceSource.NewArgumentException("value"); + throw PSTraceSource.NewArgumentException(nameof(value)); } AliasInfo info = _currentScope.SetAliasValue(aliasName, value, this.ExecutionContext, force, origin); @@ -332,12 +332,12 @@ internal AliasInfo SetAliasValue( { if (string.IsNullOrEmpty(aliasName)) { - throw PSTraceSource.NewArgumentException("aliasName"); + throw PSTraceSource.NewArgumentException(nameof(aliasName)); } if (string.IsNullOrEmpty(value)) { - throw PSTraceSource.NewArgumentException("value"); + throw PSTraceSource.NewArgumentException(nameof(value)); } AliasInfo info = _currentScope.SetAliasValue(aliasName, value, options, this.ExecutionContext, force, origin); @@ -405,7 +405,7 @@ internal AliasInfo SetAliasItem(AliasInfo alias, bool force, CommandOrigin origi { if (alias == null) { - throw PSTraceSource.NewArgumentNullException("alias"); + throw PSTraceSource.NewArgumentNullException(nameof(alias)); } AliasInfo info = _currentScope.SetAliasItem(alias, force, origin); @@ -452,7 +452,7 @@ internal AliasInfo SetAliasItemAtScope(AliasInfo alias, string scopeID, bool for { if (alias == null) { - throw PSTraceSource.NewArgumentNullException("alias"); + throw PSTraceSource.NewArgumentNullException(nameof(alias)); } // If the "private" scope was specified, make sure the options contain @@ -526,7 +526,7 @@ internal void RemoveAlias(string aliasName, bool force) { if (string.IsNullOrEmpty(aliasName)) { - throw PSTraceSource.NewArgumentException("aliasName"); + throw PSTraceSource.NewArgumentException(nameof(aliasName)); } // Use the scope enumerator to find an existing function diff --git a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs index 0b1e922b818..9e50b4e0a6a 100644 --- a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -238,7 +238,7 @@ internal void RemoveCmdlet(string name, int index, bool force, CommandOrigin ori { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } // Use the scope enumerator to find an existing function @@ -289,7 +289,7 @@ internal void RemoveCmdletEntry(string name, bool force) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } // Use the scope enumerator to find an existing function diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index aa32e151226..4016bffbaa5 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -60,7 +60,7 @@ internal bool ItemExists(string path, bool force, bool literalPath) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -108,7 +108,7 @@ internal bool ItemExists( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -128,7 +128,7 @@ internal bool ItemExists( foreach (string providerPath in providerPaths) { result = ItemExists(providerInstance, providerPath, context); - if (result == true) + if (result) { break; } @@ -252,7 +252,7 @@ internal object ItemExistsDynamicParameters(string path, CmdletProviderContext c { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -392,7 +392,7 @@ internal bool IsValidPath(string path) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -438,7 +438,7 @@ internal bool IsValidPath( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -562,7 +562,7 @@ internal bool IsItemContainer(string path) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -608,7 +608,7 @@ internal bool IsItemContainer( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -789,7 +789,7 @@ internal void RemoveItem(string[] paths, bool recurse, bool force, bool literalP { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -840,14 +840,14 @@ internal void RemoveItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -1240,7 +1240,7 @@ internal Collection GetChildItems(string[] paths, bool recurse, uint d { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1251,7 +1251,7 @@ internal Collection GetChildItems(string[] paths, bool recurse, uint d { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } GetChildItems(path, recurse, depth, context); @@ -1307,12 +1307,12 @@ internal void GetChildItems( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } ProviderInfo provider = null; @@ -2229,7 +2229,7 @@ internal Collection GetChildNames( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -2240,7 +2240,7 @@ internal Collection GetChildNames( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } GetChildNames(path, returnContainers, recurse, depth, context); @@ -2320,7 +2320,7 @@ internal void GetChildNames( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } // Construct the include filter @@ -2979,7 +2979,7 @@ internal Collection RenameItem(string path, string newName, bool force { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -3037,7 +3037,7 @@ internal void RenameItem( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -3062,7 +3062,7 @@ internal void RenameItem( { ArgumentException argException = PSTraceSource.NewArgumentException( - "path", + nameof(path), SessionStateStrings.RenameMultipleItemError); context.WriteError( @@ -3345,7 +3345,7 @@ internal Collection NewItem(string[] paths, string name, string type, { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -3409,7 +3409,7 @@ internal void NewItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) @@ -3417,7 +3417,7 @@ internal void NewItem( string resolvePath = null; if (path == null) { - PSTraceSource.NewArgumentNullException("paths"); + PSTraceSource.NewArgumentNullException(nameof(paths)); } else if (path.EndsWith((":" + Path.DirectorySeparatorChar), StringComparison.Ordinal) || path.EndsWith((":" + Path.AltDirectorySeparatorChar), StringComparison.Ordinal)) @@ -3819,7 +3819,7 @@ internal bool HasChildItems(string path, bool force, bool literalPath) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -3871,7 +3871,7 @@ internal bool HasChildItems( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -3889,7 +3889,7 @@ internal bool HasChildItems( foreach (string providerPath in providerPaths) { result = HasChildItems(providerInstance, providerPath, context); - if (result == true) + if (result) { break; } @@ -3924,12 +3924,12 @@ internal bool HasChildItems( if (string.IsNullOrEmpty(providerId)) { - throw PSTraceSource.NewArgumentException("providerId"); + throw PSTraceSource.NewArgumentException(nameof(providerId)); } if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -4097,7 +4097,7 @@ internal Collection CopyItem(string[] paths, { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (copyPath == null) @@ -4163,7 +4163,7 @@ internal void CopyItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (copyPath == null) @@ -4260,7 +4260,7 @@ internal void CopyItem( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths; @@ -4839,7 +4839,7 @@ private string ValidateRemotePathAndGetRoot(string path, Runspaces.PSSession ses if (sourceIsRemote) { - ps.AddParameter("sourceIsRemote", true); + ps.AddParameter(nameof(sourceIsRemote), true); } op = Microsoft.PowerShell.Commands.SafeInvokeCommand.Invoke(ps, null, context); diff --git a/src/System.Management.Automation/engine/SessionStateContent.cs b/src/System.Management.Automation/engine/SessionStateContent.cs index 5c4ae6e1c98..0f1cc74bc49 100644 --- a/src/System.Management.Automation/engine/SessionStateContent.cs +++ b/src/System.Management.Automation/engine/SessionStateContent.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -55,7 +55,7 @@ internal Collection GetContentReader(string[] paths, bool force, { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -107,7 +107,7 @@ internal Collection GetContentReader( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -119,7 +119,7 @@ internal Collection GetContentReader( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = @@ -396,7 +396,7 @@ internal Collection GetContentWriter(string[] paths, bool force, { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -448,7 +448,7 @@ internal Collection GetContentWriter( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -459,7 +459,7 @@ internal Collection GetContentWriter( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = @@ -738,7 +738,7 @@ internal void ClearContent(string[] paths, bool force, bool literalPath) { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -785,7 +785,7 @@ internal void ClearContent( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -795,7 +795,7 @@ internal void ClearContent( { if (path == null) { - PSTraceSource.NewArgumentNullException("paths"); + PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index 51714134f5d..7c2eeb447c8 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -65,7 +65,7 @@ internal PSDriveInfo NewDrive(PSDriveInfo drive, string scopeID) { if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } PSDriveInfo result = null; @@ -140,12 +140,12 @@ internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext { if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } if (!IsValidDriveName(drive.Name)) @@ -432,7 +432,7 @@ private PSDriveInfo GetDrive(string name, bool automount) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } PSDriveInfo result = null; @@ -473,13 +473,9 @@ private PSDriveInfo GetDrive(string name, bool automount) if (result == null && automount) { - // first try to automount as a file system drive - result = AutomountFileSystemDrive(name); - // if it didn't work, then try automounting as a BuiltIn drive (e.g. "Cert"/"Certificate"/"WSMan") - if (result == null) - { - result = AutomountBuiltInDrive(name); // internally this calls GetDrive(name, false) - } + // Attempt to automount as a file system drive + // or as a BuiltIn drive (e.g. "Cert"/"Certificate"/"WSMan") + result = AutomountFileSystemDrive(name) ?? AutomountBuiltInDrive(name); } if (result == null) @@ -528,7 +524,7 @@ internal PSDriveInfo GetDrive(string name, string scopeID) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } PSDriveInfo result = null; @@ -744,6 +740,9 @@ private PSDriveInfo AutomountFileSystemDrive(System.IO.DriveInfo systemDriveInfo /// /// Auto-mounts a built-in drive. /// + /// + /// Calls GetDrive(name, false) internally. + /// /// The name of the drive to load. /// internal PSDriveInfo AutomountBuiltInDrive(string name) @@ -994,7 +993,7 @@ internal void RemoveDrive(string driveName, bool force, string scopeID) { if (driveName == null) { - throw PSTraceSource.NewArgumentNullException("driveName"); + throw PSTraceSource.NewArgumentNullException(nameof(driveName)); } PSDriveInfo drive = GetDrive(driveName, scopeID); @@ -1037,7 +1036,7 @@ internal void RemoveDrive( { if (driveName == null) { - throw PSTraceSource.NewArgumentNullException("driveName"); + throw PSTraceSource.NewArgumentNullException(nameof(driveName)); } Dbg.Diagnostics.Assert( @@ -1079,7 +1078,7 @@ internal void RemoveDrive(PSDriveInfo drive, bool force, string scopeID) { if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1241,12 +1240,12 @@ private bool CanRemoveDrive(PSDriveInfo drive, CmdletProviderContext context) { if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } s_tracer.WriteLine("Drive name = {0}", drive.Name); diff --git a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs index 66c965dc404..575c3387d5e 100644 --- a/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateDynamicProperty.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -70,12 +70,12 @@ internal Collection NewProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (property == null) { - throw PSTraceSource.NewArgumentNullException("property"); + throw PSTraceSource.NewArgumentNullException(nameof(property)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -141,12 +141,12 @@ internal void NewProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (property == null) { - throw PSTraceSource.NewArgumentNullException("property"); + throw PSTraceSource.NewArgumentNullException(nameof(property)); } ProviderInfo provider = null; @@ -156,7 +156,7 @@ internal void NewProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = @@ -467,12 +467,12 @@ internal void RemoveProperty(string[] paths, string property, bool force, bool l { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (property == null) { - throw PSTraceSource.NewArgumentNullException("property"); + throw PSTraceSource.NewArgumentNullException(nameof(property)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -523,19 +523,19 @@ internal void RemoveProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (property == null) { - throw PSTraceSource.NewArgumentNullException("property"); + throw PSTraceSource.NewArgumentNullException(nameof(property)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -840,22 +840,22 @@ internal Collection CopyProperty( { if (sourcePaths == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } if (sourceProperty == null) { - throw PSTraceSource.NewArgumentNullException("sourceProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } if (destinationPath == null) { - throw PSTraceSource.NewArgumentNullException("destinationPath"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (destinationProperty == null) { - throw PSTraceSource.NewArgumentNullException("destinationProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -921,29 +921,29 @@ internal void CopyProperty( { if (sourcePaths == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } if (sourceProperty == null) { - throw PSTraceSource.NewArgumentNullException("sourceProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } if (destinationPath == null) { - throw PSTraceSource.NewArgumentNullException("destinationPath"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (destinationProperty == null) { - throw PSTraceSource.NewArgumentNullException("destinationProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } foreach (string sourcePath in sourcePaths) { if (sourcePath == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } ProviderInfo provider = null; @@ -1327,22 +1327,22 @@ internal Collection MoveProperty( { if (sourcePaths == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } if (sourceProperty == null) { - throw PSTraceSource.NewArgumentNullException("sourceProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } if (destinationPath == null) { - throw PSTraceSource.NewArgumentNullException("destinationPath"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (destinationProperty == null) { - throw PSTraceSource.NewArgumentNullException("destinationProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1411,22 +1411,22 @@ internal void MoveProperty( { if (sourcePaths == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } if (sourceProperty == null) { - throw PSTraceSource.NewArgumentNullException("sourceProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } if (destinationPath == null) { - throw PSTraceSource.NewArgumentNullException("destinationPath"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (destinationProperty == null) { - throw PSTraceSource.NewArgumentNullException("destinationProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } ProviderInfo provider = null; @@ -1453,7 +1453,7 @@ internal void MoveProperty( { ArgumentException argException = PSTraceSource.NewArgumentException( - "destinationPath", + nameof(destinationPath), SessionStateStrings.MovePropertyDestinationResolveToSingle); context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destinationProviderPaths)); @@ -1464,7 +1464,7 @@ internal void MoveProperty( { if (sourcePath == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } Collection providerPaths = @@ -1805,17 +1805,17 @@ internal Collection RenameProperty( { if (sourcePaths == null) { - throw PSTraceSource.NewArgumentNullException("sourcePaths"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePaths)); } if (sourceProperty == null) { - throw PSTraceSource.NewArgumentNullException("sourceProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } if (destinationProperty == null) { - throw PSTraceSource.NewArgumentNullException("destinationProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1874,24 +1874,24 @@ internal void RenameProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (sourceProperty == null) { - throw PSTraceSource.NewArgumentNullException("sourceProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(sourceProperty)); } if (destinationProperty == null) { - throw PSTraceSource.NewArgumentNullException("destinationProperty"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationProperty)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index 88ff5a5350f..42d3607cadb 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -39,7 +39,7 @@ internal void AddSessionStateEntry(SessionStateFunctionEntry entry) /// /// An IDictionary representing the visible functions. /// - internal IDictionary GetFunctionTable() + internal IDictionary GetFunctionTable() { SessionStateScopeEnumerator scopeEnumerator = new SessionStateScopeEnumerator(_currentScope); @@ -120,8 +120,8 @@ internal bool FunctionsExportedWithWildcard set { - Dbg.Assert((value == true), "This property should never be set/reset to false"); - if (value == true) + Dbg.Assert((value), "This property should never be set/reset to false"); + if (value) { _functionsExportedWithWildcard = value; } @@ -154,7 +154,7 @@ internal FunctionInfo GetFunction(string name, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } FunctionInfo result = null; @@ -269,12 +269,12 @@ internal FunctionInfo SetFunctionRaw( { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (function == null) { - throw PSTraceSource.NewArgumentNullException("function"); + throw PSTraceSource.NewArgumentNullException(nameof(function)); } string originalName = name; @@ -504,12 +504,12 @@ internal FunctionInfo SetFunction( { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (function == null) { - throw PSTraceSource.NewArgumentNullException("function"); + throw PSTraceSource.NewArgumentNullException(nameof(function)); } string originalName = name; @@ -583,12 +583,12 @@ internal FunctionInfo SetFunction( { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } if (function == null) { - throw PSTraceSource.NewArgumentNullException("function"); + throw PSTraceSource.NewArgumentNullException(nameof(function)); } string originalName = name; @@ -711,7 +711,7 @@ internal void RemoveFunction(string name, bool force, CommandOrigin origin) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } // Use the scope enumerator to find an existing function diff --git a/src/System.Management.Automation/engine/SessionStateItem.cs b/src/System.Management.Automation/engine/SessionStateItem.cs index 64b4d04b9b5..3d5262bf6c0 100644 --- a/src/System.Management.Automation/engine/SessionStateItem.cs +++ b/src/System.Management.Automation/engine/SessionStateItem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -56,7 +56,7 @@ internal Collection GetItem(string[] paths, bool force, bool literalPa { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -114,7 +114,7 @@ internal void GetItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -124,7 +124,7 @@ internal void GetItem( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = @@ -395,7 +395,7 @@ internal Collection SetItem(string[] paths, object value, bool force, { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -451,14 +451,14 @@ internal void SetItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -748,7 +748,7 @@ internal Collection ClearItem(string[] paths, bool force, bool literal { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -800,7 +800,7 @@ internal void ClearItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -810,7 +810,7 @@ internal void ClearItem( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = @@ -1079,7 +1079,7 @@ internal void InvokeDefaultAction(string[] paths, bool literalPath) { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1127,7 +1127,7 @@ internal void InvokeDefaultAction( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -1137,7 +1137,7 @@ internal void InvokeDefaultAction( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index 138f671ad6b..ca048aa0931 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -75,7 +75,7 @@ internal PathInfo GetNamespaceCurrentLocation(string namespaceID) { if (namespaceID == null) { - throw PSTraceSource.NewArgumentNullException("namespaceID"); + throw PSTraceSource.NewArgumentNullException(nameof(namespaceID)); } // If namespace ID is empty, we will use the current working drive @@ -236,7 +236,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } PathInfo current = CurrentLocation; @@ -519,7 +519,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l throw PSTraceSource.NewArgumentException( - "path", + nameof(path), SessionStateStrings.PathResolvedToMultiple, originalPath); } @@ -636,7 +636,7 @@ internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext con if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } PSDriveInfo drive = null; @@ -913,7 +913,7 @@ internal PathInfo PopLocation(string stackName) { throw PSTraceSource.NewArgumentException( - "stackName", + nameof(stackName), SessionStateStrings.StackNameResolvedToMultiple, stackName); } @@ -935,7 +935,7 @@ internal PathInfo PopLocation(string stackName) { throw PSTraceSource.NewArgumentException( - "stackName", + nameof(stackName), SessionStateStrings.StackNotFound, stackName); } @@ -1012,7 +1012,7 @@ internal PathInfoStack LocationStack(string stackName) } else { - throw PSTraceSource.NewArgumentException("stackName"); + throw PSTraceSource.NewArgumentException(nameof(stackName)); } } diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index 9ac1c715cf4..4afb9218dd7 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -48,7 +48,7 @@ internal string GetParentPath(string path, string root) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -125,7 +125,7 @@ internal string GetParentPath( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext getProviderPathContext = @@ -469,7 +469,7 @@ internal string NormalizeRelativePath(string path, string basePath) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -517,7 +517,7 @@ internal string NormalizeRelativePath( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext getProviderPathContext = @@ -546,7 +546,7 @@ internal string NormalizeRelativePath( // Since the provider didn't write an error, and we didn't get any // results ourselves, we need to write out our own error. - Exception e = PSTraceSource.NewArgumentException("path"); + Exception e = PSTraceSource.NewArgumentException(nameof(path)); context.WriteError(new ErrorRecord(e, "NormalizePathNullResult", ErrorCategory.InvalidArgument, path)); return null; } @@ -816,13 +816,13 @@ internal string MakePath( if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } if (parent == null && child == null) { - throw PSTraceSource.NewArgumentException("parent"); + throw PSTraceSource.NewArgumentException(nameof(parent)); } // Set the drive data for the context @@ -1046,7 +1046,7 @@ internal string GetChildName(string path) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1117,7 +1117,7 @@ internal string GetChildName( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } PSDriveInfo drive = null; @@ -1340,7 +1340,7 @@ internal Collection MoveItem(string[] paths, string destination, bool { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -1398,12 +1398,12 @@ internal void MoveItem( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (destination == null) { - throw PSTraceSource.NewArgumentNullException("destination"); + throw PSTraceSource.NewArgumentNullException(nameof(destination)); } ProviderInfo provider = null; @@ -1420,7 +1420,7 @@ internal void MoveItem( { ArgumentException argException = PSTraceSource.NewArgumentException( - "destination", + nameof(destination), SessionStateStrings.MoveItemOneDestination); context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, destination)); @@ -1431,7 +1431,7 @@ internal void MoveItem( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } Collection providerPaths = @@ -1496,7 +1496,7 @@ internal void MoveItem( { ArgumentException argException = PSTraceSource.NewArgumentException( - "destination", + nameof(destination), SessionStateStrings.MoveItemSourceAndDestinationNotSameProvider); context.WriteError(new ErrorRecord(argException, argException.GetType().FullName, ErrorCategory.InvalidArgument, providerPaths)); diff --git a/src/System.Management.Automation/engine/SessionStateProperty.cs b/src/System.Management.Automation/engine/SessionStateProperty.cs index 1456d427c65..d4568d2ebb3 100644 --- a/src/System.Management.Automation/engine/SessionStateProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateProperty.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -116,14 +116,14 @@ internal void GetProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -416,7 +416,7 @@ internal Collection SetProperty(string[] paths, PSObject property, boo { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (property == null) @@ -480,19 +480,19 @@ internal void SetProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (property == null) { - throw PSTraceSource.NewArgumentNullException("property"); + throw PSTraceSource.NewArgumentNullException(nameof(property)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; @@ -789,12 +789,12 @@ internal void ClearProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (propertyToClear == null) { - throw PSTraceSource.NewArgumentNullException("propertyToClear"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyToClear)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -845,19 +845,19 @@ internal void ClearProperty( { if (paths == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } if (propertyToClear == null) { - throw PSTraceSource.NewArgumentNullException("propertyToClear"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyToClear)); } foreach (string path in paths) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("paths"); + throw PSTraceSource.NewArgumentNullException(nameof(paths)); } ProviderInfo provider = null; diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index beebcc60c08..f1b637a1d84 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -254,7 +254,7 @@ internal Provider.CmdletProvider GetProviderInstance(string providerId) { if (providerId == null) { - throw PSTraceSource.NewArgumentNullException("providerId"); + throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } ProviderInfo provider = GetSingleProvider(providerId); @@ -278,7 +278,7 @@ internal Provider.CmdletProvider GetProviderInstance(ProviderInfo provider) { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } return provider.CreateInstance(); @@ -347,7 +347,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(string providerId) { if (providerId == null) { - throw PSTraceSource.NewArgumentNullException("providerId"); + throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } DriveCmdletProvider driveCmdletProvider = @@ -382,7 +382,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } DriveCmdletProvider driveCmdletProvider = @@ -417,7 +417,7 @@ private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider provi { if (providerInstance == null) { - throw PSTraceSource.NewArgumentNullException("providerInstance"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } DriveCmdletProvider driveCmdletProvider = @@ -455,7 +455,7 @@ internal ItemCmdletProvider GetItemProviderInstance(string providerId) { if (providerId == null) { - throw PSTraceSource.NewArgumentNullException("providerId"); + throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } ItemCmdletProvider itemCmdletProvider = @@ -490,7 +490,7 @@ internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } ItemCmdletProvider itemCmdletProvider = @@ -525,7 +525,7 @@ private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider provide { if (providerInstance == null) { - throw PSTraceSource.NewArgumentNullException("providerInstance"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } ItemCmdletProvider itemCmdletProvider = @@ -563,7 +563,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) { if (providerId == null) { - throw PSTraceSource.NewArgumentNullException("providerId"); + throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } ContainerCmdletProvider containerCmdletProvider = @@ -598,7 +598,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provi { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } ContainerCmdletProvider containerCmdletProvider = @@ -633,7 +633,7 @@ private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvid { if (providerInstance == null) { - throw PSTraceSource.NewArgumentNullException("providerInstance"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } ContainerCmdletProvider containerCmdletProvider = @@ -668,7 +668,7 @@ internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo pro { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } NavigationCmdletProvider navigationCmdletProvider = @@ -707,7 +707,7 @@ private static NavigationCmdletProvider GetNavigationProviderInstance(CmdletProv { if (providerInstance == null) { - throw PSTraceSource.NewArgumentNullException("providerInstance"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } NavigationCmdletProvider navigationCmdletProvider = @@ -742,7 +742,7 @@ internal bool IsProviderLoaded(string name) if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } // Get the provider from the providers container @@ -780,7 +780,7 @@ internal Collection GetProvider(string name) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } PSSnapinQualifiedName providerName = PSSnapinQualifiedName.GetInstance(name); @@ -987,7 +987,7 @@ internal void InitializeProvider( { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } if (context == null) @@ -1105,7 +1105,7 @@ internal ProviderInfo NewProvider(ProviderInfo provider) { if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } // Check to see if the provider already exists. @@ -1269,7 +1269,7 @@ internal ProviderInfo NewProvider(ProviderInfo provider) // An exception during initialization should remove the provider from // session state. - Providers.Remove(provider.Name.ToString()); + Providers.Remove(provider.Name); ProvidersCurrentWorkingDrive.Remove(provider); provider = null; } @@ -1394,12 +1394,12 @@ internal void RemoveProvider( { if (context == null) { - throw PSTraceSource.NewArgumentNullException("context"); + throw PSTraceSource.NewArgumentNullException(nameof(context)); } if (string.IsNullOrEmpty(providerName)) { - throw PSTraceSource.NewArgumentException("providerName"); + throw PSTraceSource.NewArgumentException(nameof(providerName)); } bool errors = false; diff --git a/src/System.Management.Automation/engine/SessionStatePublic.cs b/src/System.Management.Automation/engine/SessionStatePublic.cs index 7c5b41b7e74..0dca57054db 100644 --- a/src/System.Management.Automation/engine/SessionStatePublic.cs +++ b/src/System.Management.Automation/engine/SessionStatePublic.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -28,7 +28,7 @@ internal SessionState(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentNullException("sessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(sessionState)); } _sessionState = sessionState; @@ -273,7 +273,7 @@ public static bool IsVisible(CommandOrigin origin, PSVariable variable) return true; if (variable == null) { - throw PSTraceSource.NewArgumentNullException("variable"); + throw PSTraceSource.NewArgumentNullException(nameof(variable)); } return (variable.Visibility == SessionStateEntryVisibility.Public); @@ -290,7 +290,7 @@ public static bool IsVisible(CommandOrigin origin, CommandInfo commandInfo) return true; if (commandInfo == null) { - throw PSTraceSource.NewArgumentNullException("commandInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } return (commandInfo.Visibility == SessionStateEntryVisibility.Public); diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index a0298746412..434d1e0d929 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -120,7 +120,7 @@ internal void NewDrive(PSDriveInfo newDrive) { if (newDrive == null) { - throw PSTraceSource.NewArgumentNullException("newDrive"); + throw PSTraceSource.NewArgumentNullException(nameof(newDrive)); } // Ensure that multiple threads do not try to modify the @@ -171,7 +171,7 @@ internal void RemoveDrive(PSDriveInfo drive) { if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } if (_drives == null) @@ -222,7 +222,7 @@ internal PSDriveInfo GetDrive(string name) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } PSDriveInfo result = null; @@ -1711,6 +1711,7 @@ private Dictionary GetAutomountedDrives() private Dictionary _automountedDrives; private Dictionary _variables; + private Dictionary GetPrivateVariables() { if (_variables == null) diff --git a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs index f80bb29e470..9dbcfb9c519 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeAPIs.cs @@ -1,7 +1,6 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. - using Dbg = System.Management.Automation; #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings diff --git a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs index 64ac5b119cc..c3b643e4f31 100644 --- a/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs +++ b/src/System.Management.Automation/engine/SessionStateScopeEnumerator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs index fef7c7eba06..73cf89cebdf 100644 --- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs +++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -32,7 +32,7 @@ internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance( { if (providerInstance == null) { - throw PSTraceSource.NewArgumentNullException("providerInstance"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } ISecurityDescriptorCmdletProvider permissionCmdletProvider = @@ -69,7 +69,7 @@ internal Collection GetSecurityDescriptor(string path, { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -110,7 +110,7 @@ internal void GetSecurityDescriptor( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -200,12 +200,12 @@ internal Collection SetSecurityDescriptor(string path, ObjectSecurity { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (securityDescriptor == null) { - throw PSTraceSource.NewArgumentNullException("securityDescriptor"); + throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); @@ -247,12 +247,12 @@ internal void SetSecurityDescriptor( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (securityDescriptor == null) { - throw PSTraceSource.NewArgumentNullException("securityDescriptor"); + throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } ProviderInfo provider = null; @@ -394,7 +394,7 @@ internal ObjectSecurity NewSecurityDescriptorFromPath( if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } ProviderInfo provider = null; @@ -419,7 +419,7 @@ internal ObjectSecurity NewSecurityDescriptorFromPath( } else { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } return sd; @@ -533,12 +533,12 @@ internal ObjectSecurity NewSecurityDescriptorOfType( if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } if (providerInstance == null) { - throw PSTraceSource.NewArgumentNullException("providerInstance"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } // This just verifies that the provider supports the interface. diff --git a/src/System.Management.Automation/engine/SessionStateStrings.cs b/src/System.Management.Automation/engine/SessionStateStrings.cs index 741ab5f47cb..ac5ced27170 100644 --- a/src/System.Management.Automation/engine/SessionStateStrings.cs +++ b/src/System.Management.Automation/engine/SessionStateStrings.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index e01ed19cf7f..7c684abd1c3 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -153,7 +153,7 @@ internal static bool CollectionContainsValue(IEnumerable collection, object valu { if (collection == null) { - throw new ArgumentNullException("collection"); + throw new ArgumentNullException(nameof(collection)); } bool result = false; diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index fc69216b677..9b4028314b8 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -36,7 +36,7 @@ internal void AddSessionStateEntry(SessionStateVariableEntry entry) /// /// Get a variable out of session state. This interface supports - /// the scope specifiers like "global:foobar" + /// the scope specifiers like "global:example" /// /// /// name of variable to look up @@ -54,7 +54,7 @@ internal PSVariable GetVariable(string name, CommandOrigin origin) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } VariablePath variablePath = new VariablePath(name, VariablePathFlags.Variable | VariablePathFlags.Unqualified); @@ -67,7 +67,7 @@ internal PSVariable GetVariable(string name, CommandOrigin origin) /// /// Get a variable out of session state. This interface supports - /// the scope specifiers like "global:foobar" + /// the scope specifiers like "global:example" /// /// /// name of variable to look up @@ -86,7 +86,7 @@ internal PSVariable GetVariable(string name) /// /// Get a variable out of session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "env:PATH" or "global:foobar" + /// "env:PATH" or "global:example" /// /// /// name of variable to look up @@ -114,7 +114,7 @@ internal object GetVariableValue(string name) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } VariablePath variablePath = new VariablePath(name); @@ -129,7 +129,7 @@ internal object GetVariableValue(string name) /// /// Get a variable out of session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "env:PATH" or "global:foobar" + /// "env:PATH" or "global:example" /// /// /// name of variable to look up @@ -287,7 +287,7 @@ internal object GetVariableValueFromProvider( if (variablePath == null) { - throw PSTraceSource.NewArgumentNullException("variablePath"); + throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } Dbg.Diagnostics.Assert( @@ -542,7 +542,7 @@ internal PSVariable GetVariableItem( if (variablePath == null) { - throw PSTraceSource.NewArgumentNullException("variablePath"); + throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } Dbg.Diagnostics.Assert(variablePath.IsVariable, "Can't get variable w/ non-variable path"); @@ -595,7 +595,7 @@ internal PSVariable GetVariableItem( /// /// Get a variable out of session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "env:PATH" or "global:foobar" + /// "env:PATH" or "global:example" /// /// /// name of variable to look up @@ -621,7 +621,7 @@ internal PSVariable GetVariableAtScope(string name, string scopeID) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } VariablePath variablePath = new VariablePath(name); @@ -646,7 +646,7 @@ internal PSVariable GetVariableAtScope(string name, string scopeID) /// /// Get a variable out of session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "env:PATH" or "global:foobar" + /// "env:PATH" or "global:example" /// /// /// name of variable to look up @@ -685,7 +685,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } VariablePath variablePath = new VariablePath(name); @@ -922,7 +922,7 @@ internal object GetAutomaticVariableValue(AutomaticVariable variable) /// /// Set a variable in session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "$env:PATH = 'c:\windows'" or "$global:foobar = 13" + /// "$env:PATH = 'c:\windows'" or "$global:example = 13" /// /// /// The name of the item to set. @@ -956,7 +956,7 @@ internal void SetVariableValue(string name, object newValue, CommandOrigin origi { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } VariablePath variablePath = new VariablePath(name); @@ -967,7 +967,7 @@ internal void SetVariableValue(string name, object newValue, CommandOrigin origi /// /// Set a variable in session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "$env:PATH = 'c:\windows'" or "$global:foobar = 13" + /// "$env:PATH = 'c:\windows'" or "$global:example = 13" /// /// BUGBUG: this overload exists because a lot of tests in the /// testsuite use it. Those tests should eventually be fixed and this overload @@ -1005,7 +1005,7 @@ internal void SetVariableValue(string name, object newValue) /// /// Set a variable in session state. This interface supports - /// the scope specifiers like "$global:foobar = 13" + /// the scope specifiers like "$global:example = 13" /// /// /// The variable to be set. @@ -1030,7 +1030,7 @@ internal object SetVariable(PSVariable variable, bool force, CommandOrigin origi { if (variable == null || string.IsNullOrEmpty(variable.Name)) { - throw PSTraceSource.NewArgumentException("variable"); + throw PSTraceSource.NewArgumentException(nameof(variable)); } VariablePath variablePath = new VariablePath(variable.Name, VariablePathFlags.Variable | VariablePathFlags.Unqualified); @@ -1138,7 +1138,7 @@ internal object SetVariable( object result = null; if (variablePath == null) { - throw PSTraceSource.NewArgumentNullException("variablePath"); + throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } CmdletProviderContext context = null; @@ -1405,7 +1405,7 @@ internal object SetVariableAtScope(PSVariable variable, string scopeID, bool for { if (variable == null || string.IsNullOrEmpty(variable.Name)) { - throw PSTraceSource.NewArgumentException("variable"); + throw PSTraceSource.NewArgumentException(nameof(variable)); } SessionStateScope lookupScope = GetScopeByID(scopeID); @@ -1441,7 +1441,7 @@ internal object NewVariable(PSVariable variable, bool force) { if (variable == null || string.IsNullOrEmpty(variable.Name)) { - throw PSTraceSource.NewArgumentException("variable"); + throw PSTraceSource.NewArgumentException(nameof(variable)); } return @@ -1485,7 +1485,7 @@ internal object NewVariableAtScope(PSVariable variable, string scopeID, bool for { if (variable == null || string.IsNullOrEmpty(variable.Name)) { - throw PSTraceSource.NewArgumentException("variable"); + throw PSTraceSource.NewArgumentException(nameof(variable)); } // The lookup scope from above is ignored and the scope is retrieved by @@ -1564,7 +1564,7 @@ internal void RemoveVariable(string name, bool force) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } VariablePath variablePath = new VariablePath(name); @@ -1623,7 +1623,7 @@ internal void RemoveVariable(PSVariable variable, bool force) { if (variable == null) { - throw PSTraceSource.NewArgumentNullException("variable"); + throw PSTraceSource.NewArgumentNullException(nameof(variable)); } VariablePath variablePath = new VariablePath(variable.Name); @@ -1639,7 +1639,7 @@ internal void RemoveVariable(PSVariable variable, bool force) /// /// Remove a variable from session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "env:PATH" or "global:foobar" + /// "env:PATH" or "global:example" /// /// /// name of variable to remove @@ -1669,7 +1669,7 @@ internal void RemoveVariableAtScope(string name, string scopeID) /// /// Remove a variable from session state. This interface supports /// the "namespace:name" syntax so you can do things like - /// "env:PATH" or "global:foobar" + /// "env:PATH" or "global:example" /// /// /// name of variable to remove @@ -1698,7 +1698,7 @@ internal void RemoveVariableAtScope(string name, string scopeID, bool force) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } VariablePath variablePath = new VariablePath(name); @@ -1780,7 +1780,7 @@ internal void RemoveVariableAtScope(PSVariable variable, string scopeID, bool fo { if (variable == null) { - throw PSTraceSource.NewArgumentNullException("variable"); + throw PSTraceSource.NewArgumentNullException(nameof(variable)); } VariablePath variablePath = new VariablePath(variable.Name); diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 5a92077e4f9..4be5a96f52b 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -159,7 +159,7 @@ public PSVariable( { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } Name = name; @@ -688,6 +688,7 @@ internal virtual void SetValueRaw(object newValue, bool preserveValueTypeSemanti private readonly CallSite> _copyMutableValueSite = CallSite>.Create(PSVariableAssignmentBinder.Get()); + internal object CopyMutableValues(object o) { // The variable assignment binder copies mutable values and returns other values as is. diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index b867dfedc6d..aa241b6c942 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -21,190 +21,247 @@ namespace System.Management.Automation internal static class SpecialVariables { internal const string HistorySize = "MaximumHistoryCount"; + internal static readonly VariablePath HistorySizeVarPath = new VariablePath(HistorySize); internal const string MyInvocation = "MyInvocation"; + internal static readonly VariablePath MyInvocationVarPath = new VariablePath(MyInvocation); internal const string OFS = "OFS"; + internal static readonly VariablePath OFSVarPath = new VariablePath(OFS); internal const string OutputEncoding = "OutputEncoding"; + internal static readonly VariablePath OutputEncodingVarPath = new VariablePath(OutputEncoding); internal const string VerboseHelpErrors = "VerboseHelpErrors"; + internal static readonly VariablePath VerboseHelpErrorsVarPath = new VariablePath(VerboseHelpErrors); #region Logging Variables internal const string LogEngineHealthEvent = "LogEngineHealthEvent"; + internal static readonly VariablePath LogEngineHealthEventVarPath = new VariablePath(LogEngineHealthEvent); internal const string LogEngineLifecycleEvent = "LogEngineLifecycleEvent"; + internal static readonly VariablePath LogEngineLifecycleEventVarPath = new VariablePath(LogEngineLifecycleEvent); internal const string LogCommandHealthEvent = "LogCommandHealthEvent"; + internal static readonly VariablePath LogCommandHealthEventVarPath = new VariablePath(LogCommandHealthEvent); internal const string LogCommandLifecycleEvent = "LogCommandLifecycleEvent"; + internal static readonly VariablePath LogCommandLifecycleEventVarPath = new VariablePath(LogCommandLifecycleEvent); internal const string LogProviderHealthEvent = "LogProviderHealthEvent"; + internal static readonly VariablePath LogProviderHealthEventVarPath = new VariablePath(LogProviderHealthEvent); internal const string LogProviderLifecycleEvent = "LogProviderLifecycleEvent"; + internal static readonly VariablePath LogProviderLifecycleEventVarPath = new VariablePath(LogProviderLifecycleEvent); internal const string LogSettingsEvent = "LogSettingsEvent"; + internal static readonly VariablePath LogSettingsEventVarPath = new VariablePath(LogSettingsEvent); internal const string PSLogUserData = "PSLogUserData"; + internal static readonly VariablePath PSLogUserDataPath = new VariablePath(PSLogUserData); #endregion Logging Variables internal const string NestedPromptLevel = "NestedPromptLevel"; + internal static readonly VariablePath NestedPromptCounterVarPath = new VariablePath("global:" + NestedPromptLevel); internal const string CurrentlyExecutingCommand = "CurrentlyExecutingCommand"; + internal static readonly VariablePath CurrentlyExecutingCommandVarPath = new VariablePath(CurrentlyExecutingCommand); internal const string PSBoundParameters = "PSBoundParameters"; + internal static readonly VariablePath PSBoundParametersVarPath = new VariablePath(PSBoundParameters); internal const string Matches = "Matches"; + internal static readonly VariablePath MatchesVarPath = new VariablePath(Matches); internal const string LastExitCode = "LASTEXITCODE"; + internal static readonly VariablePath LastExitCodeVarPath = new VariablePath("global:" + LastExitCode); internal const string PSDebugContext = "PSDebugContext"; + internal static readonly VariablePath PSDebugContextVarPath = new VariablePath(PSDebugContext); internal const string StackTrace = "StackTrace"; + internal static readonly VariablePath StackTraceVarPath = new VariablePath("global:" + StackTrace); internal const string FirstToken = "^"; + internal static readonly VariablePath FirstTokenVarPath = new VariablePath("global:" + FirstToken); internal const string LastToken = "$"; + internal static readonly VariablePath LastTokenVarPath = new VariablePath("global:" + LastToken); internal static bool IsUnderbar(string name) { return name.Length == 1 && name[0] == '_'; } internal const string PSItem = "PSItem"; // simple alias for $_ internal const string Underbar = "_"; + internal static readonly VariablePath UnderbarVarPath = new VariablePath(Underbar); internal const string Question = "?"; + internal static readonly VariablePath QuestionVarPath = new VariablePath(Question); internal const string Args = "args"; + internal static readonly VariablePath ArgsVarPath = new VariablePath("local:" + Args); internal const string This = "this"; + internal static readonly VariablePath ThisVarPath = new VariablePath("this"); internal const string Input = "input"; + internal static readonly VariablePath InputVarPath = new VariablePath("local:" + Input); internal const string PSCmdlet = "PSCmdlet"; + internal static readonly VariablePath PSCmdletVarPath = new VariablePath("PSCmdlet"); internal const string Error = "error"; + internal static readonly VariablePath ErrorVarPath = new VariablePath("global:" + Error); internal const string EventError = "error"; + internal static readonly VariablePath EventErrorVarPath = new VariablePath("script:" + EventError); #if !UNIX internal const string PathExt = "env:PATHEXT"; + internal static readonly VariablePath PathExtVarPath = new VariablePath(PathExt); #endif internal const string PSEmailServer = "PSEmailServer"; + internal static readonly VariablePath PSEmailServerVarPath = new VariablePath(PSEmailServer); internal const string PSDefaultParameterValues = "PSDefaultParameterValues"; + internal static readonly VariablePath PSDefaultParameterValuesVarPath = new VariablePath(PSDefaultParameterValues); internal const string PSScriptRoot = "PSScriptRoot"; + internal static readonly VariablePath PSScriptRootVarPath = new VariablePath(PSScriptRoot); internal const string PSCommandPath = "PSCommandPath"; + internal static readonly VariablePath PSCommandPathVarPath = new VariablePath(PSCommandPath); internal const string PSSenderInfo = "PSSenderInfo"; + internal static readonly VariablePath PSSenderInfoVarPath = new VariablePath(PSSenderInfo); internal const string @foreach = "foreach"; + internal static readonly VariablePath foreachVarPath = new VariablePath("local:" + @foreach); internal const string @switch = "switch"; + internal static readonly VariablePath switchVarPath = new VariablePath("local:" + @switch); internal const string pwd = "PWD"; - internal static VariablePath PWDVarPath = new VariablePath("global:" + pwd); + + internal static readonly VariablePath PWDVarPath = new VariablePath("global:" + pwd); internal const string Null = "null"; - internal static VariablePath NullVarPath = new VariablePath("null"); + + internal static readonly VariablePath NullVarPath = new VariablePath("null"); internal const string True = "true"; - internal static VariablePath TrueVarPath = new VariablePath("true"); + + internal static readonly VariablePath TrueVarPath = new VariablePath("true"); internal const string False = "false"; - internal static VariablePath FalseVarPath = new VariablePath("false"); + + internal static readonly VariablePath FalseVarPath = new VariablePath("false"); internal const string PSModuleAutoLoading = "PSModuleAutoLoadingPreference"; - internal static VariablePath PSModuleAutoLoadingPreferenceVarPath = new VariablePath("global:" + PSModuleAutoLoading); + + internal static readonly VariablePath PSModuleAutoLoadingPreferenceVarPath = new VariablePath("global:" + PSModuleAutoLoading); #region Platform Variables internal const string IsLinux = "IsLinux"; - internal static VariablePath IsLinuxPath = new VariablePath("IsLinux"); + + internal static readonly VariablePath IsLinuxPath = new VariablePath("IsLinux"); internal const string IsMacOS = "IsMacOS"; - internal static VariablePath IsMacOSPath = new VariablePath("IsMacOS"); + + internal static readonly VariablePath IsMacOSPath = new VariablePath("IsMacOS"); internal const string IsWindows = "IsWindows"; - internal static VariablePath IsWindowsPath = new VariablePath("IsWindows"); + + internal static readonly VariablePath IsWindowsPath = new VariablePath("IsWindows"); internal const string IsCoreCLR = "IsCoreCLR"; - internal static VariablePath IsCoreCLRPath = new VariablePath("IsCoreCLR"); + + internal static readonly VariablePath IsCoreCLRPath = new VariablePath("IsCoreCLR"); #endregion #region Preference Variables internal const string DebugPreference = "DebugPreference"; + internal static readonly VariablePath DebugPreferenceVarPath = new VariablePath(DebugPreference); internal const string ErrorActionPreference = "ErrorActionPreference"; + internal static readonly VariablePath ErrorActionPreferenceVarPath = new VariablePath(ErrorActionPreference); internal const string ProgressPreference = "ProgressPreference"; + internal static readonly VariablePath ProgressPreferenceVarPath = new VariablePath(ProgressPreference); internal const string VerbosePreference = "VerbosePreference"; + internal static readonly VariablePath VerbosePreferenceVarPath = new VariablePath(VerbosePreference); internal const string WarningPreference = "WarningPreference"; + internal static readonly VariablePath WarningPreferenceVarPath = new VariablePath(WarningPreference); internal const string WhatIfPreference = "WhatIfPreference"; + internal static readonly VariablePath WhatIfPreferenceVarPath = new VariablePath(WhatIfPreference); internal const string ConfirmPreference = "ConfirmPreference"; + internal static readonly VariablePath ConfirmPreferenceVarPath = new VariablePath(ConfirmPreference); internal const string InformationPreference = "InformationPreference"; + internal static readonly VariablePath InformationPreferenceVarPath = new VariablePath(InformationPreference); #endregion Preference Variables internal const string ErrorView = "ErrorView"; + internal static readonly VariablePath ErrorViewVarPath = new VariablePath(ErrorView); /// /// Shell environment variable. /// internal const string PSSessionConfigurationName = "PSSessionConfigurationName"; + internal static readonly VariablePath PSSessionConfigurationNameVarPath = new VariablePath("global:" + PSSessionConfigurationName); /// @@ -212,6 +269,7 @@ internal static class SpecialVariables /// application name for the connection uri. /// internal const string PSSessionApplicationName = "PSSessionApplicationName"; + internal static readonly VariablePath PSSessionApplicationNameVarPath = new VariablePath("global:" + PSSessionApplicationName); #region AllScope variables created in every session diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index 8c2d4855469..9840aaa0555 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -298,7 +298,7 @@ public virtual Collection GetTypeNameHierarchy(object baseObject) { if (baseObject == null) { - throw new ArgumentNullException("baseObject"); + throw new ArgumentNullException(nameof(baseObject)); } Collection types = new Collection(); diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs index 517a03a3600..948cf1d9d81 100644 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ b/src/System.Management.Automation/engine/TransactedString.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs index 84606789b87..bf86d90e812 100644 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ b/src/System.Management.Automation/engine/TransactionManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 6b1237ab67b..192042a3def 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -51,7 +51,7 @@ internal ParameterSetMetadata(ParameterSetMetadata other) { if (other == null) { - throw PSTraceSource.NewArgumentNullException("other"); + throw PSTraceSource.NewArgumentNullException(nameof(other)); } _helpMessage = other._helpMessage; @@ -411,7 +411,7 @@ public ParameterMetadata(string name, Type parameterType) { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } _name = name; @@ -431,7 +431,7 @@ public ParameterMetadata(ParameterMetadata other) { if (other == null) { - throw PSTraceSource.NewArgumentNullException("other"); + throw PSTraceSource.NewArgumentNullException(nameof(other)); } _isDynamic = other._isDynamic; @@ -625,7 +625,7 @@ public static Dictionary GetParameterMetadata(Type ty { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } CommandMetadata cmdMetaData = new CommandMetadata(type); @@ -1165,7 +1165,7 @@ internal static InternalParameterMetadata Get(Type type, ExecutionContext contex { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } InternalParameterMetadata result; @@ -1208,7 +1208,7 @@ internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefi { if (runtimeDefinedParameters == null) { - throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameters"); + throw PSTraceSource.NewArgumentNullException(nameof(runtimeDefinedParameters)); } ConstructCompiledParametersUsingRuntimeDefinedParameters(runtimeDefinedParameters, processingDynamicParameters, checkNames); @@ -1236,7 +1236,7 @@ internal InternalParameterMetadata(Type type, bool processingDynamicParameters) { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } _type = type; diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index a0f62885d50..2b0c0eb2ed0 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -1606,7 +1606,7 @@ protected override void SetItem(int index, string item) { if (string.IsNullOrEmpty(item)) { - throw PSTraceSource.NewArgumentException("item"); + throw PSTraceSource.NewArgumentException(nameof(item)); } base.SetItem(index, item); @@ -1623,7 +1623,7 @@ protected override void InsertItem(int index, string item) { if (string.IsNullOrEmpty(item)) { - throw PSTraceSource.NewArgumentException("item"); + throw PSTraceSource.NewArgumentException(nameof(item)); } base.InsertItem(index, item); @@ -1672,7 +1672,7 @@ public ConsolidatedString(IEnumerable strings) string str = this[i]; if (string.IsNullOrEmpty(str)) { - throw PSTraceSource.NewArgumentException("strings"); + throw PSTraceSource.NewArgumentException(nameof(strings)); } } @@ -1681,7 +1681,7 @@ public ConsolidatedString(IEnumerable strings) internal static readonly ConsolidatedString Empty = new ConsolidatedString(Array.Empty()); - internal static IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); + internal static readonly IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); private class ConsolidatedStringEqualityComparer : IEqualityComparer { @@ -1816,7 +1816,7 @@ protected TypeTableLoadException(SerializationInfo info, StreamingContext contex { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } int errorCount = info.GetInt32("ErrorCount"); @@ -1843,7 +1843,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -1912,7 +1912,7 @@ private TypeData() public TypeData(string typeName) : this() { if (string.IsNullOrWhiteSpace(typeName)) - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); this.TypeName = typeName; } @@ -1930,7 +1930,7 @@ public TypeData(Type type) : this() { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } this.TypeName = type.FullName; @@ -2367,7 +2367,7 @@ internal TypeMemberData(string name) { if (string.IsNullOrWhiteSpace(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } Name = name; @@ -2716,7 +2716,7 @@ public PropertySetData(IEnumerable referencedProperties) { if (referencedProperties == null) { - throw PSTraceSource.NewArgumentNullException("referencedProperties"); + throw PSTraceSource.NewArgumentNullException(nameof(referencedProperties)); } ReferencedProperties = new Collection(new List(referencedProperties)); @@ -3147,7 +3147,7 @@ private static bool CheckStandardMembers(ConcurrentBag errors, string ty TypesXmlStrings.MemberMustBePresent, PropertySerializationSet, SerializationMethodNode, - SerializationMethod.SpecificProperties.ToString(), + nameof(SerializationMethod.SpecificProperties), InheritPropertySerializationSet, "false"); serializationSettingsOk = false; @@ -3922,7 +3922,7 @@ internal TypeTable(IEnumerable typeFiles, AuthorizationManager authoriza { if (typeFiles == null) { - throw PSTraceSource.NewArgumentNullException("typeFiles"); + throw PSTraceSource.NewArgumentNullException(nameof(typeFiles)); } ConcurrentBag errors = new ConcurrentBag(); @@ -4668,7 +4668,7 @@ private void UpdateWithModuleContents( public void AddType(TypeData typeData) { if (typeData == null) - throw PSTraceSource.NewArgumentNullException("typeData"); + throw PSTraceSource.NewArgumentNullException(nameof(typeData)); Dbg.Assert(isShared, "This method should only be called by the developer user. It should not be used internally."); @@ -4695,7 +4695,7 @@ public void RemoveType(string typeName) { if (string.IsNullOrEmpty(typeName)) { - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } Dbg.Assert(isShared, "This method should only be called by the developer user. It should not be used internally."); @@ -4741,12 +4741,12 @@ internal void Update( { if (filePath == null) { - throw new ArgumentNullException("filePath"); + throw new ArgumentNullException(nameof(filePath)); } if (errors == null) { - throw new ArgumentNullException("errors"); + throw new ArgumentNullException(nameof(errors)); } if (isShared) @@ -4818,9 +4818,9 @@ internal void Update( bool isRemove) { if (type == null) - throw new ArgumentNullException("type"); + throw new ArgumentNullException(nameof(type)); if (errors == null) - throw new ArgumentNullException("errors"); + throw new ArgumentNullException(nameof(errors)); if (isShared) { diff --git a/src/System.Management.Automation/engine/TypeTable_GetEvent_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_GetEvent_Types_Ps1Xml.cs index 35e7e77c4fe..a306c9cd9c8 100644 --- a/src/System.Management.Automation/engine/TypeTable_GetEvent_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_GetEvent_Types_Ps1Xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; diff --git a/src/System.Management.Automation/engine/TypeTable_TypesV3_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_TypesV3_Ps1Xml.cs index f95d3e04035..63c2ea1918d 100644 --- a/src/System.Management.Automation/engine/TypeTable_TypesV3_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_TypesV3_Ps1Xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index 15e940d4302..aad2f70246e 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -12,6 +12,7 @@ namespace System.Management.Automation.Runspaces public sealed partial class TypeTable { private const int ValueFactoryCacheCount = 6; + private static readonly Func>[] s_valueFactoryCache; private static Func> GetValueFactoryBasedOnInitCapacity(int capacity) @@ -37,7 +38,6 @@ private static Func> GetVal return s_valueFactoryCache[cacheIndex]; - // Local helper function to avoid creating an instance of the generated delegate helper class // every time 'GetValueFactoryBasedOnInitCapacity' is invoked. static Func> CreateValueFactory(int capacity) @@ -1138,6 +1138,24 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) typeMembers, isOverride: false); + newMembers.Add(@"CommandLine"); + AddMember( + errors, + typeName, + new PSScriptProperty( + @"CommandLine", + GetScriptBlock(@" + if ($IsWindows) { + (Get-CimInstance Win32_Process -Filter ""ProcessId = $($this.Id)"").CommandLine + } elseif ($IsLinux) { + Get-Content -LiteralPath ""/proc/$($this.Id)/cmdline"" + } + "), + setterScript: null, + shouldCloneOnAccess: true), + typeMembers, + isOverride: false); + newMembers.Add(@"Parent"); AddMember( errors, diff --git a/src/System.Management.Automation/engine/UserFeedbackParameters.cs b/src/System.Management.Automation/engine/UserFeedbackParameters.cs index 27c5a46a4f8..feb1464d922 100644 --- a/src/System.Management.Automation/engine/UserFeedbackParameters.cs +++ b/src/System.Management.Automation/engine/UserFeedbackParameters.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; @@ -18,7 +18,7 @@ internal PagingParameters(MshCommandRuntime commandRuntime) { if (commandRuntime == null) { - throw PSTraceSource.NewArgumentNullException("commandRuntime"); + throw PSTraceSource.NewArgumentNullException(nameof(commandRuntime)); } commandRuntime.PagingParameters = this; @@ -116,7 +116,7 @@ internal ShouldProcessParameters(MshCommandRuntime commandRuntime) { if (commandRuntime == null) { - throw PSTraceSource.NewArgumentNullException("commandRuntime"); + throw PSTraceSource.NewArgumentNullException(nameof(commandRuntime)); } _commandRuntime = commandRuntime; diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 41a3e4573e1..12374148fa7 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -14,6 +14,7 @@ using System.Management.Automation.Configuration; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; using System.Management.Automation.Security; using System.Numerics; @@ -301,7 +302,7 @@ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int /// /// Allowed PowerShell Editions. /// - internal static string[] AllowedEditionValues = { "Desktop", "Core" }; + internal static readonly string[] AllowedEditionValues = { "Desktop", "Core" }; /// /// Helper fn to check byte[] arg for null. @@ -484,6 +485,7 @@ internal static string GetWindowsPowerShellVersionFromRegistry() #endif internal static string DefaultPowerShellAppBase => GetApplicationBase(DefaultPowerShellShellID); + internal static string GetApplicationBase(string shellId) { // Use the location of SMA.dll as the application base. @@ -734,7 +736,7 @@ internal static bool IsValidPSEditionValue(string editionValue) /// The subdirectory of module paths /// e.g. ~\Documents\WindowsPowerShell\Modules and %ProgramFiles%\WindowsPowerShell\Modules. /// - internal static string ModuleDirectory = Path.Combine(ProductNameForDirectory, "Modules"); + internal static readonly string ModuleDirectory = Path.Combine(ProductNameForDirectory, "Modules"); internal static readonly ConfigScope[] SystemWideOnlyConfig = new[] { ConfigScope.AllUsers }; internal static readonly ConfigScope[] CurrentUserOnlyConfig = new[] { ConfigScope.CurrentUser }; @@ -1455,11 +1457,11 @@ internal static Encoding GetEncoding(string path) } // BigEndianUTF32 encoding is possible, but requires creation - internal static Encoding BigEndianUTF32Encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true); + 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 Dictionary encodingMap = + internal static readonly Dictionary encodingMap = new Dictionary() { { "255-254", Encoding.Unicode }, @@ -1469,7 +1471,7 @@ internal static Encoding GetEncoding(string path) { "239-187-191", Encoding.UTF8 }, }; - internal static char[] nonPrintableCharacters = { + 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, @@ -1825,6 +1827,7 @@ private static void WriteVerbose(PowerShell ps, string msg) } private const string WhereObjectCommandAlias = "?"; + private static bool TryGetCommandInfoList(PowerShell ps, HashSet commandNames, out Collection cmdInfoList) { if (commandNames.Count == 0) @@ -1876,6 +1879,7 @@ internal class PipelineForBatchingChecker : AstVisitor { internal readonly HashSet ValidVariables = new HashSet(StringComparer.OrdinalIgnoreCase); internal readonly HashSet Commands = new HashSet(StringComparer.OrdinalIgnoreCase); + internal ScriptBlockAst ScriptBeingConverted { get; set; } public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) @@ -2098,6 +2102,25 @@ public static bool TestImplicitRemotingBatching(string commandPipeline, System.M { return Utils.TryRunAsImplicitBatch(commandPipeline, runspace); } + + /// + /// Constructs a custom PSSenderInfo instance that can be assigned to $PSSenderInfo + /// in order to simulate a remoting session with respect to the $PSSenderInfo.ConnectionString (connection URL) + /// and $PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion (the remoting client's PowerShell version). + /// See Get-FormatDataTest.ps1. + /// + /// The connection URL to reflect in the returned instance's ConnectionString property. + /// The version number to report as the remoting client's PowerShell version. + /// The newly constructed custom PSSenderInfo instance. + public static PSSenderInfo GetCustomPSSenderInfo(string url, Version clientVersion) + { + var dummyPrincipal = new PSPrincipal(new PSIdentity("none", true, "someuser", null), null); + var pssi = new PSSenderInfo(dummyPrincipal, url); + pssi.ApplicationArguments = new PSPrimitiveDictionary(); + pssi.ApplicationArguments.Add("PSVersionTable", new PSObject(new PSPrimitiveDictionary())); + ((PSPrimitiveDictionary)PSObject.Base(pssi.ApplicationArguments["PSVersionTable"])).Add("PSVersion", new PSObject(clientVersion)); + return pssi; + } } /// diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index 7e9a0a4a026..f41bb3380ba 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -30,7 +30,7 @@ internal PSVariableAttributeCollection(PSVariable variable) { if (variable == null) { - throw PSTraceSource.NewArgumentNullException("variable"); + throw PSTraceSource.NewArgumentNullException(nameof(variable)); } _variable = variable; diff --git a/src/System.Management.Automation/engine/VariableInterfaces.cs b/src/System.Management.Automation/engine/VariableInterfaces.cs index 428ba7522fe..90411860b6d 100644 --- a/src/System.Management.Automation/engine/VariableInterfaces.cs +++ b/src/System.Management.Automation/engine/VariableInterfaces.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation; @@ -35,7 +35,7 @@ internal PSVariableIntrinsics(SessionStateInternal sessionState) { if (sessionState == null) { - throw PSTraceSource.NewArgumentException("sessionState"); + throw PSTraceSource.NewArgumentException(nameof(sessionState)); } _sessionState = sessionState; diff --git a/src/System.Management.Automation/engine/VariablePath.cs b/src/System.Management.Automation/engine/VariablePath.cs index db1bb184fbf..0e33ae620c5 100644 --- a/src/System.Management.Automation/engine/VariablePath.cs +++ b/src/System.Management.Automation/engine/VariablePath.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics; @@ -83,7 +83,7 @@ internal VariablePath(string path, VariablePathFlags knownFlags) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } _userPath = path; diff --git a/src/System.Management.Automation/engine/WinRT/IInspectable.cs b/src/System.Management.Automation/engine/WinRT/IInspectable.cs index d01cf5965cd..f6f4d9ee7d9 100644 --- a/src/System.Management.Automation/engine/WinRT/IInspectable.cs +++ b/src/System.Management.Automation/engine/WinRT/IInspectable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Reflection; diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index 7c6ebb99ee0..b676337531e 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -30,7 +30,7 @@ namespace System.Management.Automation /// task, extending the Cmdlet or PSCmdlet classes only as a thin management layer. /// /// - public abstract partial class Cmdlet : InternalCommand + public abstract class Cmdlet : InternalCommand { #region public_properties @@ -252,10 +252,10 @@ public virtual string GetResourceString(string baseName, string resourceId) using (PSTransactionManager.GetEngineProtectionScope()) { if (string.IsNullOrEmpty(baseName)) - throw PSTraceSource.NewArgumentNullException("baseName"); + throw PSTraceSource.NewArgumentNullException(nameof(baseName)); if (string.IsNullOrEmpty(resourceId)) - throw PSTraceSource.NewArgumentNullException("resourceId"); + throw PSTraceSource.NewArgumentNullException(nameof(resourceId)); ResourceManager manager = ResourceManagerCache.GetResourceManager(this.GetType().Assembly, baseName); string retValue = null; @@ -266,12 +266,12 @@ public virtual string GetResourceString(string baseName, string resourceId) } catch (MissingManifestResourceException) { - throw PSTraceSource.NewArgumentException("baseName", GetErrorText.ResourceBaseNameFailure, baseName); + throw PSTraceSource.NewArgumentException(nameof(baseName), GetErrorText.ResourceBaseNameFailure, baseName); } if (retValue == null) { - throw PSTraceSource.NewArgumentException("resourceId", GetErrorText.ResourceIdFailure, resourceId); + throw PSTraceSource.NewArgumentException(nameof(resourceId), GetErrorText.ResourceIdFailure, resourceId); } return retValue; @@ -1719,7 +1719,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) using (PSTransactionManager.GetEngineProtectionScope()) { if (errorRecord == null) - throw new ArgumentNullException("errorRecord"); + throw new ArgumentNullException(nameof(errorRecord)); if (commandRuntime != null) { diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index 30d83e57693..f9f550da7fa 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -220,7 +220,7 @@ private bool CommandInfoMatches(CommandInfo commandInfo) // If the breakpoint looks like it might have specified a module name and the command // we're checking is in a module, try matching the module\command against the pattern // in the breakpoint. - if (!string.IsNullOrEmpty(commandInfo.ModuleName) && Command.IndexOf('\\') != -1) + if (!string.IsNullOrEmpty(commandInfo.ModuleName) && Command.Contains('\\')) { if (CommandPattern.IsMatch(commandInfo.ModuleName + "\\" + commandInfo.Name)) return true; diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 3b183bb2125..6355b0d83e5 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -248,7 +248,7 @@ public bool UseDefaultProcessing /// public StartRunspaceDebugProcessingEventArgs(Runspace runspace) { - if (runspace == null) { throw new PSArgumentNullException("runspace"); } + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } Runspace = runspace; } @@ -274,7 +274,7 @@ public Runspace Runspace /// public ProcessRunspaceDebugEndEventArgs(Runspace runspace) { - if (runspace == null) { throw new PSArgumentNullException("runspace"); } + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } Runspace = runspace; } @@ -525,7 +525,7 @@ protected bool IsDebuggerBreakpointUpdatedEventSubscribed() /// protected void RaiseStartRunspaceDebugProcessingEvent(StartRunspaceDebugProcessingEventArgs args) { - if (args == null) { throw new PSArgumentNullException("args"); } + if (args == null) { throw new PSArgumentNullException(nameof(args)); } StartRunspaceDebugProcessing.SafeInvoke(this, args); } @@ -533,7 +533,7 @@ protected void RaiseStartRunspaceDebugProcessingEvent(StartRunspaceDebugProcessi /// protected void RaiseRunspaceProcessingCompletedEvent(ProcessRunspaceDebugEndEventArgs args) { - if (args == null) { throw new PSArgumentNullException("args"); } + if (args == null) { throw new PSArgumentNullException(nameof(args)); } RunspaceDebugProcessingCompleted.SafeInvoke(this, args); } @@ -1072,6 +1072,7 @@ internal override bool IsDebuggerSteppingEnabled } private bool? _isLocalSession; + private bool IsLocalSession { get @@ -1723,8 +1724,10 @@ internal void Clear() // Runspace debugger integration. private Dictionary _runningRunspaces; + private const int _jobCallStackOffset = 2; private const int _runspaceCallStackOffset = 1; + private bool _preserveUnhandledDebugStopEvent; private ManualResetEventSlim _preserveDebugStopEvent; @@ -2306,12 +2309,12 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC { if (command == null) { - throw new PSArgumentNullException("command"); + throw new PSArgumentNullException(nameof(command)); } if (output == null) { - throw new PSArgumentNullException("output"); + throw new PSArgumentNullException(nameof(output)); } if (!DebuggerStopped) @@ -2915,7 +2918,7 @@ private Debugger GetRunspaceDebugger(int runspaceId) /// internal override void DebugJob(Job job, bool breakAll) { - if (job == null) { throw new PSArgumentNullException("job"); } + if (job == null) { throw new PSArgumentNullException(nameof(job)); } lock (_syncObject) { @@ -2989,7 +2992,7 @@ private bool TryAddDebugJob(Job job, bool breakAll) internal override void StopDebugJob(Job job) { // Parameter validation. - if (job == null) { throw new PSArgumentNullException("job"); } + if (job == null) { throw new PSArgumentNullException(nameof(job)); } SetInternalDebugMode(InternalDebugMode.Disabled); @@ -3036,7 +3039,7 @@ internal override void DebugRunspace(Runspace runspace, bool breakAll) { if (runspace == null) { - throw new PSArgumentNullException("runspace"); + throw new PSArgumentNullException(nameof(runspace)); } if (runspace.RunspaceStateInfo.State != RunspaceState.Opened) @@ -3079,7 +3082,7 @@ internal override void DebugRunspace(Runspace runspace, bool breakAll) /// Runspace. internal override void StopDebugRunspace(Runspace runspace) { - if (runspace == null) { throw new PSArgumentNullException("runspace"); } + if (runspace == null) { throw new PSArgumentNullException(nameof(runspace)); } SetInternalDebugMode(InternalDebugMode.Disabled); @@ -4225,7 +4228,7 @@ public NestedRunspaceDebugger( { if (runspace == null || runspace.Debugger == null) { - throw new PSArgumentNullException("runspace"); + throw new PSArgumentNullException(nameof(runspace)); } _runspace = runspace; @@ -4725,7 +4728,7 @@ public EmbeddedRunspaceDebugger( { if (rootDebugger == null) { - throw new PSArgumentNullException("rootDebugger"); + throw new PSArgumentNullException(nameof(rootDebugger)); } _command = command; @@ -5474,7 +5477,7 @@ public PSDebugContext(InvocationInfo invocationInfo, List breakpoint { if (breakpoints == null) { - throw new PSArgumentNullException("breakpoints"); + throw new PSArgumentNullException(nameof(breakpoints)); } this.InvocationInfo = invocationInfo; @@ -5526,7 +5529,7 @@ internal CallStackFrame(FunctionContext functionContext, InvocationInfo invocati { if (invocationInfo == null) { - throw new PSArgumentNullException("invocationInfo"); + throw new PSArgumentNullException(nameof(invocationInfo)); } if (functionContext != null) @@ -5682,7 +5685,7 @@ public static bool ShouldAddCommandToHistory(string command) { if (command == null) { - throw new PSArgumentNullException("command"); + throw new PSArgumentNullException(nameof(command)); } lock (s_noHistoryCommandNames) @@ -5700,12 +5703,12 @@ public static void StartMonitoringRunspace(Debugger debugger, PSMonitorRunspaceI { if (debugger == null) { - throw new PSArgumentNullException("debugger"); + throw new PSArgumentNullException(nameof(debugger)); } if (runspaceInfo == null) { - throw new PSArgumentNullException("runspaceInfo"); + throw new PSArgumentNullException(nameof(runspaceInfo)); } debugger.StartMonitoringRunspace(runspaceInfo); @@ -5720,12 +5723,12 @@ public static void EndMonitoringRunspace(Debugger debugger, PSMonitorRunspaceInf { if (debugger == null) { - throw new PSArgumentNullException("debugger"); + throw new PSArgumentNullException(nameof(debugger)); } if (runspaceInfo == null) { - throw new PSArgumentNullException("runspaceInfo"); + throw new PSArgumentNullException(nameof(runspaceInfo)); } debugger.EndMonitoringRunspace(runspaceInfo); @@ -5791,7 +5794,7 @@ protected PSMonitorRunspaceInfo( { if (runspace == null) { - throw new PSArgumentNullException("runspace"); + throw new PSArgumentNullException(nameof(runspace)); } Runspace = runspace; diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index c84f39d3891..8a0101ae802 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Threading; @@ -241,7 +241,7 @@ internal bool InvokeCallbackOnThread(WaitCallback callback, object state) { if (callback == null) { - throw new PSArgumentNullException("callback"); + throw new PSArgumentNullException(nameof(callback)); } _invokeCallback = callback; diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index 82c35951f4c..9fca84d4a33 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; @@ -38,7 +38,7 @@ class ChoiceDescription if (string.IsNullOrEmpty(label)) { // "label" is not localizable - throw PSTraceSource.NewArgumentException("label", DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); + throw PSTraceSource.NewArgumentException(nameof(label), DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); } this.label = label; @@ -68,13 +68,13 @@ class ChoiceDescription if (string.IsNullOrEmpty(label)) { // "label" is not localizable - throw PSTraceSource.NewArgumentException("label", DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); + throw PSTraceSource.NewArgumentException(nameof(label), DescriptionsStrings.NullOrEmptyErrorTemplate, "label"); } if (helpMessage == null) { // "helpMessage" is not localizable - throw PSTraceSource.NewArgumentNullException("helpMessage"); + throw PSTraceSource.NewArgumentNullException(nameof(helpMessage)); } this.label = label; diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index ae091e2ed59..b98e447563b 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -52,7 +52,7 @@ public Command(string command, bool isScript, bool useLocalScope) IsEndOfStatement = false; if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } CommandText = command; @@ -65,7 +65,7 @@ internal Command(string command, bool isScript, bool? useLocalScope) IsEndOfStatement = false; if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } CommandText = command; @@ -109,6 +109,7 @@ internal Command(Command command) MergeToResult = command.MergeToResult; _mergeUnclaimedPreviousCommandResults = command._mergeUnclaimedPreviousCommandResults; IsEndOfStatement = command.IsEndOfStatement; + CommandInfo = command.CommandInfo; foreach (CommandParameter param in command.Parameters) { @@ -317,17 +318,17 @@ public void MergeMyResults(PipelineResultTypes myResult, PipelineResultTypes toR // Validate parameters. if (myResult == PipelineResultTypes.None || myResult == PipelineResultTypes.Output) { - throw PSTraceSource.NewArgumentException("myResult", RunspaceStrings.InvalidMyResultError); + throw PSTraceSource.NewArgumentException(nameof(myResult), RunspaceStrings.InvalidMyResultError); } if (myResult == PipelineResultTypes.Error && toResult != PipelineResultTypes.Output) { - throw PSTraceSource.NewArgumentException("toResult", RunspaceStrings.InvalidValueToResultError); + throw PSTraceSource.NewArgumentException(nameof(toResult), RunspaceStrings.InvalidValueToResultError); } if (toResult != PipelineResultTypes.Output && toResult != PipelineResultTypes.Null) { - throw PSTraceSource.NewArgumentException("toResult", RunspaceStrings.InvalidValueToResult); + throw PSTraceSource.NewArgumentException(nameof(toResult), RunspaceStrings.InvalidValueToResult); } // For V2 backwards compatibility. @@ -517,8 +518,8 @@ CommandOrigin origin case PSLanguageMode.NoLanguage: string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed, "UseLocalScope", - PSLanguageMode.RestrictedLanguage.ToString(), - PSLanguageMode.NoLanguage.ToString()); + nameof(PSLanguageMode.RestrictedLanguage), + nameof(PSLanguageMode.NoLanguage)); throw new RuntimeException(message); case PSLanguageMode.FullLanguage: // Interactive script commands are permitted in this mode... @@ -591,7 +592,7 @@ internal static Command FromPSObjectForRemoting(PSObject commandAsPSObject) { if (commandAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("commandAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(commandAsPSObject)); } string commandText = RemotingDecoder.GetPropertyValue(commandAsPSObject, RemoteDataNameStrings.CommandText); diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index f0b4a640f22..a57b2d4a626 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -333,7 +333,7 @@ internal RunspaceStateEventArgs(RunspaceStateInfo runspaceStateInfo) { if (runspaceStateInfo == null) { - throw PSTraceSource.NewArgumentNullException("runspaceStateInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(runspaceStateInfo)); } RunspaceStateInfo = runspaceStateInfo; @@ -1672,6 +1672,7 @@ internal SessionStateProxy() } private RunspaceBase _runspace; + internal SessionStateProxy(RunspaceBase runspace) { Dbg.Assert(runspace != null, "Caller should validate the parameter"); @@ -1700,7 +1701,7 @@ public virtual void SetVariable(string name, object value) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } _runspace.SetVariable(name, value); @@ -1728,7 +1729,7 @@ public virtual object GetVariable(string name) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (name.Equals(string.Empty)) diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 43b27614a12..cffbc6d81a1 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -40,7 +40,7 @@ protected RunspaceBase(PSHost host) { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } InitialSessionState = InitialSessionState.CreateDefault(); @@ -66,12 +66,12 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState) { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } if (initialSessionState == null) { - throw PSTraceSource.NewArgumentNullException("initialSessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } Host = host; @@ -104,12 +104,12 @@ protected RunspaceBase(PSHost host, InitialSessionState initialSessionState, boo { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } if (initialSessionState == null) { - throw PSTraceSource.NewArgumentNullException("initialSessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } Host = host; @@ -535,7 +535,7 @@ public override Pipeline CreatePipeline(string command) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } return CoreCreatePipeline(command, false, false); @@ -556,7 +556,7 @@ public override Pipeline CreatePipeline(string command, bool addToHistory) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } return CoreCreatePipeline(command, addToHistory, false); @@ -590,7 +590,7 @@ public override Pipeline CreateNestedPipeline(string command, bool addToHistory) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } return CoreCreatePipeline(command, addToHistory, true); @@ -1043,7 +1043,7 @@ internal void StopNestedPipelines(Pipeline pipeline) // Concurrency check should be done under runspace lock lock (SyncRoot) { - if (_bSessionStateProxyCallInProgress == true) + if (_bSessionStateProxyCallInProgress) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoPipelineWhenSessionStateProxyInProgress); } @@ -1151,7 +1151,7 @@ private void DoConcurrentCheckAndMarkSessionStateProxyCallInProgress() throw e; } - if (_bSessionStateProxyCallInProgress == true) + if (_bSessionStateProxyCallInProgress) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.AnotherSessionStateProxyInProgress); } diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs index fbb38b61127..2021ae6abf9 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -62,7 +62,7 @@ public static Runspace CreateRunspace(PSHost host) { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } return new LocalRunspace(host, InitialSessionState.CreateDefault()); @@ -85,7 +85,7 @@ public static Runspace CreateRunspace(InitialSessionState initialSessionState) { if (initialSessionState == null) { - throw PSTraceSource.NewArgumentNullException("initialSessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } PSHost host = new DefaultHost(CultureInfo.CurrentCulture, CultureInfo.CurrentUICulture); @@ -116,12 +116,12 @@ public static Runspace CreateRunspace(PSHost host, InitialSessionState initialSe { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } if (initialSessionState == null) { - throw PSTraceSource.NewArgumentNullException("initialSessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } return new LocalRunspace(host, initialSessionState); @@ -150,12 +150,12 @@ internal static Runspace CreateRunspaceFromSessionStateNoClone(PSHost host, Init { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } if (initialSessionState == null) { - throw PSTraceSource.NewArgumentNullException("initialSessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } return new LocalRunspace(host, initialSessionState, true); diff --git a/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs b/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs index ad61687a10c..1542ab865f7 100644 --- a/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/DefaultHost.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 20deca8818e..545440a1574 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -43,7 +43,7 @@ public class if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentException("name", DescriptionsStrings.NullOrEmptyErrorTemplate, "name"); + throw PSTraceSource.NewArgumentException(nameof(name), DescriptionsStrings.NullOrEmptyErrorTemplate, "name"); } this.name = name; @@ -76,7 +76,7 @@ public string Name { if (parameterType == null) { - throw PSTraceSource.NewArgumentNullException("parameterType"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterType)); } SetParameterTypeName(parameterType.Name); @@ -319,7 +319,7 @@ public string Name { if (string.IsNullOrEmpty(nameOfType)) { - throw PSTraceSource.NewArgumentException("nameOfType", DescriptionsStrings.NullOrEmptyErrorTemplate, "nameOfType"); + throw PSTraceSource.NewArgumentException(nameof(nameOfType), DescriptionsStrings.NullOrEmptyErrorTemplate, "nameOfType"); } parameterTypeName = nameOfType; @@ -339,7 +339,7 @@ public string Name { if (string.IsNullOrEmpty(fullNameOfType)) { - throw PSTraceSource.NewArgumentException("fullNameOfType", DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfType"); + throw PSTraceSource.NewArgumentException(nameof(fullNameOfType), DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfType"); } parameterTypeFullName = fullNameOfType; @@ -359,7 +359,7 @@ public string Name { if (string.IsNullOrEmpty(fullNameOfAssembly)) { - throw PSTraceSource.NewArgumentException("fullNameOfAssembly", DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfAssembly"); + throw PSTraceSource.NewArgumentException(nameof(fullNameOfAssembly), DescriptionsStrings.NullOrEmptyErrorTemplate, "fullNameOfAssembly"); } parameterAssemblyFullName = fullNameOfAssembly; diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index d5e1ef12d86..7bedae6c737 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -141,7 +141,6 @@ public override string ToString() /// private long _pipelineId; - /// /// Returns a clone of this object. /// @@ -285,12 +284,12 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) if (count < -1) { - throw PSTraceSource.NewArgumentOutOfRangeException("count", count); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } if (newest.ToString() == null) { - throw PSTraceSource.NewArgumentNullException("newest"); + throw PSTraceSource.NewArgumentNullException(nameof(newest)); } if (count == -1 || count > _countEntriesAdded || count > _countEntriesInBuffer) @@ -331,7 +330,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) if (firstId <= 1) break; // if entry is null , continue the loop with the next entry if (_buffer[GetIndexFromId(i)] == null) continue; - if (_buffer[GetIndexFromId(i)].Cleared == true) + if (_buffer[GetIndexFromId(i)].Cleared) { // we have to clear count entries before an id, so if an entry is null,decrement // first id as long as its is greater than the lowest entry in the buffer. @@ -344,7 +343,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { // if an entry is null after being cleared by clear-history cmdlet, // continue with the next entry - if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared == true) + if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared) continue; entriesList.Add(_buffer[GetIndexFromId(i)].Clone()); } @@ -364,7 +363,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) if (firstId >= _countEntriesAdded) break; // if entry is null , continue the loop with the next entry if (_buffer[GetIndexFromId(i)] == null) continue; - if (_buffer[GetIndexFromId(i)].Cleared == true) + if (_buffer[GetIndexFromId(i)].Cleared) { // we have to clear count entries before an id, so if an entry is null,increment first id firstId++; @@ -376,7 +375,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { // if an entry is null after being cleared by clear-history cmdlet, // continue with the next entry - if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared == true) + if (_buffer[GetIndexFromId(i)] == null || _buffer[GetIndexFromId(i)].Cleared) continue; entriesList.Add(_buffer[GetIndexFromId(i)].Clone()); } @@ -406,7 +405,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) { if (index > _countEntriesAdded) break; if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || - (_buffer[GetIndexFromId(index)].Cleared == true)) + (_buffer[GetIndexFromId(index)].Cleared)) { index++; continue; } @@ -435,7 +434,7 @@ internal HistoryInfo[] GetEntries(long id, long count, SwitchParameter newest) if (index < 1) break; if ((index <= 0 || GetIndexFromId(index) >= _buffer.Length) || - (_buffer[GetIndexFromId(index)].Cleared == true)) + (_buffer[GetIndexFromId(index)].Cleared)) { index--; continue; } else { @@ -467,12 +466,12 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S { if (count < -1) { - throw PSTraceSource.NewArgumentOutOfRangeException("count", count); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } if (newest.ToString() == null) { - throw PSTraceSource.NewArgumentNullException("newest"); + throw PSTraceSource.NewArgumentNullException(nameof(newest)); } if (count > _countEntriesAdded || count == -1) @@ -560,7 +559,7 @@ internal void ClearEntry(long id) { if (id < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("id", id); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(id), id); } // no entries are present to clear if (_countEntriesInBuffer == 0) @@ -610,7 +609,7 @@ private long Add(HistoryInfo entry) { if (entry == null) { - throw PSTraceSource.NewArgumentNullException("entry"); + throw PSTraceSource.NewArgumentNullException(nameof(entry)); } _buffer[GetIndexForNewEntry()] = entry; @@ -638,7 +637,7 @@ private HistoryInfo CoreGetEntry(long id) { if (id <= 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("id", id); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(id), id); } if (_countEntriesInBuffer == 0) @@ -1020,7 +1019,7 @@ protected override void EndProcessing() { // Invoke-history can execute only one command. If multiple // ids were provided, throw exception - if (_multipleIdProvided == true) + if (_multipleIdProvided) { Exception ex = new ArgumentException @@ -1717,7 +1716,7 @@ protected override void BeginProcessing() protected override void ProcessRecord() { // case statement to identify the parameter set - switch (ParameterSetName.ToString()) + switch (ParameterSetName) { case "IDParameter": ClearHistoryByID(); diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index acc3a26bd53..ecc4780c284 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -800,12 +800,12 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace { if (command == null) { - throw new PSArgumentNullException("command"); + throw new PSArgumentNullException(nameof(command)); } if (runspace == null) { - throw new PSArgumentNullException("runspace"); + throw new PSArgumentNullException(nameof(runspace)); } if ((runspace.Debugger != null) && runspace.Debugger.InBreakpoint) diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index 34aa7ca0e30..9325f95ccad 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -158,6 +158,7 @@ internal virtual void ToPSObjectForRemoting(PSObject psObject) [DataMember()] private string _message; + private InvocationInfo _invocationInfo; private ReadOnlyCollection _pipelineIterationInfo; private bool _serializeExtendedInfo; diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index f56d05341c4..e170a3792e4 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs index d310d2fd056..d182ef6302a 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostRawUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 366a76902c5..1e2478d7bd2 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -27,7 +27,7 @@ class InternalHostUserInterface : PSHostUserInterface, IHostUISupportsMultipleCh Dbg.Assert(parentHost != null, "parent may not be null"); if (parentHost == null) { - throw PSTraceSource.NewArgumentNullException("parentHost"); + throw PSTraceSource.NewArgumentNullException(nameof(parentHost)); } _parent = parentHost; @@ -88,7 +88,7 @@ public override bool SupportsVirtualTerminal /// /// /// if the UI property of the external host is null, possibly because the PSHostUserInterface is not - /// implemented by the external host + /// implemented by the external host. /// public override string @@ -120,12 +120,53 @@ public override return result; } + /// + /// See base class. + /// + /// + /// The characters typed by the user. + /// + /// + /// If the UI property of the external host is null, possibly because the PSHostUserInterface is not + /// implemented by the external host. + /// + public override + string + ReadLineMaskedAsString() + { + if (_externalUI == null) + { + ThrowNotInteractive(); + } + + string result = null; + + try + { + result = _externalUI.ReadLineMaskedAsString(); + } + catch (PipelineStoppedException) + { + // PipelineStoppedException is thrown by host when it wants + // to stop the pipeline. + LocalPipeline lpl = (LocalPipeline)((RunspaceBase)_parent.Context.CurrentRunspace).GetCurrentlyRunningPipeline(); + if (lpl == null) + { + throw; + } + + lpl.Stopper.Stop(); + } + + return result; + } + /// /// See base class. /// /// /// if the UI property of the external host is null, possibly because the PSHostUserInterface is not - /// implemented by the external host + /// implemented by the external host. /// public override @@ -414,7 +455,7 @@ internal void WriteDebugInfoBuffers(DebugRecord record) throw ense; default: Dbg.Assert(false, "all preferences should be checked"); - throw PSTraceSource.NewArgumentException("preference", + throw PSTraceSource.NewArgumentException(nameof(preference), InternalHostUserInterfaceStrings.UnsupportedPreferenceError, preference); // break; } @@ -546,7 +587,7 @@ public override { if (record == null) { - throw PSTraceSource.NewArgumentNullException("record"); + throw PSTraceSource.NewArgumentNullException(nameof(record)); } // Write to Information Buffers @@ -732,12 +773,12 @@ public override { if (descriptions == null) { - throw PSTraceSource.NewArgumentNullException("descriptions"); + throw PSTraceSource.NewArgumentNullException(nameof(descriptions)); } if (descriptions.Count < 1) { - throw PSTraceSource.NewArgumentException("descriptions", InternalHostUserInterfaceStrings.PromptEmptyDescriptionsError, "descriptions"); + throw PSTraceSource.NewArgumentException(nameof(descriptions), InternalHostUserInterfaceStrings.PromptEmptyDescriptionsError, "descriptions"); } if (_externalUI == null) @@ -898,12 +939,12 @@ private Collection EmulatePromptForMultipleChoice(string caption, if (choices == null) { - throw PSTraceSource.NewArgumentNullException("choices"); + throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { - throw PSTraceSource.NewArgumentException("choices", + throw PSTraceSource.NewArgumentException(nameof(choices), InternalHostUserInterfaceStrings.EmptyChoicesError, "choices"); } @@ -921,10 +962,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, defaultChoice); } - if (!defaultChoiceKeys.ContainsKey(defaultChoice)) - { - defaultChoiceKeys.Add(defaultChoice, true); - } + defaultChoiceKeys.TryAdd(defaultChoice, true); } } diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index f72322e90d7..191a5309cc7 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -88,7 +88,7 @@ public PSListModifier(Hashtable hash) { if (hash == null) { - throw PSTraceSource.NewArgumentNullException("hash"); + throw PSTraceSource.NewArgumentNullException(nameof(hash)); } _itemsToAdd = new Collection(); @@ -106,7 +106,7 @@ public PSListModifier(Hashtable hash) if (!isAdd && !isRemove && !isReplace) { - throw PSTraceSource.NewArgumentException("hash", PSListModifierStrings.ListModifierDisallowedKey, key); + throw PSTraceSource.NewArgumentException(nameof(hash), PSListModifierStrings.ListModifierDisallowedKey, key); } Collection collection; @@ -138,7 +138,7 @@ public PSListModifier(Hashtable hash) } else { - throw PSTraceSource.NewArgumentException("hash", PSListModifierStrings.ListModifierDisallowedKey, entry.Key); + throw PSTraceSource.NewArgumentException(nameof(hash), PSListModifierStrings.ListModifierDisallowedKey, entry.Key); } } } @@ -181,7 +181,7 @@ public void ApplyTo(IList collectionToUpdate) { if (collectionToUpdate == null) { - throw PSTraceSource.NewArgumentNullException("collectionToUpdate"); + throw PSTraceSource.NewArgumentNullException(nameof(collectionToUpdate)); } if (_replacementItems.Count > 0) @@ -214,7 +214,7 @@ public void ApplyTo(object collectionToUpdate) { if (collectionToUpdate == null) { - throw new ArgumentNullException("collectionToUpdate"); + throw new ArgumentNullException(nameof(collectionToUpdate)); } collectionToUpdate = PSObject.Base(collectionToUpdate); diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 796e6c4d18c..92740acf8dd 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -1340,7 +1340,7 @@ internal sealed class StopJobOperationHelper : IThrottleOperation internal StopJobOperationHelper(Job job) { _job = job; - _job.StateChanged += new EventHandler(HandleJobStateChanged); + _job.StateChanged += HandleJobStateChanged; } /// @@ -1392,7 +1392,7 @@ internal override void StopOperation() /// private void RaiseOperationCompleteEvent() { - _job.StateChanged -= new EventHandler(HandleJobStateChanged); + _job.StateChanged -= HandleJobStateChanged; OperationStateEventArgs operationStateArgs = new OperationStateEventArgs(); operationStateArgs.OperationState = OperationState.StartComplete; @@ -1417,7 +1417,7 @@ internal sealed class CloseOrDisconnectRunspaceOperationHelper : IThrottleOperat internal CloseOrDisconnectRunspaceOperationHelper(RemoteRunspace remoteRunspace) { _remoteRunspace = remoteRunspace; - _remoteRunspace.StateChanged += new EventHandler(HandleRunspaceStateChanged); + _remoteRunspace.StateChanged += HandleRunspaceStateChanged; } /// @@ -1494,7 +1494,7 @@ internal override void StopOperation() /// private void RaiseOperationCompleteEvent() { - _remoteRunspace.StateChanged -= new EventHandler(HandleRunspaceStateChanged); + _remoteRunspace.StateChanged -= HandleRunspaceStateChanged; OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); @@ -1592,7 +1592,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index a0d50bd15d8..379deff42e7 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -1320,6 +1320,7 @@ internal PipelineStopper(LocalPipeline localPipeline) /// This is set true when stop is called. /// private bool _stopping; + internal bool IsStopping { get @@ -1341,7 +1342,7 @@ internal void Push(PipelineProcessor item) { if (item == null) { - throw PSTraceSource.NewArgumentNullException("item"); + throw PSTraceSource.NewArgumentNullException(nameof(item)); } lock (_syncRoot) @@ -1394,7 +1395,7 @@ internal void Stop() PipelineProcessor[] copyStack; lock (_syncRoot) { - if (_stopping == true) + if (_stopping) { return; } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index fdd6dce1196..0c5ef87436f 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -41,6 +41,7 @@ public abstract class PSHost /// The powershell spec states that 128 is the maximum nesting depth. /// internal const int MaximumNestedPromptLevel = 128; + internal static bool IsStdOutputRedirected; /// diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index 41d27605390..79f4bcff66a 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; @@ -794,13 +794,13 @@ public int Bottom if (right < left) { // "right" and "left" are not localizable - throw PSTraceSource.NewArgumentException("right", MshHostRawUserInterfaceStrings.LessThanErrorTemplate, "right", "left"); + throw PSTraceSource.NewArgumentException(nameof(right), MshHostRawUserInterfaceStrings.LessThanErrorTemplate, "right", "left"); } if (bottom < top) { // "bottom" and "top" are not localizable - throw PSTraceSource.NewArgumentException("bottom", MshHostRawUserInterfaceStrings.LessThanErrorTemplate, "bottom", "top"); + throw PSTraceSource.NewArgumentException(nameof(bottom), MshHostRawUserInterfaceStrings.LessThanErrorTemplate, "bottom", "top"); } this.left = left; @@ -1681,7 +1681,7 @@ int offset { if (source == null) { - throw PSTraceSource.NewArgumentNullException("source"); + throw PSTraceSource.NewArgumentNullException(nameof(source)); } // this implementation is inefficient @@ -1720,7 +1720,7 @@ string source { if (source == null) { - throw PSTraceSource.NewArgumentNullException("source"); + throw PSTraceSource.NewArgumentNullException(nameof(source)); } return source.Length; @@ -1807,7 +1807,7 @@ char source if (contents == null) { - throw PSTraceSource.NewArgumentNullException("contents"); + throw PSTraceSource.NewArgumentNullException(nameof(contents)); } byte[][] charLengths = new byte[contents.Length][]; @@ -1835,7 +1835,7 @@ char source if (maxStringLengthInBufferCells <= 0) { - throw PSTraceSource.NewArgumentException("contents", MshHostRawUserInterfaceStrings.AllNullOrEmptyStringsErrorTemplate); + throw PSTraceSource.NewArgumentException(nameof(contents), MshHostRawUserInterfaceStrings.AllNullOrEmptyStringsErrorTemplate); } BufferCell[,] results = new BufferCell[contents.Length, maxStringLengthInBufferCells]; @@ -1920,14 +1920,14 @@ char source if (width <= 0) { // "width" is not localizable - throw PSTraceSource.NewArgumentOutOfRangeException("width", width, + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(width), width, MshHostRawUserInterfaceStrings.NonPositiveNumberErrorTemplate, "width"); } if (height <= 0) { // "height" is not localizable - throw PSTraceSource.NewArgumentOutOfRangeException("height", height, + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(height), height, MshHostRawUserInterfaceStrings.NonPositiveNumberErrorTemplate, "height"); } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index 38166d0b8e3..2efd4d3c154 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -59,6 +59,30 @@ public abstract System.Management.Automation.Host.PSHostRawUserInterface RawUI /// /// public abstract string ReadLine(); + + /// + /// Same as ReadLine except that the input is not echoed to the user while it is collected + /// or is echoed in some obfuscated way, such as showing a dot for each character. + /// + /// + /// The characters typed by the user. + /// + /// + /// Note that credentials (a user name and password) should be gathered with + /// + /// + /// + /// + /// + /// + /// + /// + public virtual string ReadLineMaskedAsString() + { + // Default implementation of the function to maintain backwards compatibility of the base class. + throw new PSNotImplementedException(); + } + /// /// Same as ReadLine, except that the result is a SecureString, and that the input is not echoed to the user while it is /// collected (or is echoed in some obfuscated way, such as showing a dot for each character). @@ -391,12 +415,16 @@ internal void IgnoreCommand(string commandText, InvocationInfo invocation) /// make it to the actual host. /// internal bool TranscribeOnly => Interlocked.CompareExchange(ref _transcribeOnlyCount, 0, 0) != 0; + private int _transcribeOnlyCount = 0; + internal IDisposable SetTranscribeOnly() => new TranscribeOnlyCookie(this); + private sealed class TranscribeOnlyCookie : IDisposable { private PSHostUserInterface _ui; private bool _disposed = false; + public TranscribeOnlyCookie(PSHostUserInterface ui) { _ui = ui; @@ -950,6 +978,7 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio internal static TranscriptionOption systemTranscript = null; private static object s_systemTranscriptLock = new object(); + private static Lazy s_transcriptionSettingCache = new Lazy( () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); @@ -1247,7 +1276,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch if (andPos + 1 < choices[i].Label.Length) { splitLabel.Append(choices[i].Label.Substring(andPos + 1)); - hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.Substring(andPos + 1, 1).Trim()); + hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.AsSpan(andPos + 1, 1).Trim().ToString()); } hotkeysAndPlainLabels[1, i] = splitLabel.ToString().Trim(); diff --git a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs index f53035d6c22..1d21fa952a0 100644 --- a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs +++ b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /********************************************************************++ @@ -236,8 +236,7 @@ internal static CultureInfo GetUICulture(bool filterOutNonConsoleCultures) { try { - string[] fallbacks = langBuffer.Split(new char[] { '\0' }, - StringSplitOptions.RemoveEmptyEntries); + string[] fallbacks = langBuffer.Split('\0', StringSplitOptions.RemoveEmptyEntries); string fallback = fallbacks[0]; string[] fallbacksForParent = null; diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index b9615ab0783..781e53eaf51 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Runspaces; @@ -133,7 +133,7 @@ public PSCommand AddCommand(string cmdlet, bool useLocalScope) { if (cmdlet == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } if (_owner != null) @@ -175,7 +175,7 @@ public PSCommand AddScript(string script) { if (script == null) { - throw PSTraceSource.NewArgumentNullException("script"); + throw PSTraceSource.NewArgumentNullException(nameof(script)); } if (_owner != null) @@ -220,7 +220,7 @@ public PSCommand AddScript(string script, bool useLocalScope) { if (script == null) { - throw PSTraceSource.NewArgumentNullException("script"); + throw PSTraceSource.NewArgumentNullException(nameof(script)); } if (_owner != null) @@ -258,7 +258,7 @@ public PSCommand AddCommand(Command command) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } if (_owner != null) diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index 2f21bb990f4..51d74dcc269 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -333,14 +333,14 @@ protected PSDataCollection(SerializationInfo info, StreamingContext context) { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } IList listToUse = info.GetValue("Data", typeof(IList)) as IList; if (listToUse == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } _data = listToUse; @@ -664,7 +664,7 @@ public T this[int index] { if ((index < 0) || (index >= _data.Count)) { - throw PSTraceSource.NewArgumentOutOfRangeException("index", index, + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(index), index, PSDataBufferStrings.IndexOutOfRange, 0, _data.Count - 1); } @@ -738,7 +738,7 @@ public void RemoveAt(int index) { if ((index < 0) || (index >= _data.Count)) { - throw PSTraceSource.NewArgumentOutOfRangeException("index", index, + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(index), index, PSDataBufferStrings.IndexOutOfRange, 0, _data.Count - 1); } @@ -1299,7 +1299,7 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } info.AddValue("Data", _data); @@ -1514,7 +1514,7 @@ internal void InternalAddRange(Guid psInstanceId, ICollection collection) { if (collection == null) { - throw PSTraceSource.NewArgumentNullException("collection"); + throw PSTraceSource.NewArgumentNullException(nameof(collection)); } int index = -1; @@ -1631,12 +1631,12 @@ private static void VerifyValueType(object value) { if (typeof(T).IsValueType) { - throw PSTraceSource.NewArgumentNullException("value", PSDataBufferStrings.ValueNullReference); + throw PSTraceSource.NewArgumentNullException(nameof(value), PSDataBufferStrings.ValueNullReference); } } else if (!(value is T)) { - throw PSTraceSource.NewArgumentException("value", PSDataBufferStrings.CannotConvertToGenericType, + throw PSTraceSource.NewArgumentException(nameof(value), PSDataBufferStrings.CannotConvertToGenericType, value.GetType().FullName, typeof(T).FullName); } diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index c52715927b1..a25e4e2c840 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -1,6 +1,7 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Management.Automation.Host; @@ -320,7 +321,7 @@ internal abstract class PSTaskBase : IDisposable protected PowerShell _powershell; protected PSDataCollection _output; - private const string RunspaceName = "PSTask"; + public const string RunspaceName = "PSTask"; private static int s_taskId; @@ -364,6 +365,11 @@ public PSInvocationState State /// public int Id { get => _id; } + /// + /// Gets Task Runspace. + /// + public Runspace Runspace { get => _runspace; } + #endregion #region Constructor @@ -410,7 +416,6 @@ protected PSTaskBase( /// public void Dispose() { - _runspace.Dispose(); _powershell.Dispose(); _output.Dispose(); } @@ -422,7 +427,8 @@ public void Dispose() /// /// Start task. /// - public void Start() + /// Runspace used to run task. + public void Start(Runspace runspace) { if (_powershell != null) { @@ -430,13 +436,8 @@ public void Start() return; } - // Create and open Runspace for this task to run in - var iss = InitialSessionState.CreateDefault2(); - iss.LanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) - ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; - _runspace = RunspaceFactory.CreateRunspace(iss); - _runspace.Name = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", RunspaceName, s_taskId); - _runspace.Open(); + Dbg.Assert(runspace != null, "Task runspace cannot be null."); + _runspace = runspace; // If available, set current working directory on the runspace. // Temporarily set the newly created runspace as the thread default runspace for any needed module loading. @@ -445,8 +446,17 @@ public void Start() var oldDefaultRunspace = Runspace.DefaultRunspace; try { - Runspace.DefaultRunspace = _runspace; - _runspace.ExecutionContext.SessionState.Internal.SetLocation(_currentLocationPath); + Runspace.DefaultRunspace = runspace; + var context = new CmdletProviderContext(runspace.ExecutionContext) + { + // _currentLocationPath denotes the current path as-is, and should not be attempted expanded. + SuppressWildcardExpansion = true + }; + runspace.ExecutionContext.SessionState.Internal.SetLocation(_currentLocationPath, context); + } + catch (DriveNotFoundException) + { + // Allow task to run if current drive is not available. } finally { @@ -456,7 +466,7 @@ public void Start() // Create the PowerShell command pipeline for the provided script block // The script will run on the provided Runspace in a new thread by default - _powershell = PowerShell.Create(_runspace); + _powershell = PowerShell.Create(runspace); // Initialize PowerShell object data streams and event handlers _output = new PSDataCollection(); @@ -632,8 +642,13 @@ internal sealed class PSTaskPool : IDisposable private readonly ManualResetEvent _stopAll; private readonly object _syncObject; private readonly Dictionary _taskPool; + private readonly ConcurrentQueue _runspacePool; + private readonly ConcurrentDictionary _activeRunspaces; private readonly WaitHandle[] _waitHandles; + private readonly bool _useRunspacePool; private bool _isOpen; + private bool _stopping; + private int _createdRunspaceCount; private const int AddAvailable = 0; private const int Stop = 1; @@ -648,9 +663,13 @@ private PSTaskPool() { } /// Initializes a new instance of the class. /// /// Total number of allowed running objects in pool at one time. - public PSTaskPool(int size) + /// When true, a new runspace object is created for the task instead of reusing one from the pool. + public PSTaskPool( + int size, + bool useNewRunspace) { _sizeLimit = size; + _useRunspacePool = !useNewRunspace; _isOpen = true; _syncObject = new object(); _addAvailable = new ManualResetEvent(true); @@ -661,6 +680,11 @@ public PSTaskPool(int size) _stopAll, // index 1 }; _taskPool = new Dictionary(size); + _activeRunspaces = new ConcurrentDictionary(); + if (_useRunspacePool) + { + _runspacePool = new ConcurrentQueue(); + } } #endregion @@ -684,6 +708,14 @@ public bool IsOpen get => _isOpen; } + /// + /// Gets a value of the count of total runspaces allocated. + /// + public int AllocatedRunspaceCount + { + get => _createdRunspaceCount; + } + #endregion #region IDisposable @@ -695,6 +727,21 @@ public void Dispose() { _addAvailable.Dispose(); _stopAll.Dispose(); + + DisposeRunspaces(); + } + + /// + /// Dispose runspaces. + /// + internal void DisposeRunspaces() + { + foreach (var item in _activeRunspaces) + { + item.Value.Dispose(); + } + + _activeRunspaces.Clear(); } #endregion @@ -721,6 +768,7 @@ public bool Add(PSTaskBase task) switch (index) { case AddAvailable: + var runspace = GetRunspace(task.Id); task.StateChanged += HandleTaskStateChangedDelegate; lock (_syncObject) { @@ -735,7 +783,7 @@ public bool Add(PSTaskBase task) _addAvailable.Reset(); } - task.Start(); + task.Start(runspace); } return true; @@ -763,18 +811,28 @@ public bool Add(PSTaskChildJob childJob) /// public void StopAll() { + _stopping = true; + // Accept no more input Close(); _stopAll.Set(); // Stop all running tasks + PSTaskBase[] tasksToStop; lock (_syncObject) { - foreach (var task in _taskPool.Values) - { - task.Dispose(); - } + tasksToStop = new PSTaskBase[_taskPool.Values.Count]; + _taskPool.Values.CopyTo(tasksToStop, 0); } + + foreach (var task in tasksToStop) + { + task.Dispose(); + } + + // Dispose all active runspaces + DisposeRunspaces(); + _stopping = false; } /// @@ -803,6 +861,7 @@ private void HandleTaskStateChanged(object sender, PSInvocationStateChangedEvent case PSInvocationState.Completed: case PSInvocationState.Stopped: case PSInvocationState.Failed: + ReturnRunspace(task); lock (_syncObject) { _taskPool.Remove(task.Id); @@ -813,7 +872,12 @@ private void HandleTaskStateChanged(object sender, PSInvocationStateChangedEvent } task.StateChanged -= HandleTaskStateChangedDelegate; - task.Dispose(); + if (!_stopping || stateInfo.State != PSInvocationState.Stopped) + { + // StopAll disposes tasks. + task.Dispose(); + } + CheckForComplete(); break; } @@ -842,6 +906,64 @@ private void CheckForComplete() } } + private Runspace GetRunspace(int taskId) + { + var runspaceName = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", PSTask.RunspaceName, taskId); + + if (_useRunspacePool && _runspacePool.TryDequeue(out Runspace runspace)) + { + if (runspace.RunspaceStateInfo.State == RunspaceState.Opened && + runspace.RunspaceAvailability == RunspaceAvailability.Available) + { + try + { + runspace.ResetRunspaceState(); + runspace.Name = runspaceName; + return runspace; + } + catch + { + // If the runspace cannot be reset for any reason, remove it. + } + } + + RemoveActiveRunspace(runspace); + } + + // Create and initialize a new Runspace + var iss = InitialSessionState.CreateDefault2(); + iss.LanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) + ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; + runspace = RunspaceFactory.CreateRunspace(iss); + runspace.Name = runspaceName; + _activeRunspaces.TryAdd(runspace.Id, runspace); + runspace.Open(); + _createdRunspaceCount++; + + return runspace; + } + + private void ReturnRunspace(PSTaskBase task) + { + var runspace = task.Runspace; + Dbg.Assert(runspace != null, "Task runspace cannot be null."); + if (_useRunspacePool && + runspace.RunspaceStateInfo.State == RunspaceState.Opened && + runspace.RunspaceAvailability == RunspaceAvailability.Available) + { + _runspacePool.Enqueue(runspace); + return; + } + + RemoveActiveRunspace(runspace); + } + + private void RemoveActiveRunspace(Runspace runspace) + { + runspace.Dispose(); + _activeRunspaces.TryRemove(runspace.Id, out Runspace _); + } + #endregion } @@ -852,7 +974,7 @@ private void CheckForComplete() /// /// Job for running ForEach-Object parallel task child jobs asynchronously. /// - internal sealed class PSTaskJob : Job + public sealed class PSTaskJob : Job { #region Members @@ -862,6 +984,18 @@ internal sealed class PSTaskJob : Job #endregion + #region Properties + + /// + /// Gets a value of the count of total runspaces allocated. + /// + public int AllocatedRunspaceCount + { + get => _taskPool.AllocatedRunspaceCount; + } + + #endregion + #region Constructor private PSTaskJob() { } @@ -871,11 +1005,13 @@ private PSTaskJob() { } /// /// Job command text. /// Pool size limit for task job. - public PSTaskJob( + /// When true, a new runspace object is created for the task instead of reusing one from the pool. + internal PSTaskJob( string command, - int throttleLimit) : base(command, string.Empty) + int throttleLimit, + bool useNewRunspace) : base(command, string.Empty) { - _taskPool = new PSTaskPool(throttleLimit); + _taskPool = new PSTaskPool(throttleLimit, useNewRunspace); _isOpen = true; PSJobTypeName = nameof(PSTaskJob); @@ -949,14 +1085,14 @@ protected override void Dispose(bool disposing) #endregion - #region Public Methods + #region Internal Methods /// /// Add a child job to the collection. /// /// Child job to add. /// True when child job is successfully added. - public bool AddJob(PSTaskChildJob childJob) + internal bool AddJob(PSTaskChildJob childJob) { if (!_isOpen) { @@ -971,7 +1107,7 @@ public bool AddJob(PSTaskChildJob childJob) /// Closes this parent job to adding more child jobs and starts /// the child jobs running with the provided throttle limit. /// - public void Start() + internal void Start() { _isOpen = false; SetJobState(JobState.Running); @@ -1017,6 +1153,9 @@ private void HandleTaskPoolComplete(object sender, EventArgs args) } SetJobState(finalState); + + // Release job task pool runspace resources. + (sender as PSTaskPool).DisposeRunspaces(); } catch (ObjectDisposedException) { } @@ -1052,7 +1191,7 @@ public PSTaskChildDebugger( { if (debugger == null) { - throw new PSArgumentNullException("debugger"); + throw new PSArgumentNullException(nameof(debugger)); } _wrappedDebugger = debugger; diff --git a/src/System.Management.Automation/engine/hostifaces/Parameter.cs b/src/System.Management.Automation/engine/hostifaces/Parameter.cs index 54fdbb18de0..3f7d072318a 100644 --- a/src/System.Management.Automation/engine/hostifaces/Parameter.cs +++ b/src/System.Management.Automation/engine/hostifaces/Parameter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Language; @@ -33,7 +33,7 @@ public CommandParameter(string name) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } } @@ -51,7 +51,7 @@ public CommandParameter(string name, object value) { if (string.IsNullOrWhiteSpace(name)) { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } Name = name; @@ -90,7 +90,7 @@ internal static CommandParameter FromCommandParameterInternal(CommandParameterIn { if (internalParameter == null) { - throw PSTraceSource.NewArgumentNullException("internalParameter"); + throw PSTraceSource.NewArgumentNullException(nameof(internalParameter)); } // we want the name to preserve 1) dashes, 2) colons, 3) followed-by-space information @@ -125,7 +125,7 @@ internal static CommandParameterInternal ToCommandParameterInternal(CommandParam { if (publicParameter == null) { - throw PSTraceSource.NewArgumentNullException("publicParameter"); + throw PSTraceSource.NewArgumentNullException(nameof(publicParameter)); } string name = publicParameter.Name; @@ -211,7 +211,7 @@ internal static CommandParameter FromPSObjectForRemoting(PSObject parameterAsPSO { if (parameterAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("parameterAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(parameterAsPSObject)); } string name = RemotingDecoder.GetPropertyValue(parameterAsPSObject, RemoteDataNameStrings.ParameterName); diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index b73d4ed7db2..0a584c6fc36 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -305,7 +305,7 @@ internal Pipeline(Runspace runspace, CommandCollection command) { if (runspace == null) { - PSTraceSource.NewArgumentNullException("runspace"); + PSTraceSource.NewArgumentNullException(nameof(runspace)); } // This constructor is used only internally. // Caller should make sure the input is valid diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index d1b26a1e111..ba559a5e1f6 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1169,7 +1169,7 @@ public PowerShell AddCommand(CommandInfo commandInfo) { if (commandInfo == null) { - throw PSTraceSource.NewArgumentNullException("commandInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } Command cmd = new Command(commandInfo); @@ -1292,7 +1292,7 @@ public PowerShell AddParameters(IList parameters) { if (parameters == null) { - throw PSTraceSource.NewArgumentNullException("parameters"); + throw PSTraceSource.NewArgumentNullException(nameof(parameters)); } if (_psCommand.Commands.Count == 0) @@ -1340,7 +1340,7 @@ public PowerShell AddParameters(IDictionary parameters) { if (parameters == null) { - throw PSTraceSource.NewArgumentNullException("parameters"); + throw PSTraceSource.NewArgumentNullException(nameof(parameters)); } if (_psCommand.Commands.Count == 0) @@ -1356,7 +1356,7 @@ public PowerShell AddParameters(IDictionary parameters) if (parameterName == null) { - throw PSTraceSource.NewArgumentException("parameters", PowerShellStrings.KeyMustBeString); + throw PSTraceSource.NewArgumentException(nameof(parameters), PowerShellStrings.KeyMustBeString); } _psCommand.AddParameter(parameterName, entry.Value); @@ -2727,7 +2727,7 @@ public void Invoke(IEnumerable input, IList output, PSInvocationSettings s { if (output == null) { - throw PSTraceSource.NewArgumentNullException("output"); + throw PSTraceSource.NewArgumentNullException(nameof(output)); } // use the above collection as the data store. PSDataCollection listToWriteTo = new PSDataCollection(output); @@ -2798,7 +2798,7 @@ public void Invoke(PSDataCollection input, PSDataCollec { if (output == null) { - throw PSTraceSource.NewArgumentNullException("output"); + throw PSTraceSource.NewArgumentNullException(nameof(output)); } CoreInvoke(input, output, settings); @@ -3034,7 +3034,7 @@ public IAsyncResult BeginInvoke(PSDataCollection input, { if (output == null) { - throw PSTraceSource.NewArgumentNullException("output"); + throw PSTraceSource.NewArgumentNullException(nameof(output)); } DetermineIsBatching(); @@ -3649,7 +3649,7 @@ public PSDataCollection EndInvoke(IAsyncResult asyncResult) if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; @@ -3658,7 +3658,7 @@ public PSDataCollection EndInvoke(IAsyncResult asyncResult) (psAsyncResult.OwnerId != InstanceId) || (psAsyncResult.IsAssociatedWithAsyncInvoke != true)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), PowerShellStrings.AsyncResultNotOwned, "IAsyncResult", "BeginInvoke"); } @@ -3752,16 +3752,16 @@ public void EndStop(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } PowerShellAsyncResult psAsyncResult = asyncResult as PowerShellAsyncResult; if ((psAsyncResult == null) || (psAsyncResult.OwnerId != InstanceId) || - (psAsyncResult.IsAssociatedWithAsyncInvoke != false)) + (psAsyncResult.IsAssociatedWithAsyncInvoke)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), PowerShellStrings.AsyncResultNotOwned, "IAsyncResult", "BeginStop"); } @@ -3940,7 +3940,7 @@ private SteppablePipeline GetSteppablePipeline(ExecutionContext context, Command ( Runspace.DefaultRunspace.ExecutionContext, false, - IsNested == true ? CommandOrigin.Internal : CommandOrigin.Runspace + IsNested ? CommandOrigin.Internal : CommandOrigin.Runspace ); commandProcessorBase.RedirectShellErrorOutputPipe = RedirectShellErrorOutputPipe; @@ -5720,7 +5720,7 @@ internal static PowerShell FromPSObjectForRemoting(PSObject powerShellAsPSObject { if (powerShellAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("powerShellAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(powerShellAsPSObject)); } Collection extraCommands = null; @@ -6153,12 +6153,12 @@ internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { if (context == null) { - throw new ArgumentNullException("context"); + throw new ArgumentNullException(nameof(context)); } if (powerShell == null) { - throw new ArgumentNullException("powerShell"); + throw new ArgumentNullException(nameof(powerShell)); } _powerShell = powerShell; diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 5ea05bd2c0f..35029df1e06 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.ComponentModel; @@ -38,7 +38,8 @@ static PowerShellProcessInstance() PwshExePath = Path.Combine(Utils.DefaultPowerShellAppBase, "pwsh"); #else PwshExePath = Path.Combine(Utils.DefaultPowerShellAppBase, "pwsh.exe"); - WinPwshExePath = Path.Combine(Utils.GetApplicationBaseFromRegistry(Utils.DefaultPowerShellShellID), "powershell.exe"); + var winPowerShellDir = Utils.GetApplicationBaseFromRegistry(Utils.DefaultPowerShellShellID); + WinPwshExePath = string.IsNullOrEmpty(winPowerShellDir) ? null : Path.Combine(winPowerShellDir, "powershell.exe"); #endif } @@ -59,6 +60,11 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent startingWindowsPowerShell51 = (powerShellVersion != null) && (powerShellVersion.Major == 5) && (powerShellVersion.Minor == 1); if (startingWindowsPowerShell51) { + if (WinPwshExePath == null) + { + throw new PSInvalidOperationException(RemotingErrorIdStrings.WindowsPowerShellNotPresent); + } + exePath = WinPwshExePath; if (useWow64) @@ -93,13 +99,16 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent LoadUserProfile = true, #endif }; - +#if !UNIX if (startingWindowsPowerShell51) { _startInfo.ArgumentList.Add("-Version"); _startInfo.ArgumentList.Add("5.1"); - } + // if starting Windows PowerShell, need to remove PowerShell specific segments of PSModulePath + _startInfo.Environment["PSModulePath"] = ModuleIntrinsics.GetWindowsPowerShellModulePath(); + } +#endif _startInfo.ArgumentList.Add("-s"); _startInfo.ArgumentList.Add("-NoLogo"); _startInfo.ArgumentList.Add("-NoProfile"); diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs index d9616190772..04dc65baac2 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInit.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs index acc0ddf426d..25c611eba0e 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 541575099b2..3c88f8b9ff7 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -506,6 +506,7 @@ public sealed class RunspacePool : IDisposable private RunspacePoolInternal _internalPool; private object _syncObject = new object(); + private event EventHandler InternalStateChanged = null; private event EventHandler InternalForwardEvent = null; private event EventHandler InternalRunspaceCreated = null; @@ -747,8 +748,7 @@ public event EventHandler StateChanged // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. - _internalPool.StateChanged += - new EventHandler(OnStateChanged); + _internalPool.StateChanged += OnStateChanged; } } } @@ -760,8 +760,7 @@ public event EventHandler StateChanged InternalStateChanged -= value; if (InternalStateChanged == null) { - _internalPool.StateChanged -= - new EventHandler(OnStateChanged); + _internalPool.StateChanged -= OnStateChanged; } } } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index 3215b8f2f6b..02f0fffaf30 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -76,7 +76,7 @@ public RunspacePoolInternal(int minRunspaces, { if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } this.host = host; @@ -121,12 +121,12 @@ public RunspacePoolInternal(int minRunspaces, { if (initialSessionState == null) { - throw PSTraceSource.NewArgumentNullException("initialSessionState"); + throw PSTraceSource.NewArgumentNullException(nameof(initialSessionState)); } if (host == null) { - throw PSTraceSource.NewArgumentNullException("host"); + throw PSTraceSource.NewArgumentNullException(nameof(host)); } _initialSessionState = initialSessionState.Clone(); @@ -154,17 +154,17 @@ protected RunspacePoolInternal(int minRunspaces, int maxRunspaces) { if (maxRunspaces < 1) { - throw PSTraceSource.NewArgumentException("maxRunspaces", RunspacePoolStrings.MaxPoolLessThan1); + throw PSTraceSource.NewArgumentException(nameof(maxRunspaces), RunspacePoolStrings.MaxPoolLessThan1); } if (minRunspaces < 1) { - throw PSTraceSource.NewArgumentException("minRunspaces", RunspacePoolStrings.MinPoolLessThan1); + throw PSTraceSource.NewArgumentException(nameof(minRunspaces), RunspacePoolStrings.MinPoolLessThan1); } if (minRunspaces > maxRunspaces) { - throw PSTraceSource.NewArgumentException("minRunspaces", RunspacePoolStrings.MinPoolGreaterThanMaxPool); + throw PSTraceSource.NewArgumentException(nameof(minRunspaces), RunspacePoolStrings.MinPoolGreaterThanMaxPool); } maxPoolSz = maxRunspaces; @@ -618,7 +618,7 @@ public void EndOpen(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; @@ -627,7 +627,7 @@ public void EndOpen(IAsyncResult asyncResult) (rsAsyncResult.OwnerId != instanceId) || (!rsAsyncResult.IsAssociatedWithAsyncOpen)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginOpen"); @@ -685,7 +685,7 @@ public virtual void EndClose(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; @@ -694,7 +694,7 @@ public virtual void EndClose(IAsyncResult asyncResult) (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginClose"); @@ -754,7 +754,7 @@ public void ReleaseRunspace(Runspace runspace) { if (runspace == null) { - throw PSTraceSource.NewArgumentNullException("runspace"); + throw PSTraceSource.NewArgumentNullException(nameof(runspace)); } AssertPoolIsOpen(); @@ -893,7 +893,7 @@ internal void CancelGetRunspace(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } GetRunspaceAsyncResult grsAsyncResult = @@ -901,7 +901,7 @@ internal void CancelGetRunspace(IAsyncResult asyncResult) if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginGetRunspace"); @@ -932,7 +932,7 @@ internal Runspace EndGetRunspace(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } GetRunspaceAsyncResult grsAsyncResult = @@ -940,7 +940,7 @@ internal Runspace EndGetRunspace(IAsyncResult asyncResult) if ((grsAsyncResult == null) || (grsAsyncResult.OwnerId != instanceId)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginGetRunspace"); @@ -1332,7 +1332,7 @@ protected void CleanupCallback(object state) Runspace runspaceToDestroy = null; lock (pool) { - if (pool.Count <= 0) + if (pool.Count == 0) { break; // break from while } diff --git a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs index 9d408fc99d6..f5155fd7c13 100644 --- a/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs +++ b/src/System.Management.Automation/engine/hostifaces/internalHostuserInterfacesecurity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index 305514f70d8..64efdb12e4a 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Runspaces @@ -97,7 +97,7 @@ protected PipelineBase(Runspace runspace, // to add cmd to CommandCollection again (Initialize does this).. because of this // I am handling history here.. Initialize(runspace, null, false, isNested); - if (true == addToHistory) + if (addToHistory) { // get command text for history.. string cmdText = command.GetCommandStringForHistory(); @@ -128,7 +128,7 @@ protected PipelineBase(PipelineBase pipeline) // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (pipeline == null) { - throw PSTraceSource.NewArgumentNullException("pipeline"); + throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } if (pipeline._disposed) @@ -921,7 +921,7 @@ private set { Dbg.Assert(value != null, "ErrorStream cannot be null"); _errorStream = value; - _errorStream.DataReady += new EventHandler(OnErrorStreamDataReady); + _errorStream.DataReady += OnErrorStreamDataReady; } } @@ -933,7 +933,7 @@ private void OnErrorStreamDataReady(object sender, EventArgs e) // unsubscribe from further event notifications as // this notification is suffice to say there is an // error. - _errorStream.DataReady -= new EventHandler(OnErrorStreamDataReady); + _errorStream.DataReady -= OnErrorStreamDataReady; SetHadErrors(true); } } @@ -997,7 +997,7 @@ private void Initialize(Runspace runspace, string command, bool addToHistory, bo if (addToHistory && command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } if (command != null) @@ -1052,7 +1052,7 @@ protected override InputStream.Close(); OutputStream.Close(); - _errorStream.DataReady -= new EventHandler(OnErrorStreamDataReady); + _errorStream.DataReady -= OnErrorStreamDataReady; _errorStream.Close(); _executionEventQueue.Clear(); diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index 1c2523874c1..56aca65df37 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -253,6 +253,7 @@ public override string ToString() internal sealed class GotoInstruction : IndexedBranchInstruction { private const int Variants = 4; + private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize]; private readonly bool _hasResult; diff --git a/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs b/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs index 0bb35e1ff26..ab7aa891a26 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicSplatInstruction.cs @@ -20,7 +20,7 @@ namespace System.Management.Automation.Interpreter /// /// Implements dynamic call site with many arguments. Wraps the arguments into . /// - internal sealed partial class DynamicSplatInstruction : Instruction + internal sealed class DynamicSplatInstruction : Instruction { private readonly CallSite> _site; private readonly int _argumentCount; diff --git a/src/System.Management.Automation/engine/interpreter/Instruction.cs b/src/System.Management.Automation/engine/interpreter/Instruction.cs index f2072b2a488..0a46fd88dfa 100644 --- a/src/System.Management.Automation/engine/interpreter/Instruction.cs +++ b/src/System.Management.Automation/engine/interpreter/Instruction.cs @@ -22,7 +22,7 @@ internal interface IInstructionProvider void AddInstructions(LightCompiler compiler); } - internal abstract partial class Instruction + internal abstract class Instruction { public const int UnknownInstrIndex = int.MaxValue; diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 3e15b1fbba4..d4d6923da81 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -35,6 +35,7 @@ internal sealed class InterpretedFrame [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] private int[] _continuations; + private int _continuationIndex; private int _pendingContinuation; private object _pendingValue; diff --git a/src/System.Management.Automation/engine/interpreter/Interpreter.cs b/src/System.Management.Automation/engine/interpreter/Interpreter.cs index 622364184e0..8afdfe69b3d 100644 --- a/src/System.Management.Automation/engine/interpreter/Interpreter.cs +++ b/src/System.Management.Automation/engine/interpreter/Interpreter.cs @@ -31,6 +31,7 @@ namespace System.Management.Automation.Interpreter internal sealed class Interpreter { internal static readonly object NoValue = new object(); + internal const int RethrowOnReturn = Int32.MaxValue; // zero: sync compilation diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index e05965cb8ff..b05b317dfb5 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -2034,7 +2034,7 @@ private void CompileNoLabelPush(Expression expr) case ExpressionType.PostDecrementAssign: CompileReducibleExpression(expr); break; default: throw Assert.Unreachable; - }; + } Debug.Assert(_instructions.CurrentStackDepth == startingStackDepth + (expr.Type == typeof(void) ? 0 : 1)); } diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index 45874d6a6c8..2ff8dbf9790 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -126,7 +126,7 @@ internal static T[] AddLast(this IList list, T item) } } - internal static partial class DelegateHelpers + internal static class DelegateHelpers { #region Generated Maximum Delegate Arity @@ -239,8 +239,8 @@ internal static object BooleanToObject(bool b) internal static readonly MethodInfo BooleanToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("BooleanToObject"); internal static readonly MethodInfo Int32ToObjectMethod = typeof(ScriptingRuntimeHelpers).GetMethod("Int32ToObject"); - internal static object True = true; - internal static object False = false; + internal static readonly object True = true; + internal static readonly object False = false; internal static object GetPrimitiveDefaultValue(Type type) { @@ -375,6 +375,7 @@ internal class HybridReferenceDictionary where TKey : class private KeyValuePair[] _keysAndValues; private Dictionary _dict; private int _count; + private const int _arraySize = 10; public HybridReferenceDictionary() diff --git a/src/System.Management.Automation/engine/lang/codegen.cs b/src/System.Management.Automation/engine/lang/codegen.cs index d94adf00cc8..16fdf3079ba 100644 --- a/src/System.Management.Automation/engine/lang/codegen.cs +++ b/src/System.Management.Automation/engine/lang/codegen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Text; diff --git a/src/System.Management.Automation/engine/lang/interface/PSParseError.cs b/src/System.Management.Automation/engine/lang/interface/PSParseError.cs index e3be59b5bee..5fa12cc073c 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParseError.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParseError.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /********************************************************************++ diff --git a/src/System.Management.Automation/engine/lang/interface/PSParser.cs b/src/System.Management.Automation/engine/lang/interface/PSParser.cs index 21d8b5b1bf9..2b6886dbce6 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSParser.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /********************************************************************++ @@ -147,7 +147,7 @@ private Collection Errors public static Collection Tokenize(string script, out Collection errors) { if (script == null) - throw PSTraceSource.NewArgumentNullException("script"); + throw PSTraceSource.NewArgumentNullException(nameof(script)); PSParser psParser = new PSParser(); @@ -174,7 +174,7 @@ public static Collection Tokenize(string script, out Collection Tokenize(object[] script, out Collection errors) { if (script == null) - throw PSTraceSource.NewArgumentNullException("script"); + throw PSTraceSource.NewArgumentNullException(nameof(script)); StringBuilder sb = new StringBuilder(); foreach (object obj in script) diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index 712dc35ec54..b0b34ec0544 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /********************************************************************++ diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 38045a18d9c..d3af98dcea5 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -278,6 +278,7 @@ static ParserOps() private const int _MinCache = -100; private const int _MaxCache = 1000; + private static readonly object[] s_integerCache = new object[_MaxCache - _MinCache]; private static readonly string[] s_chars = new string[255]; internal static readonly object _TrueObject = (object)true; @@ -904,7 +905,6 @@ private static object AsChar(object obj) return null; } - /// /// The implementation of the PowerShell -replace operator.... /// @@ -927,7 +927,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e { // only allow 1 or 2 arguments to -replace throw InterpreterError.NewInterpreterException(rval, typeof(RuntimeException), errorPosition, - "BadReplaceArgument", ParserStrings.BadReplaceArgument, ignoreCase ? "-ireplace" : "-replace", rList.Count); + "BadReplaceArgument", ParserStrings.BadReplaceArgument, errorPosition.Text, rList.Count); } if (rList.Count > 0) @@ -1177,13 +1177,10 @@ internal static object MatchOperator(ExecutionContext context, IScriptExtent err // if passed an explicit regex, just use it // otherwise compile the expression. - Regex r = PSObject.Base(rval) as Regex; - if (r == null) - { - // In this situation, creation of Regex should not fail. We are not - // processing ArgumentException in this case. - r = NewRegex(PSObject.ToStringParser(context, rval), reOptions); - } + // In this situation, creation of Regex should not fail. We are not + // processing ArgumentException in this case. + Regex r = PSObject.Base(rval) as Regex + ?? NewRegex(PSObject.ToStringParser(context, rval), reOptions); IEnumerator list = LanguagePrimitives.GetEnumerator(lval); if (list == null) @@ -1639,12 +1636,14 @@ internal static object CallMethod( internal class RangeEnumerator : IEnumerator { private int _lowerBound; + internal int LowerBound { get { return _lowerBound; } } private int _upperBound; + internal int UpperBound { get { return _upperBound; } @@ -1810,7 +1809,7 @@ internal static RuntimeException NewInterpreterExceptionWithInnerException(objec { // errToken may be null if (string.IsNullOrEmpty(resourceIdAndErrorId)) - throw PSTraceSource.NewArgumentException("resourceIdAndErrorId"); + throw PSTraceSource.NewArgumentException(nameof(resourceIdAndErrorId)); // innerException may be null // args may be null or empty diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 8a16a5f8726..cdce996a3c9 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -361,7 +361,6 @@ internal PowerShell GetPowerShell( public SteppablePipeline GetSteppablePipeline() => GetSteppablePipelineImpl(commandOrigin: CommandOrigin.Internal, args: null); - /// /// Get a steppable pipeline object. /// @@ -647,16 +646,17 @@ internal ReadOnlyCollection OutputType /// /// This does normal array reduction in the case of a one-element array. /// - internal static object GetRawResult(List result) + internal static object GetRawResult(List result, bool wrapToPSObject) { switch (result.Count) { case 0: return AutomationNull.Value; case 1: - return LanguagePrimitives.AsPSObjectOrNull(result[0]); + return wrapToPSObject ? LanguagePrimitives.AsPSObjectOrNull(result[0]) : result[0]; default: - return LanguagePrimitives.AsPSObjectOrNull(result.ToArray()); + object resultArray = result.ToArray(); + return wrapToPSObject ? LanguagePrimitives.AsPSObjectOrNull(resultArray) : resultArray; } } @@ -807,7 +807,7 @@ internal object InvokeAsDelegateHelper(object dollarUnder, object dollarThis, ob outputPipe: outputPipe, invocationInfo: null, args: args); - return GetRawResult(rawResult); + return GetRawResult(rawResult, wrapToPSObject: false); } #endregion @@ -934,7 +934,7 @@ internal object DoInvokeReturnAsIs( outputPipe: outputPipe, invocationInfo: null, args: args); - return GetRawResult(result); + return GetRawResult(result, wrapToPSObject: true); } internal void InvokeWithPipe( diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index a0089fc5d35..4d24dcf55a3 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -181,7 +181,7 @@ public interface ICustomAstVisitor2 : ICustomAstVisitor } #if DEBUG - class CheckAllParentsSet : AstVisitor2 + internal class CheckAllParentsSet : AstVisitor2 { internal CheckAllParentsSet(Ast root) { @@ -328,7 +328,7 @@ internal AstVisitAction CheckParent(Ast ast) /// /// Check if contains type. /// - class CheckTypeBuilder : AstVisitor2 + internal class CheckTypeBuilder : AstVisitor2 { public override AstVisitAction VisitTypeConstraint(TypeConstraintAst ast) { diff --git a/src/System.Management.Automation/engine/parser/CharTraits.cs b/src/System.Management.Automation/engine/parser/CharTraits.cs index 1130a3909bb..fc45f017afd 100644 --- a/src/System.Management.Automation/engine/parser/CharTraits.cs +++ b/src/System.Management.Automation/engine/parser/CharTraits.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Language diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 1a0c8e104d3..d25aad0485d 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -169,6 +169,7 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo ExceptionHandlingOps_ConvertToMethodInvocationException = typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToMethodInvocationException), StaticFlags); + internal static readonly MethodInfo ExceptionHandlingOps_FindMatchingHandler = typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.FindMatchingHandler), StaticFlags); @@ -221,14 +222,19 @@ internal static class CachedReflectionInfo internal static readonly FieldInfo FunctionContext__currentSequencePointIndex = typeof(FunctionContext).GetField(nameof(FunctionContext._currentSequencePointIndex), InstanceFlags); + internal static readonly FieldInfo FunctionContext__executionContext = typeof(FunctionContext).GetField(nameof(FunctionContext._executionContext), InstanceFlags); + internal static readonly FieldInfo FunctionContext__functionName = typeof(FunctionContext).GetField(nameof(FunctionContext._functionName), InstanceFlags); + internal static readonly FieldInfo FunctionContext__localsTuple = typeof(FunctionContext).GetField(nameof(FunctionContext._localsTuple), InstanceFlags); + internal static readonly FieldInfo FunctionContext__outputPipe = typeof(FunctionContext).GetField(nameof(FunctionContext._outputPipe), InstanceFlags); + internal static readonly MethodInfo FunctionContext_PopTrapHandlers = typeof(FunctionContext).GetMethod(nameof(FunctionContext.PopTrapHandlers), InstanceFlags); @@ -275,13 +281,16 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo InterpreterError_NewInterpreterException = typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterException), StaticFlags); + internal static readonly MethodInfo InterpreterError_NewInterpreterExceptionWithInnerException = typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterExceptionWithInnerException), StaticFlags); internal static readonly MethodInfo LanguagePrimitives_GetInvalidCastMessages = typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.GetInvalidCastMessages), StaticFlags); + internal static readonly MethodInfo LanguagePrimitives_IsNull = typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.IsNull), StaticFlags); + internal static readonly MethodInfo LanguagePrimitives_ThrowInvalidCastException = typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.ThrowInvalidCastException), StaticFlags); @@ -455,6 +464,7 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo PSScriptProperty_InvokeGetter = typeof(PSScriptProperty).GetMethod(nameof(PSScriptProperty.InvokeGetter), InstanceFlags); + internal static readonly MethodInfo PSScriptProperty_InvokeSetter = typeof(PSScriptProperty).GetMethod(nameof(PSScriptProperty.InvokeSetter), InstanceFlags); @@ -612,7 +622,6 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo VariableOps_SetVariableValue = typeof(VariableOps).GetMethod(nameof(VariableOps.SetVariableValue), StaticFlags); - internal static readonly MethodInfo Utils_IsComObject = typeof(Utils).GetMethod(nameof(Utils.IsComObject), StaticFlags); @@ -658,7 +667,8 @@ internal static class ExpressionCache internal static readonly Expression CatchAllType = Expression.Constant(typeof(ExceptionHandlingOps.CatchAll), typeof(Type)); // Empty expression is used at the end of blocks to give them the void expression result internal static readonly Expression Empty = Expression.Empty(); - internal static Expression GetExecutionContextFromTLS = + + internal static readonly Expression GetExecutionContextFromTLS = Expression.Call(CachedReflectionInfo.LocalPipeline_GetExecutionContextFromTLS); internal static readonly Expression BoxedTrue = Expression.Field(null, typeof(Boxed).GetField("True", BindingFlags.Static | BindingFlags.NonPublic)); @@ -804,8 +814,10 @@ internal class Compiler : ICustomAstVisitor2 private static readonly CatchBlock[] s_stmtCatchHandlers; internal static readonly Type DottedLocalsTupleType = MutableTuple.MakeTupleType(SpecialVariables.AutomaticVariableTypes); + internal static readonly Dictionary DottedLocalsNameIndexMap = new Dictionary(SpecialVariables.AutomaticVariableTypes.Length, StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary DottedScriptCmdletLocalsNameIndexMap = new Dictionary( SpecialVariables.AutomaticVariableTypes.Length + SpecialVariables.PreferenceVariableTypes.Length, @@ -982,19 +994,23 @@ private static Expression Coalesce(Expression left, Expression right) { return left; } - else if (leftType == typeof(AutomationNull)) - { - return right; - } else { - Expression lhs = left.Cast(typeof(object)); - Expression rhs = right.Cast(typeof(object)); + ParameterExpression lhsStoreVar = Expression.Variable(typeof(object)); + var blockParameters = new ParameterExpression[] { lhsStoreVar }; + var blockStatements = new Expression[] + { + Expression.Assign(lhsStoreVar, left.Cast(typeof(object))), + Expression.Condition( + Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhsStoreVar), + right.Cast(typeof(object)), + lhsStoreVar), + }; - return Expression.Condition( - Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhs), - rhs, - lhs); + return Expression.Block( + typeof(object), + blockParameters, + blockStatements); } } @@ -2277,7 +2293,7 @@ private Expression CaptureAstResults( result = resultList; break; default: - throw new ArgumentOutOfRangeException("context"); + throw new ArgumentOutOfRangeException(nameof(context)); } finallyExprs.Add(Expression.Assign(s_getCurrentPipe, oldPipe)); @@ -4171,7 +4187,9 @@ public object VisitCommand(CommandAst commandAst) private Expression GetCommandArgumentExpression(CommandElementAst element) { var constElement = element as ConstantExpressionAst; - if (constElement != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constElement.StaticType))) + if (constElement != null + && (LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constElement.StaticType)) + || constElement.StaticType == typeof(System.Numerics.BigInteger))) { var commandArgumentText = constElement.Extent.Text; if (!commandArgumentText.Equals(constElement.Value.ToString(), StringComparison.Ordinal)) diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index 16d4a8d271e..5813ed9d41f 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -435,7 +435,6 @@ private static object CompileAndInvoke(Ast ast) public object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordAst) { return AutomationNull.Value; } - public object VisitStatementBlock(StatementBlockAst statementBlockAst) { CheckIsConstant(statementBlockAst, "Caller to verify ast is constant"); diff --git a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs index 6970e17b7cd..93e11f598b1 100644 --- a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs +++ b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs index 0fb4ab37b0a..467f3f2c5e7 100644 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. +// Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 703fc00706f..7ffaab3ff0a 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -20,11 +20,13 @@ internal class TypeDefiner internal const string DynamicClassAssemblyFullNamePrefix = "PowerShell Class Assembly,"; private static int s_globalCounter = 0; + private static readonly CustomAttributeBuilder s_hiddenCustomAttributeBuilder = new CustomAttributeBuilder(typeof(HiddenAttribute).GetConstructor(Type.EmptyTypes), Array.Empty()); private static readonly string s_sessionStateKeeperFieldName = "__sessionStateKeeper"; internal static readonly string SessionStateFieldName = "__sessionState"; + private static readonly MethodInfo s_sessionStateKeeper_GetSessionState = typeof(SessionStateKeeper).GetMethod("GetSessionState", BindingFlags.Instance | BindingFlags.Public); @@ -347,7 +349,6 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou // fall to the default base type } else - { if (baseClass.IsSealed) { @@ -1298,6 +1299,7 @@ private static IEnumerable GetAssemblyAttributeBuilders( } private static int counter = 0; + internal static Assembly DefineTypes(Parser parser, Ast rootAst, TypeDefinitionAst[] typeDefinitions) { Diagnostics.Assert(rootAst.Parent == null, "Caller should only define types from the root ast"); diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index b0b84572dd5..cb0ace0029a 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -8,14 +8,10 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Linq.Expressions; using System.Management.Automation.Runspaces; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; -#if !CORECLR -using Microsoft.CodeAnalysis; -#endif namespace System.Management.Automation.Language { @@ -43,6 +39,7 @@ public sealed class Parser private ParseMode _parseMode; internal string _fileName; + internal bool ProduceV2Tokens { get; set; } internal const string VERBATIM_ARGUMENT = "--%"; @@ -72,7 +69,7 @@ public static ScriptBlockAst ParseFile(string fileName, out Token[] tokens, out var parser = new Parser(); if (!string.IsNullOrEmpty(fileName) && fileName.Length > scriptSchemaExtension.Length && fileName.EndsWith(scriptSchemaExtension, StringComparison.OrdinalIgnoreCase)) { - parser._keywordModuleName = Path.GetFileName(fileName.Substring(0, fileName.Length - scriptSchemaExtension.Length)); + parser._keywordModuleName = Path.GetFileName(fileName.AsSpan(0, fileName.Length - scriptSchemaExtension.Length)).ToString(); parseDscResource = true; } @@ -2749,28 +2746,42 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke while (true) { - ExpressionAst clauseCondition = GetSingleCommandArgument(CommandArgumentContext.SwitchCondition); - if (clauseCondition == null) - { - // ErrorRecovery: if we don't have anything that looks like a condition, we won't - // find a body (because a body is just a script block, which works as a condition.) - // So don't look for a body, hope we find the '}' next. + Token token = PeekToken(); + bool isDefaultClause = token.Kind == TokenKind.Default; + ExpressionAst clauseCondition = null; - isError = true; - ReportIncompleteInput(After(endErrorStatement), - nameof(ParserStrings.MissingSwitchConditionExpression), - ParserStrings.MissingSwitchConditionExpression); - // Consume a closing curly, if there is one, to avoid an extra error - if (PeekToken().Kind == TokenKind.RCurly) + if (isDefaultClause) + { + // Consume the 'default' token. + SkipToken(); + clauseCondition = new StringConstantExpressionAst(token.Extent, token.Text, StringConstantType.BareWord); + } + else + { + clauseCondition = GetSingleCommandArgument(CommandArgumentContext.SwitchCondition); + if (clauseCondition == null) { - SkipToken(); - } + // ErrorRecovery: if we don't have anything that looks like a condition, we won't + // find a body (because a body is just a script block, which works as a condition.) + // So don't look for a body, hope we find the '}' next. + isError = true; + ReportIncompleteInput(After(endErrorStatement), + nameof(ParserStrings.MissingSwitchConditionExpression), + ParserStrings.MissingSwitchConditionExpression); - break; + // Consume a closing curly, if there is one, to avoid an extra error + if (PeekToken().Kind == TokenKind.RCurly) + { + SkipToken(); + } + + break; + } } errorAsts.Add(clauseCondition); endErrorStatement = clauseCondition.Extent; + StatementBlockAst clauseBody = StatementBlockRule(); if (clauseBody == null) { @@ -2786,11 +2797,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke errorAsts.Add(clauseBody); endErrorStatement = clauseBody.Extent; - var clauseConditionString = clauseCondition as StringConstantExpressionAst; - - if (clauseConditionString != null && - clauseConditionString.StringConstantType == StringConstantType.BareWord && - clauseConditionString.Value.Equals("default", StringComparison.OrdinalIgnoreCase)) + if (isDefaultClause) { if (@default != null) { @@ -2812,7 +2819,7 @@ private StatementAst SwitchStatementRule(LabelToken labelToken, Token switchToke SkipNewlinesAndSemicolons(); - Token token = PeekToken(); + token = PeekToken(); if (token.Kind == TokenKind.RCurly) { rCurly = token; @@ -4891,7 +4898,7 @@ private StatementAst UsingStatementRule(Token usingToken) { case TokenKind.EndOfInput: case TokenKind.NewLine: - // Example: 'using module ,FooBar' + // Example: 'using module ,exampleModuleName' // GetCommandArgument will successfully return an argument for a unary array argument // but we don't want to allow that syntax with a using statement. case TokenKind.Comma: @@ -8086,7 +8093,8 @@ public override string ToString() [EventSource(Name = "Microsoft-PowerShell-Parser")] internal class ParserEventSource : EventSource { - internal static ParserEventSource Log = new ParserEventSource(); + internal static readonly ParserEventSource Log = new ParserEventSource(); + internal const int MaxScriptLengthToLog = 50; public void ParseStart(string FileName, int Length) { WriteEvent(1, FileName, Length); } @@ -8111,7 +8119,7 @@ internal class ParserEventSource : EventSource internal static string GetFileOrScript(string fileName, string input) { - return fileName ?? input.Substring(0, Math.Min(256, input.Length)).Trim(); + return fileName ?? input.AsSpan(0, Math.Min(256, input.Length)).Trim().ToString(); } } } diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index f26054174e4..e9f273fed14 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -150,7 +150,7 @@ internal static string VerboseMessage(IScriptExtent position) : sourceLine.Length - position.StartColumnNumber + 1; // Expand tabs before figuring out if we need to truncate the line - if (sourceLine.IndexOf('\t') != -1) + if (sourceLine.Contains('\t')) { var copyLine = new StringBuilder(sourceLine.Length * 2); diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index ad95def8db8..b865a76ee40 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index 75328a91ddd..37320de83d1 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -64,6 +64,7 @@ internal bool IsAstSafe(Ast ast) // This is a check of the number of visits private uint _visitCount = 0; + private const uint MaxVisitCount = 5000; private const int MaxHashtableKeyCount = 500; @@ -529,7 +530,7 @@ public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) var target = indexExpressionAst.Target.Accept(this); if (index == null || target == null) { - throw new ArgumentNullException("indexExpressionAst"); + throw new ArgumentNullException(nameof(indexExpressionAst)); } return GetIndexedValueFromTarget(target, index); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 5fcd1ab4a0a..b7d3bdb8bc8 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -18,15 +18,18 @@ namespace System.Management.Automation.Language internal class SemanticChecks : AstVisitor2, IAstPostVisitHandler { private readonly Parser _parser; + private static readonly IsConstantValueVisitor s_isConstantAttributeArgVisitor = new IsConstantValueVisitor { CheckingAttributeArgument = true, }; + private static readonly IsConstantValueVisitor s_isConstantAttributeArgForClassVisitor = new IsConstantValueVisitor { CheckingAttributeArgument = true, CheckingClassAttributeArguments = true }; + private readonly Stack _memberScopeStack; private readonly Stack _scopeStack; diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index f9fcf48d906..42091ba2e7b 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -498,8 +498,8 @@ private Collection GetModulesFromUsingModule(UsingStatementAst usi return null; } - // case 1: relative path. Relative for file in the same folder should include .\ - bool isPath = fullyQualifiedNameStr.Contains(@"\"); + // case 1: relative path. Relative for file in the same folder should include .\ or ./ + bool isPath = fullyQualifiedNameStr.Contains('\\') || fullyQualifiedNameStr.Contains('/'); if (isPath && !LocationGlobber.IsAbsolutePath(fullyQualifiedNameStr)) { string rootPath = Path.GetDirectoryName(_parser._fileName); diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 9380092a35a..f49c1fe5cd3 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -109,7 +109,7 @@ internal static IList InferTypeOf( } } - class PSTypeNameComparer : IEqualityComparer + internal class PSTypeNameComparer : IEqualityComparer { public bool Equals(PSTypeName x, PSTypeName y) { @@ -2347,7 +2347,7 @@ private static CommandBaseAst GetPreviousPipelineCommand(CommandAst commandAst) } } - static class TypeInferenceExtension + internal static class TypeInferenceExtension { public static bool EqualsOrdinalIgnoreCase(this string s, string t) { diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index 9fee8108b60..24c949960d1 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -221,7 +221,7 @@ private static Type ResolveTypeNameWorker(TypeName typeName, /// This set should be used directly only in the method CallResolveTypeNameWorkerHelper. /// [ThreadStatic] - private static HashSet s_searchedAssemblies = null; + private static HashSet t_searchedAssemblies = null; /// /// A helper method to call ResolveTypeNameWorker in steps. @@ -233,21 +233,21 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, TypeResolutionState typeResolutionState, out Exception exception) { - if (s_searchedAssemblies == null) + if (t_searchedAssemblies == null) { - s_searchedAssemblies = new HashSet(); + t_searchedAssemblies = new HashSet(); } else { // Clear the set before starting a full search to make sure we have a clean start. - s_searchedAssemblies.Clear(); + t_searchedAssemblies.Clear(); } try { exception = null; var currentScope = context != null ? context.EngineSessionState.CurrentScope : null; - Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, s_searchedAssemblies, typeResolutionState, + Type result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, t_searchedAssemblies, typeResolutionState, /*onlySearchInGivenAssemblies*/ false, /* reportAmbiguousException */ true, out exception); if (exception == null && result == null) { @@ -256,14 +256,14 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, // If the assemblies to search from is not specified by the caller of 'ResolveTypeNameWithContext', // then we search our assembly cache first, so as to give preference to resolving the type against // assemblies explicitly loaded by powershell, for example, via importing module/snapin. - result = ResolveTypeNameWorker(typeName, currentScope, context.AssemblyCache.Values, s_searchedAssemblies, typeResolutionState, + result = ResolveTypeNameWorker(typeName, currentScope, context.AssemblyCache.Values, t_searchedAssemblies, typeResolutionState, /*onlySearchInGivenAssemblies*/ true, /* reportAmbiguousException */ false, out exception); } if (result == null) { // Search from the assembly list passed in. - result = ResolveTypeNameWorker(typeName, currentScope, assemblies, s_searchedAssemblies, typeResolutionState, + result = ResolveTypeNameWorker(typeName, currentScope, assemblies, t_searchedAssemblies, typeResolutionState, /*onlySearchInGivenAssemblies*/ true, /* reportAmbiguousException */ false, out exception); } } @@ -273,7 +273,7 @@ private static Type CallResolveTypeNameWorkerHelper(TypeName typeName, finally { // Clear the set after a full search, so dynamic assemblies can get reclaimed as needed. - s_searchedAssemblies.Clear(); + t_searchedAssemblies.Clear(); } } @@ -723,7 +723,7 @@ internal static class CoreTypes // expose the ability to corrupt or escape PowerShell's environment. The following operations must // be safe: type conversion, all constructors, all methods (instance and static), and // and properties (instance and static). - internal static Lazy> Items = new Lazy>( + internal static readonly Lazy> Items = new Lazy>( () => new Dictionary { @@ -845,11 +845,11 @@ internal static bool Contains(Type inputType) internal static class TypeAccelerators { // builtins are not exposed publicly in a direct manner so they can't be changed at all - internal static Dictionary builtinTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary builtinTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); // users can add to user added accelerators (but not currently remove any.) Keeping a separate // list allows us to add removing in the future w/o worrying about breaking the builtins. - internal static Dictionary userTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); + internal static readonly Dictionary userTypeAccelerators = new Dictionary(64, StringComparer.OrdinalIgnoreCase); // We expose this one publicly for programmatic access to our type accelerator table, but it is // otherwise unused (so changes to this dictionary don't affect internals.) diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 66d7f43804d..8b0ab3249df 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -37,6 +37,7 @@ internal VariableAnalysisDetails() internal class FindAllVariablesVisitor : AstVisitor { private static readonly HashSet s_hashOfPessimizingCmdlets = new HashSet(StringComparer.OrdinalIgnoreCase); + private static readonly string[] s_pessimizingCmdlets = new string[] { "New-Variable", @@ -107,6 +108,7 @@ internal static Dictionary Visit(IParameterMeta } private bool _disableOptimizations; + private readonly Dictionary _variables = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -251,6 +253,7 @@ public override AstVisitAction VisitVariableExpression(VariableExpressionAst var } private int _runtimeUsingIndex; + public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpressionAst) { // On the local machine, we may have set the index because of a call to ScriptBlockToPowerShell or Invoke-Command. @@ -353,6 +356,7 @@ private class Block internal object _visitData; internal bool _throws; internal bool _returns; + internal bool _unreachable { get; private set; } // Only Entry block, that can be constructed via NewEntryBlock() is reachable initially. diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 460ef64f8bb..79d74b9edef 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // @@ -58,6 +58,7 @@ internal interface IParameterMetadataProvider IEnumerable GetExperimentalAttributes(); bool UsesCmdletBinding(); + ReadOnlyCollection Parameters { get; } ScriptBlockAst Body { get; } @@ -66,6 +67,7 @@ internal interface IParameterMetadataProvider PowerShell GetPowerShell(ExecutionContext context, Dictionary variables, bool isTrustedInput, bool filterNonUsingVariables, bool? createLocalScope, params object[] args); + string GetWithInputHandlingForInvokeCommand(); /// @@ -93,7 +95,7 @@ protected Ast(IScriptExtent extent) { if (extent == null) { - throw PSTraceSource.NewArgumentNullException("extent"); + throw PSTraceSource.NewArgumentNullException(nameof(extent)); } this.Extent = extent; @@ -119,7 +121,7 @@ public object Visit(ICustomAstVisitor astVisitor) { if (astVisitor == null) { - throw PSTraceSource.NewArgumentNullException("astVisitor"); + throw PSTraceSource.NewArgumentNullException(nameof(astVisitor)); } return this.Accept(astVisitor); @@ -133,7 +135,7 @@ public void Visit(AstVisitor astVisitor) { if (astVisitor == null) { - throw PSTraceSource.NewArgumentNullException("astVisitor"); + throw PSTraceSource.NewArgumentNullException(nameof(astVisitor)); } this.InternalVisit(astVisitor); @@ -149,7 +151,7 @@ public IEnumerable FindAll(Func predicate, bool searchNestedScri { if (predicate == null) { - throw PSTraceSource.NewArgumentNullException("predicate"); + throw PSTraceSource.NewArgumentNullException(nameof(predicate)); } return AstSearcher.FindAll(this, predicate, searchNestedScriptBlocks); @@ -165,7 +167,7 @@ public Ast Find(Func predicate, bool searchNestedScriptBlocks) { if (predicate == null) { - throw PSTraceSource.NewArgumentNullException("predicate"); + throw PSTraceSource.NewArgumentNullException(nameof(predicate)); } return AstSearcher.FindFirst(this, predicate, searchNestedScriptBlocks); @@ -286,7 +288,7 @@ internal void ClearParent() internal abstract object Accept(ICustomAstVisitor visitor); internal abstract AstVisitAction InternalVisit(AstVisitor visitor); - internal static PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); + internal static readonly PSTypeName[] EmptyPSTypeNameArray = Array.Empty(); internal bool IsInWorkflow() { @@ -449,7 +451,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable ne { if (kind == null) { - throw PSTraceSource.NewArgumentNullException("kind"); + throw PSTraceSource.NewArgumentNullException(nameof(kind)); } Kind = kind; @@ -465,7 +467,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable EmptySnapinCollection = Utils.EmptyReadOnlyCollection(); + internal static readonly ReadOnlyCollection EmptyAssemblyCollection = Utils.EmptyReadOnlyCollection(); + internal static readonly ReadOnlyCollection EmptyModuleCollection = Utils.EmptyReadOnlyCollection(); + internal static readonly ReadOnlyCollection EmptyEditionCollection = Utils.EmptyReadOnlyCollection(); @@ -760,6 +765,7 @@ public class ScriptBlockAst : Ast, IParameterMetadataProvider { private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyUsingStatementList = Utils.EmptyReadOnlyCollection(); @@ -1019,7 +1025,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable using if (statements == null) { - throw PSTraceSource.NewArgumentNullException("statements"); + throw PSTraceSource.NewArgumentNullException(nameof(statements)); } if (paramBlock != null) @@ -1238,7 +1244,7 @@ internal string ToStringForSerialization(Tuple, stri string varSign = varAst.Splatted ? "@" : "$"; string newVarName = varSign + UsingExpressionAst.UsingPrefix + varName; - newScript.Append(script.Substring(startOffset, astStartOffset - startOffset)); + newScript.Append(script.AsSpan(startOffset, astStartOffset - startOffset)); newScript.Append(newVarName); startOffset = astEndOffset; } @@ -1259,13 +1265,13 @@ internal string ToStringForSerialization(Tuple, stri newParams += ",\n"; } - newScript.Append(script.Substring(startOffset, currentOffset - startOffset)); + newScript.Append(script.AsSpan(startOffset, currentOffset - startOffset)); newScript.Append(newParams); startOffset = currentOffset; } } - newScript.Append(script.Substring(startOffset, endOffset - startOffset)); + newScript.Append(script.AsSpan(startOffset, endOffset - startOffset)); string result = newScript.ToString(); if (Parent != null && initialStartOffset == this.Extent.StartOffset && initialEndOffset == this.Extent.EndOffset) @@ -1603,6 +1609,7 @@ public class ParamBlockAst : Ast { private static readonly ReadOnlyCollection s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyParameterList = Utils.EmptyReadOnlyCollection(); @@ -1753,12 +1760,12 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs if (!blockName.HasTrait(TokenFlags.ScriptBlockBlockName) || (unnamed && (blockName == TokenKind.Begin || blockName == TokenKind.Dynamicparam))) { - throw PSTraceSource.NewArgumentException("blockName"); + throw PSTraceSource.NewArgumentException(nameof(blockName)); } if (statementBlock == null) { - throw PSTraceSource.NewArgumentNullException("statementBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(statementBlock)); } this.Unnamed = unnamed; @@ -1901,12 +1908,12 @@ public NamedAttributeArgumentAst(IScriptExtent extent, string argumentName, Expr { if (string.IsNullOrEmpty(argumentName)) { - throw PSTraceSource.NewArgumentNullException("argumentName"); + throw PSTraceSource.NewArgumentNullException(nameof(argumentName)); } if (argument == null) { - throw PSTraceSource.NewArgumentNullException("argument"); + throw PSTraceSource.NewArgumentNullException(nameof(argument)); } this.Argument = argument; @@ -1979,7 +1986,7 @@ protected AttributeBaseAst(IScriptExtent extent, ITypeName typeName) { if (typeName == null) { - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } this.TypeName = typeName; @@ -2000,6 +2007,7 @@ public class AttributeAst : AttributeBaseAst { private static readonly ReadOnlyCollection s_emptyPositionalArguments = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyNamedAttributeArguments = Utils.EmptyReadOnlyCollection(); @@ -2190,7 +2198,7 @@ public ParameterAst(IScriptExtent extent, { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (attributes != null) @@ -2304,7 +2312,7 @@ internal string GetParamTextWithDollarUsingHandling(IEnumerator s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyMembersCollection = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyBaseTypesCollection = Utils.EmptyReadOnlyCollection(); @@ -2533,7 +2543,7 @@ public TypeDefinitionAst(IScriptExtent extent, string name, IEnumerable s_emptyAttributeList = Utils.EmptyReadOnlyCollection(); + private static readonly ReadOnlyCollection s_emptyParameterList = Utils.EmptyReadOnlyCollection(); @@ -3205,13 +3216,13 @@ public FunctionMemberAst(IScriptExtent extent, FunctionDefinitionAst functionDef { if (functionDefinitionAst == null) { - throw PSTraceSource.NewArgumentNullException("functionDefinitionAst"); + throw PSTraceSource.NewArgumentNullException(nameof(functionDefinitionAst)); } if ((methodAttributes & (MethodAttributes.Private | MethodAttributes.Public)) == (MethodAttributes.Private | MethodAttributes.Public)) { - throw PSTraceSource.NewArgumentException("methodAttributes"); + throw PSTraceSource.NewArgumentException(nameof(methodAttributes)); } if (returnType != null) @@ -3582,17 +3593,17 @@ public FunctionDefinitionAst(IScriptExtent extent, { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } if (isFilter && isWorkflow) { - throw PSTraceSource.NewArgumentException("isFilter"); + throw PSTraceSource.NewArgumentException(nameof(isFilter)); } this.IsFilter = isFilter; @@ -3687,7 +3698,7 @@ public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenC { if (scriptBlockTokenCache == null) { - throw new ArgumentNullException("scriptBlockTokenCache"); + throw new ArgumentNullException(nameof(scriptBlockTokenCache)); } var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); @@ -3890,7 +3901,7 @@ public IfStatementAst(IScriptExtent extent, IEnumerable clauses, State { if (clauses == null || !clauses.Any()) { - throw PSTraceSource.NewArgumentException("clauses"); + throw PSTraceSource.NewArgumentException(nameof(clauses)); } this.Clauses = new ReadOnlyCollection(clauses.ToArray()); @@ -3995,7 +4006,7 @@ public DataStatementAst(IScriptExtent extent, { if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } if (string.IsNullOrWhiteSpace(variableName)) @@ -4137,7 +4148,7 @@ protected LoopStatementAst(IScriptExtent extent, string label, PipelineBaseAst c { if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } this.Body = body; @@ -4404,7 +4415,7 @@ public DoWhileStatementAst(IScriptExtent extent, string label, PipelineBaseAst c { if (condition == null) { - throw PSTraceSource.NewArgumentNullException("condition"); + throw PSTraceSource.NewArgumentNullException(nameof(condition)); } } @@ -4460,7 +4471,7 @@ public DoUntilStatementAst(IScriptExtent extent, string label, PipelineBaseAst c { if (condition == null) { - throw PSTraceSource.NewArgumentNullException("condition"); + throw PSTraceSource.NewArgumentNullException(nameof(condition)); } } @@ -4516,7 +4527,7 @@ public WhileStatementAst(IScriptExtent extent, string label, PipelineBaseAst con { if (condition == null) { - throw PSTraceSource.NewArgumentNullException("condition"); + throw PSTraceSource.NewArgumentNullException(nameof(condition)); } } @@ -4636,7 +4647,7 @@ public SwitchStatementAst(IScriptExtent extent, { // Must specify either clauses or default. If neither, just complain about clauses as that's the most likely // invalid argument. - throw PSTraceSource.NewArgumentException("clauses"); + throw PSTraceSource.NewArgumentException(nameof(clauses)); } this.Flags = flags; @@ -4752,7 +4763,7 @@ public CatchClauseAst(IScriptExtent extent, IEnumerable catch { if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } if (catchTypes != null) @@ -4855,13 +4866,13 @@ public TryStatementAst(IScriptExtent extent, { if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } if ((catchClauses == null || !catchClauses.Any()) && @finally == null) { // If no catches and no finally, just complain about catchClauses as that's the most likely invalid argument. - throw PSTraceSource.NewArgumentException("catchClauses"); + throw PSTraceSource.NewArgumentException(nameof(catchClauses)); } this.Body = body; @@ -4964,7 +4975,7 @@ public TrapStatementAst(IScriptExtent extent, TypeConstraintAst trapType, Statem { if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } if (trapType != null) @@ -5520,7 +5531,7 @@ public PipelineAst(IScriptExtent extent, IEnumerable pipelineEle { if (pipelineElements == null || !pipelineElements.Any()) { - throw PSTraceSource.NewArgumentException("pipelineElements"); + throw PSTraceSource.NewArgumentException(nameof(pipelineElements)); } this.Background = background; @@ -5557,7 +5568,7 @@ public PipelineAst(IScriptExtent extent, CommandBaseAst commandAst, bool backgro { if (commandAst == null) { - throw PSTraceSource.NewArgumentNullException("commandAst"); + throw PSTraceSource.NewArgumentNullException(nameof(commandAst)); } this.Background = background; @@ -5830,12 +5841,12 @@ public CommandAst(IScriptExtent extent, { if (commandElements == null || !commandElements.Any()) { - throw PSTraceSource.NewArgumentException("commandElements"); + throw PSTraceSource.NewArgumentException(nameof(commandElements)); } if (invocationOperator != TokenKind.Dot && invocationOperator != TokenKind.Ampersand && invocationOperator != TokenKind.Unknown) { - throw PSTraceSource.NewArgumentException("invocationOperator"); + throw PSTraceSource.NewArgumentException(nameof(invocationOperator)); } this.CommandElements = new ReadOnlyCollection(commandElements.ToArray()); @@ -5951,7 +5962,7 @@ public CommandExpressionAst(IScriptExtent extent, { if (expression == null) { - throw PSTraceSource.NewArgumentNullException("expression"); + throw PSTraceSource.NewArgumentNullException(nameof(expression)); } this.Expression = expression; @@ -6144,7 +6155,7 @@ public FileRedirectionAst(IScriptExtent extent, RedirectionStream stream, Expres { if (file == null) { - throw PSTraceSource.NewArgumentNullException("file"); + throw PSTraceSource.NewArgumentNullException(nameof(file)); } this.Location = file; @@ -6220,7 +6231,7 @@ public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKin if ((@operator.GetTraits() & TokenFlags.AssignmentOperator) == 0) { - throw PSTraceSource.NewArgumentException("operator"); + throw PSTraceSource.NewArgumentException(nameof(@operator)); } // If the assignment is just an expression and the expression is not backgrounded then @@ -6361,17 +6372,17 @@ public ConfigurationDefinitionAst(IScriptExtent extent, { if (extent == null) { - throw PSTraceSource.NewArgumentNullException("extent"); + throw PSTraceSource.NewArgumentNullException(nameof(extent)); } if (body == null) { - throw PSTraceSource.NewArgumentNullException("body"); + throw PSTraceSource.NewArgumentNullException(nameof(body)); } if (instanceName == null) { - throw PSTraceSource.NewArgumentNullException("instanceName"); + throw PSTraceSource.NewArgumentNullException(nameof(instanceName)); } this.Body = body; @@ -6643,17 +6654,17 @@ private static bool IsImportCommand(StatementAst stmt, List ConfigurationBuildInParameters } private static List s_configurationBuildInParameters; + private static IEnumerable ConfigurationBuildInParameterAttribAsts { get @@ -6842,7 +6854,7 @@ public DynamicKeywordStatementAst(IScriptExtent extent, { if (commandElements == null || commandElements.Count() <= 0) { - throw PSTraceSource.NewArgumentException("commandElements"); + throw PSTraceSource.NewArgumentException(nameof(commandElements)); } this.CommandElements = new ReadOnlyCollection(commandElements.ToArray()); @@ -6931,6 +6943,7 @@ internal DynamicKeyword Keyword } private DynamicKeyword _keyword; + internal Token LCurly { get; set; } internal Token FunctionName { get; set; } internal ExpressionAst InstanceName { get; set; } @@ -6939,6 +6952,7 @@ internal DynamicKeyword Keyword internal string ElementName { get; set; } private PipelineAst _commandCallPipelineAst; + internal PipelineAst GenerateCommandCallPipelineAst() { if (_commandCallPipelineAst != null) @@ -7348,7 +7362,7 @@ public BinaryExpressionAst(IScriptExtent extent, ExpressionAst left, TokenKind @ { if ((@operator.GetTraits() & TokenFlags.BinaryOperator) == 0) { - throw PSTraceSource.NewArgumentException("operator"); + throw PSTraceSource.NewArgumentException(nameof(@operator)); } if (left == null || right == null || errorPosition == null) @@ -7461,12 +7475,12 @@ public UnaryExpressionAst(IScriptExtent extent, TokenKind tokenKind, ExpressionA { if ((tokenKind.GetTraits() & TokenFlags.UnaryOperator) == 0) { - throw PSTraceSource.NewArgumentException("tokenKind"); + throw PSTraceSource.NewArgumentException(nameof(tokenKind)); } if (child == null) { - throw PSTraceSource.NewArgumentNullException("child"); + throw PSTraceSource.NewArgumentNullException(nameof(child)); } this.TokenKind = tokenKind; @@ -7548,7 +7562,7 @@ public BlockStatementAst(IScriptExtent extent, Token kind, StatementBlockAst bod if (kind.Kind != TokenKind.Sequence && kind.Kind != TokenKind.Parallel) { - throw PSTraceSource.NewArgumentException("kind"); + throw PSTraceSource.NewArgumentException(nameof(kind)); } this.Kind = kind; @@ -8179,7 +8193,7 @@ public TypeName(IScriptExtent extent, string name) var c = name[0]; if (c == '[' || c == ']' || c == ',') { - throw PSTraceSource.NewArgumentException("name"); + throw PSTraceSource.NewArgumentException(nameof(name)); } int backtick = name.IndexOf('`'); @@ -8209,7 +8223,7 @@ public TypeName(IScriptExtent extent, string name, string assembly) { if (string.IsNullOrEmpty(assembly)) { - throw PSTraceSource.NewArgumentNullException("assembly"); + throw PSTraceSource.NewArgumentNullException(nameof(assembly)); } AssemblyName = assembly; @@ -8401,7 +8415,7 @@ internal bool IsType(Type type) int lastDotIndex = fullTypeName.LastIndexOf('.'); if (lastDotIndex >= 0) { - return fullTypeName.Substring(lastDotIndex + 1).Equals(Name, StringComparison.OrdinalIgnoreCase); + return fullTypeName.AsSpan(lastDotIndex + 1).Equals(Name, StringComparison.OrdinalIgnoreCase); } return false; @@ -8449,7 +8463,7 @@ public GenericTypeName(IScriptExtent extent, ITypeName genericTypeName, IEnumera if (genericArguments == null) { - throw PSTraceSource.NewArgumentException("genericArguments"); + throw PSTraceSource.NewArgumentException(nameof(genericArguments)); } Extent = extent; @@ -8458,7 +8472,7 @@ public GenericTypeName(IScriptExtent extent, ITypeName genericTypeName, IEnumera if (this.GenericArguments.Count == 0) { - throw PSTraceSource.NewArgumentException("genericArguments"); + throw PSTraceSource.NewArgumentException(nameof(genericArguments)); } } @@ -8746,7 +8760,7 @@ public ArrayTypeName(IScriptExtent extent, ITypeName elementType, int rank) if (rank <= 0) { - throw PSTraceSource.NewArgumentException("rank"); + throw PSTraceSource.NewArgumentException(nameof(rank)); } Extent = extent; @@ -8941,7 +8955,7 @@ public ReflectionTypeName(Type type) { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } _type = type; @@ -9042,7 +9056,7 @@ public TypeExpressionAst(IScriptExtent extent, ITypeName typeName) { if (typeName == null) { - throw PSTraceSource.NewArgumentNullException("typeName"); + throw PSTraceSource.NewArgumentNullException(nameof(typeName)); } this.TypeName = typeName; @@ -9107,7 +9121,7 @@ public VariableExpressionAst(IScriptExtent extent, string variableName, bool spl { if (string.IsNullOrEmpty(variableName)) { - throw PSTraceSource.NewArgumentNullException("variableName"); + throw PSTraceSource.NewArgumentNullException(nameof(variableName)); } this.VariablePath = new VariablePath(variableName); @@ -9134,7 +9148,7 @@ public VariableExpressionAst(IScriptExtent extent, VariablePath variablePath, bo { if (variablePath == null) { - throw PSTraceSource.NewArgumentNullException("variablePath"); + throw PSTraceSource.NewArgumentNullException(nameof(variablePath)); } this.VariablePath = variablePath; @@ -9429,7 +9443,7 @@ public StringConstantExpressionAst(IScriptExtent extent, string value, StringCon { if (value == null) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } this.StringConstantType = stringConstantType; @@ -9529,13 +9543,13 @@ public ExpandableStringExpressionAst(IScriptExtent extent, { if (value == null) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } if (type != StringConstantType.DoubleQuoted && type != StringConstantType.DoubleQuotedHereString && type != StringConstantType.BareWord) { - throw PSTraceSource.NewArgumentException("type"); + throw PSTraceSource.NewArgumentException(nameof(type)); } var ast = Language.Parser.ScanString(value); @@ -9676,7 +9690,7 @@ public ScriptBlockExpressionAst(IScriptExtent extent, ScriptBlockAst scriptBlock { if (scriptBlock == null) { - throw PSTraceSource.NewArgumentNullException("scriptBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } this.ScriptBlock = scriptBlock; @@ -9748,7 +9762,7 @@ public ArrayLiteralAst(IScriptExtent extent, IList elements) { if (elements == null || !elements.Any()) { - throw PSTraceSource.NewArgumentException("elements"); + throw PSTraceSource.NewArgumentException(nameof(elements)); } this.Elements = new ReadOnlyCollection(elements); @@ -9921,7 +9935,7 @@ public ArrayExpressionAst(IScriptExtent extent, StatementBlockAst statementBlock { if (statementBlock == null) { - throw PSTraceSource.NewArgumentNullException("statementBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(statementBlock)); } this.SubExpression = statementBlock; @@ -9987,7 +10001,7 @@ public ParenExpressionAst(IScriptExtent extent, PipelineBaseAst pipeline) { if (pipeline == null) { - throw PSTraceSource.NewArgumentNullException("pipeline"); + throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } this.Pipeline = pipeline; @@ -10053,7 +10067,7 @@ public SubExpressionAst(IScriptExtent extent, StatementBlockAst statementBlock) { if (statementBlock == null) { - throw PSTraceSource.NewArgumentNullException("statementBlock"); + throw PSTraceSource.NewArgumentNullException(nameof(statementBlock)); } this.SubExpression = statementBlock; @@ -10113,7 +10127,7 @@ public UsingExpressionAst(IScriptExtent extent, ExpressionAst expressionAst) { if (expressionAst == null) { - throw PSTraceSource.NewArgumentNullException("expressionAst"); + throw PSTraceSource.NewArgumentNullException(nameof(expressionAst)); } RuntimeUsingIndex = -1; @@ -10163,7 +10177,7 @@ public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usin { if (usingExpressionAst == null) { - throw new ArgumentNullException("usingExpressionAst"); + throw new ArgumentNullException(nameof(usingExpressionAst)); } return ExtractUsingVariableImpl(usingExpressionAst); diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index e9575ebe720..3f78e299a88 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -585,6 +585,9 @@ public enum TokenKind /// The 'base' keyword Base = 168, + /// The 'default' keyword + Default = 169, + #endregion Keywords } @@ -944,6 +947,7 @@ public static class TokenTraits /* Command */ TokenFlags.Keyword, /* Hidden */ TokenFlags.Keyword, /* Base */ TokenFlags.Keyword, + /* Default */ TokenFlags.Keyword, #endregion Flags for keywords }; @@ -1142,6 +1146,7 @@ public static class TokenTraits /* Command */ "command", /* Hidden */ "hidden", /* Base */ "base", + /* Default */ "default", #endregion Text for keywords }; @@ -1149,9 +1154,9 @@ public static class TokenTraits #if DEBUG static TokenTraits() { - Diagnostics.Assert(s_staticTokenFlags.Length == ((int)TokenKind.Base + 1), + Diagnostics.Assert(s_staticTokenFlags.Length == ((int)TokenKind.Default + 1), "Table size out of sync with enum - _staticTokenFlags"); - Diagnostics.Assert(s_tokenText.Length == ((int)TokenKind.Base + 1), + Diagnostics.Assert(s_tokenText.Length == ((int)TokenKind.Default + 1), "Table size out of sync with enum - _tokenText"); // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index e11d7f8de7d..6c956607e10 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -153,7 +153,7 @@ public static bool ContainsKeyword(string name) { if (string.IsNullOrEmpty(name)) { - PSArgumentNullException e = PSTraceSource.NewArgumentNullException("name"); + PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name)); throw e; } @@ -167,7 +167,7 @@ public static void AddKeyword(DynamicKeyword keywordToAdd) { if (keywordToAdd == null) { - PSArgumentNullException e = PSTraceSource.NewArgumentNullException("keywordToAdd"); + PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(keywordToAdd)); throw e; } @@ -191,7 +191,7 @@ public static void RemoveKeyword(string name) { if (string.IsNullOrEmpty(name)) { - PSArgumentNullException e = PSTraceSource.NewArgumentNullException("name"); + PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name)); throw e; } @@ -207,7 +207,7 @@ internal static bool IsHiddenKeyword(string name) { if (string.IsNullOrEmpty(name)) { - PSArgumentNullException e = PSTraceSource.NewArgumentNullException("name"); + PSArgumentNullException e = PSTraceSource.NewArgumentNullException(nameof(name)); throw e; } @@ -543,7 +543,7 @@ internal enum NumberSuffixFlags Decimal = 0x10, /// - /// Indicates 'I' suffix for BigInteger (arbitrarily large integer) numerals. + /// Indicates 'N' suffix for BigInteger (arbitrarily large integer) numerals. /// BigInteger = 0x20 } @@ -590,6 +590,7 @@ internal class Tokenizer { private static readonly Dictionary s_keywordTable = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary s_operatorTable = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -628,7 +629,7 @@ private static readonly Dictionary s_operatorTable /*A*/ "configuration", "public", "private", "static", /*A*/ /*B*/ "interface", "enum", "namespace", "module", /*B*/ /*C*/ "type", "assembly", "command", "hidden", /*C*/ - /*D*/ "base", /*D*/ + /*D*/ "base", "default", /*D*/ }; private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] { @@ -644,7 +645,7 @@ private static readonly Dictionary s_operatorTable /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ - /*D*/ TokenKind.Base, /*D*/ + /*D*/ TokenKind.Base, TokenKind.Default, /*D*/ }; internal static readonly string[] _operatorText = new string[] { @@ -724,6 +725,7 @@ internal Tokenizer(Parser parser) // TODO: use auto-properties when making 'ternary operator' an official feature. private bool _forceEndNumberOnTernaryOpChars; + internal bool ForceEndNumberOnTernaryOpChars { get { return _forceEndNumberOnTernaryOpChars; } @@ -1460,17 +1462,28 @@ private char Backtick(char c, out char surrogateCharacter) switch (c) { - case '0': return '\0'; - case 'a': return '\a'; - case 'b': return '\b'; - case 'e': return '\u001b'; - case 'f': return '\f'; - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'u': return ScanUnicodeEscape(out surrogateCharacter); - case 'v': return '\v'; - default: return c; + case '0': + return '\0'; + case 'a': + return '\a'; + case 'b': + return '\b'; + case 'e': + return '\u001b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'u': + return ScanUnicodeEscape(out surrogateCharacter); + case 'v': + return '\v'; + default: + return c; } } @@ -3557,8 +3570,9 @@ private static bool TryGetNumberValue( { try { - NumberStyles style = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | - NumberStyles.AllowExponent; + NumberStyles style = NumberStyles.AllowLeadingSign + | NumberStyles.AllowDecimalPoint + | NumberStyles.AllowExponent; if (real) { @@ -3685,9 +3699,21 @@ private static bool TryGetNumberValue( } // If we're expecting a sign bit, remove the leading 0 added in ScanNumberHelper - if (!suffix.HasFlag(NumberSuffixFlags.Unsigned) && ((strNum.Length - 1) & 7) == 0) + if (!suffix.HasFlag(NumberSuffixFlags.Unsigned)) { - strNum = strNum.Slice(1); + var expectedLength = suffix switch + { + NumberSuffixFlags.SignedByte => 2, + NumberSuffixFlags.Short => 4, + NumberSuffixFlags.Long => 16, + // No suffix flag can mean int or long depending on input string length + _ => strNum.Length < 16 ? 8 : 16 + }; + + if (strNum.Length == expectedLength + 1) + { + strNum = strNum.Slice(1); + } } style = NumberStyles.AllowHexSpecifier; @@ -4217,7 +4243,6 @@ internal Token GetMemberAccessOperator(bool allowLBracket) return NewToken(TokenKind.LBracket); } - if (ExperimentalFeature.IsEnabled("PSNullConditionalOperators") && c == '?') { _tokenStart = _currentIndex; @@ -4988,7 +5013,10 @@ internal Token NextToken() _currentIndex = _tokenStart; c = GetChar(); - if (strNum == null) { return ScanGenericToken(c); } + if (strNum == null) + { + return ScanGenericToken(c); + } } return NewToken(TokenKind.Exclaim); diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 4c509970309..8b1779de882 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -156,6 +156,7 @@ internal void LogExecutionError(InvocationInfo invocationInfo, ErrorRecord error } private bool _terminatingErrorLogged = false; + internal void LogExecutionException(Exception exception) { _executionFailed = true; @@ -239,7 +240,7 @@ internal void LogToEventLog() { // We check to see if the command is needs writing (or if there is anything in the buffer) // before we flush it. Flushing the empty buffer causes a measurable performance degradation. - if (_commands == null || _commands.Count <= 0 || _eventLogBuffer.Count == 0) + if (_commands == null || _commands.Count == 0 || _eventLogBuffer.Count == 0) return; MshLog.LogPipelineExecutionDetailEvent(_commands[0].Command.Context, @@ -285,7 +286,7 @@ internal int Add(CommandProcessorBase commandProcessor) internal void AddRedirectionPipe(PipelineProcessor pipelineProcessor) { - if (pipelineProcessor == null) throw PSTraceSource.NewArgumentNullException("pipelineProcessor"); + if (pipelineProcessor == null) throw PSTraceSource.NewArgumentNullException(nameof(pipelineProcessor)); if (_redirectionPipes == null) _redirectionPipes = new List(); _redirectionPipes.Add(pipelineProcessor); @@ -317,7 +318,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma { if (commandProcessor == null) { - throw PSTraceSource.NewArgumentNullException("commandProcessor"); + throw PSTraceSource.NewArgumentNullException(nameof(commandProcessor)); } if (_commands == null) @@ -349,7 +350,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma { // "First command cannot have input" throw PSTraceSource.NewArgumentException( - "readFromCommand", + nameof(readFromCommand), PipelineStrings.FirstCommandCannotHaveInput); } @@ -360,7 +361,7 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma { // "invalid command number" throw PSTraceSource.NewArgumentException( - "readFromCommand", + nameof(readFromCommand), PipelineStrings.InvalidCommandNumber); } else @@ -1559,6 +1560,7 @@ internal bool Stopping } private LocalPipeline _localPipeline; + internal LocalPipeline LocalPipeline { get { return _localPipeline; } diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 2c4ade7cb5f..c867f355158 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -125,7 +125,7 @@ public WildcardPattern(string pattern, WildcardOptions options) public static WildcardPattern Get(string pattern, WildcardOptions options) { if (pattern == null) - throw PSTraceSource.NewArgumentNullException("pattern"); + throw PSTraceSource.NewArgumentNullException(nameof(pattern)); if (pattern.Length == 1 && pattern[0] == '*') return s_matchAllIgnoreCasePattern; @@ -449,7 +449,7 @@ internal WildcardPatternException(ErrorRecord errorRecord) { if (errorRecord == null) { - throw new ArgumentNullException("errorRecord"); + throw new ArgumentNullException(nameof(errorRecord)); } _errorRecord = errorRecord; @@ -752,6 +752,7 @@ internal class WildcardPatternToRegexParser : WildcardPatternParser private RegexOptions _regexOptions; private const string regexChars = "()[.?*{}^$+|\\"; // ']' is missing on purpose + private static bool IsRegexChar(char ch) { for (int i = 0; i < regexChars.Length; i++) diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index 7101e7ffb7a..ba4e08c8f6f 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; @@ -238,7 +238,7 @@ internal void ExecuteVoid(Action writeErrorAction) // Create an error record and write it to the stream. ErrorRecord errorRecord = new ErrorRecord( exception, - PSRemotingErrorId.RemoteHostCallFailed.ToString(), + nameof(PSRemotingErrorId.RemoteHostCallFailed), ErrorCategory.InvalidArgument, _remoteHostCall.MethodName); writeErrorAction(errorRecord); diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 07bfd126b88..4f966f5bdba 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -251,24 +251,17 @@ internal void Initialize( dataStructureHandler = runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this); // register for events from the data structure handler - dataStructureHandler.InvocationStateInfoReceived += - new EventHandler>(HandleInvocationStateInfoReceived); - dataStructureHandler.OutputReceived += new EventHandler>(HandleOutputReceived); - dataStructureHandler.ErrorReceived += new EventHandler>(HandleErrorReceived); - dataStructureHandler.InformationalMessageReceived += - new EventHandler>(HandleInformationalMessageReceived); - dataStructureHandler.HostCallReceived += - new EventHandler>(HandleHostCallReceived); - dataStructureHandler.ClosedNotificationFromRunspacePool += - new EventHandler>(HandleCloseNotificationFromRunspacePool); - dataStructureHandler.BrokenNotificationFromRunspacePool += - new EventHandler>(HandleBrokenNotificationFromRunspacePool); - dataStructureHandler.ConnectCompleted += new EventHandler>(HandleConnectCompleted); - dataStructureHandler.ReconnectCompleted += new EventHandler>(HandleConnectCompleted); - dataStructureHandler.RobustConnectionNotification += - new EventHandler(HandleRobustConnectionNotification); - dataStructureHandler.CloseCompleted += - new EventHandler(HandleCloseCompleted); + dataStructureHandler.InvocationStateInfoReceived += HandleInvocationStateInfoReceived; + dataStructureHandler.OutputReceived += HandleOutputReceived; + dataStructureHandler.ErrorReceived += HandleErrorReceived; + dataStructureHandler.InformationalMessageReceived += HandleInformationalMessageReceived; + dataStructureHandler.HostCallReceived += HandleHostCallReceived; + dataStructureHandler.ClosedNotificationFromRunspacePool += HandleCloseNotificationFromRunspacePool; + dataStructureHandler.BrokenNotificationFromRunspacePool += HandleBrokenNotificationFromRunspacePool; + dataStructureHandler.ConnectCompleted += HandleConnectCompleted; + dataStructureHandler.ReconnectCompleted += HandleConnectCompleted; + dataStructureHandler.RobustConnectionNotification += HandleRobustConnectionNotification; + dataStructureHandler.CloseCompleted += HandleCloseCompleted; } /// @@ -924,10 +917,12 @@ private void HandleRobustConnectionNotification( protected bool stopCalled = false; protected PSHost hostToUse; protected RemoteRunspacePoolInternal runspacePool; + protected const string WRITE_DEBUG_LINE = "WriteDebugLine"; protected const string WRITE_VERBOSE_LINE = "WriteVerboseLine"; protected const string WRITE_WARNING_LINE = "WriteWarningLine"; protected const string WRITE_PROGRESS = "WriteProgress"; + protected bool initialized = false; /// /// This queue is for the state change events that resulted in closing the underlying diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 6ff1f9953e1..e8453457f47 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -333,7 +333,7 @@ public JobStateEventArgs(JobStateInfo jobStateInfo, JobStateInfo previousJobStat { if (jobStateInfo == null) { - throw PSTraceSource.NewArgumentNullException("jobStateInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(jobStateInfo)); } JobStateInfo = jobStateInfo; @@ -366,7 +366,7 @@ public sealed class JobIdentifier internal JobIdentifier(int id, Guid instanceId) { if (id <= 0) - PSTraceSource.NewArgumentException("id", RemotingErrorIdStrings.JobSessionIdLessThanOne, id); + PSTraceSource.NewArgumentException(nameof(id), RemotingErrorIdStrings.JobSessionIdLessThanOne, id); Id = id; InstanceId = instanceId; } @@ -463,10 +463,10 @@ protected Job(string command, string name, IList childJobs) protected Job(string command, string name, JobIdentifier token) { if (token == null) - throw PSTraceSource.NewArgumentNullException("token", RemotingErrorIdStrings.JobIdentifierNull); + throw PSTraceSource.NewArgumentNullException(nameof(token), RemotingErrorIdStrings.JobIdentifierNull); if (token.Id > s_jobIdSeed) { - throw PSTraceSource.NewArgumentException("token", RemotingErrorIdStrings.JobIdNotYetAssigned, token.Id); + throw PSTraceSource.NewArgumentException(nameof(token), RemotingErrorIdStrings.JobIdNotYetAssigned, token.Id); } Command = command; @@ -510,7 +510,7 @@ internal static string GetCommandTextFromInvocationInfo(InvocationInfo invocatio { Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber > 0, "Column numbers start at 1"); Dbg.Assert(scriptExtent.StartScriptPosition.ColumnNumber <= scriptExtent.StartScriptPosition.Line.Length, "Column numbers are not greater than the length of a line"); - return scriptExtent.StartScriptPosition.Line.Substring(scriptExtent.StartScriptPosition.ColumnNumber - 1).Trim(); + return scriptExtent.StartScriptPosition.Line.AsSpan(scriptExtent.StartScriptPosition.ColumnNumber - 1).Trim().ToString(); } return invocationInfo.InvocationName; @@ -831,6 +831,7 @@ internal virtual void WriteInformation(InformationRecord informationRecord) } private Lazy _parentActivityId; + internal void SetParentActivityIdGetter(Func parentActivityIdGetter) { Dbg.Assert(parentActivityIdGetter != null, "Caller should verify parentActivityIdGetter != null"); @@ -1787,8 +1788,8 @@ internal PSRemotingJob(string[] computerNames, // Create Child Job and Register for its StateChanged Event PSRemotingChildJob childJob = new PSRemotingChildJob(remoteCommand, helper, _throttleManager); - childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); - childJob.JobUnblocked += new EventHandler(HandleJobUnblocked); + childJob.StateChanged += HandleChildJobStateChanged; + childJob.JobUnblocked += HandleJobUnblocked; // Add this job to list of childjobs ChildJobs.Add(childJob); @@ -1822,8 +1823,8 @@ internal PSRemotingJob(PSSession[] remoteRunspaceInfos, // Create Child Job object and Register for its state changed event PSRemotingChildJob job = new PSRemotingChildJob(remoteCommand, helper, _throttleManager); - job.StateChanged += new EventHandler(HandleChildJobStateChanged); - job.JobUnblocked += new EventHandler(HandleJobUnblocked); + job.StateChanged += HandleChildJobStateChanged; + job.JobUnblocked += HandleJobUnblocked; // Add the child job to list of child jobs ChildJobs.Add(job); @@ -1852,8 +1853,8 @@ internal PSRemotingJob(List helpers, foreach (ExecutionCmdletHelper helper in helpers) { PSRemotingChildJob job = new PSRemotingChildJob(helper, _throttleManager, aggregateResults); - job.StateChanged += new EventHandler(HandleChildJobStateChanged); - job.JobUnblocked += new EventHandler(HandleJobUnblocked); + job.StateChanged += HandleChildJobStateChanged; + job.JobUnblocked += HandleJobUnblocked; ChildJobs.Add(job); } @@ -2462,7 +2463,7 @@ private void HandleChildJobStateChanged(object sender, JobStateEventArgs e) { SetJobState(JobState.Failed); } - else if (_stopIsCalled == true) + else if (_stopIsCalled) { SetJobState(JobState.Stopped); } @@ -2684,7 +2685,7 @@ internal class DisconnectedJobOperation : ExecutionCmdletHelper internal DisconnectedJobOperation(Pipeline pipeline) { this.pipeline = pipeline; - this.pipeline.StateChanged += new EventHandler(HandlePipelineStateChanged); + this.pipeline.StateChanged += HandlePipelineStateChanged; } internal override void StartOperation() @@ -2813,15 +2814,15 @@ internal PSRemotingChildJob(ExecutionCmdletHelper helper, ThrottleManager thrott } else { - _remotePipeline.StateChanged += new EventHandler(HandlePipelineStateChanged); - _remotePipeline.Output.DataReady += new EventHandler(HandleOutputReady); - _remotePipeline.Error.DataReady += new EventHandler(HandleErrorReady); + _remotePipeline.StateChanged += HandlePipelineStateChanged; + _remotePipeline.Output.DataReady += HandleOutputReady; + _remotePipeline.Error.DataReady += HandleErrorReady; } Runspace.AvailabilityChanged += HandleRunspaceAvailabilityChanged; IThrottleOperation operation = helper as IThrottleOperation; - operation.OperationComplete += new EventHandler(HandleOperationComplete); + operation.OperationComplete += HandleOperationComplete; SetJobState(JobState.Disconnected, null); } @@ -3240,12 +3241,12 @@ protected virtual void HandleOperationComplete(object sender, OperationStateEven /// protected virtual void DoFinish() { - if (_doFinishCalled == true) + if (_doFinishCalled) return; lock (SyncObject) { - if (_doFinishCalled == true) + if (_doFinishCalled) return; _doFinishCalled = true; @@ -3382,8 +3383,11 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai fullyQualifiedErrorId, ErrorCategory.OpenError, null, null, null, null, null, errorDetails, null); } - else if (pipeline.PipelineStateInfo.State == PipelineState.Failed) + else if ((pipeline.PipelineStateInfo.State == PipelineState.Failed) || + ((pipeline.PipelineStateInfo.State == PipelineState.Stopped) && + (pipeline.PipelineStateInfo.Reason != null && !(pipeline.PipelineStateInfo.Reason is PipelineStoppedException)))) { + // Pipeline stopped state is also an error condition if the associated exception is not 'PipelineStoppedException'. object targetObject = runspace.ConnectionInfo.ComputerName; failureException = pipeline.PipelineStateInfo.Reason; if (failureException != null) @@ -3394,6 +3398,15 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai if (rException != null) { errorRecord = rException.ErrorRecord; + + // A RemoteException will hide a PipelineStoppedException, which should be ignored. + if (errorRecord != null && + errorRecord.FullyQualifiedErrorId.Equals("PipelineStopped", StringComparison.OrdinalIgnoreCase)) + { + // PipelineStoppedException should not be reported as error. + failureException = null; + return; + } } else { @@ -3481,7 +3494,7 @@ protected virtual void DoCleanupOnFinished() StopAggregateResultsFromHelper(Helper); Runspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged; IThrottleOperation operation = Helper as IThrottleOperation; - operation.OperationComplete -= new EventHandler(HandleOperationComplete); + operation.OperationComplete -= HandleOperationComplete; UnregisterThrottleComplete(_throttleManager); _throttleManager = null; } @@ -3496,31 +3509,26 @@ protected void AggregateResultsFromHelper(ExecutionCmdletHelper helper) { // Get the pipeline associated with this helper and register for appropriate events Pipeline pipeline = helper.Pipeline; - pipeline.Output.DataReady += new EventHandler(HandleOutputReady); - pipeline.Error.DataReady += new EventHandler(HandleErrorReady); - pipeline.StateChanged += new EventHandler(HandlePipelineStateChanged); + pipeline.Output.DataReady += HandleOutputReady; + pipeline.Error.DataReady += HandleErrorReady; + pipeline.StateChanged += HandlePipelineStateChanged; // Register handler for method executor object stream. Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline"); RemotePipeline remotePipeline = pipeline as RemotePipeline; - remotePipeline.MethodExecutorStream.DataReady += new EventHandler(HandleHostCalls); - remotePipeline.PowerShell.Streams.Progress.DataAdded += - new EventHandler(HandleProgressAdded); - remotePipeline.PowerShell.Streams.Warning.DataAdded += - new EventHandler(HandleWarningAdded); - remotePipeline.PowerShell.Streams.Verbose.DataAdded += - new EventHandler(HandleVerboseAdded); - remotePipeline.PowerShell.Streams.Debug.DataAdded += - new EventHandler(HandleDebugAdded); - remotePipeline.PowerShell.Streams.Information.DataAdded += - new EventHandler(HandleInformationAdded); + remotePipeline.MethodExecutorStream.DataReady += HandleHostCalls; + remotePipeline.PowerShell.Streams.Progress.DataAdded += HandleProgressAdded; + remotePipeline.PowerShell.Streams.Warning.DataAdded += HandleWarningAdded; + remotePipeline.PowerShell.Streams.Verbose.DataAdded += HandleVerboseAdded; + remotePipeline.PowerShell.Streams.Debug.DataAdded += HandleDebugAdded; + remotePipeline.PowerShell.Streams.Information.DataAdded += HandleInformationAdded; // Enable method executor stream so that host methods are queued up // on it instead of being executed asynchronously when they arrive. remotePipeline.IsMethodExecutorStreamEnabled = true; IThrottleOperation operation = helper as IThrottleOperation; - operation.OperationComplete += new EventHandler(HandleOperationComplete); + operation.OperationComplete += HandleOperationComplete; } /// @@ -3673,19 +3681,14 @@ protected void RemoveAggreateCallbacksFromHelper(ExecutionCmdletHelper helper) // Remove old data aggregation and host calls. Dbg.Assert(pipeline is RemotePipeline, "pipeline is RemotePipeline"); RemotePipeline remotePipeline = pipeline as RemotePipeline; - remotePipeline.MethodExecutorStream.DataReady -= new EventHandler(HandleHostCalls); + remotePipeline.MethodExecutorStream.DataReady -= HandleHostCalls; if (remotePipeline.PowerShell != null) { - remotePipeline.PowerShell.Streams.Progress.DataAdded -= - new EventHandler(HandleProgressAdded); - remotePipeline.PowerShell.Streams.Warning.DataAdded -= - new EventHandler(HandleWarningAdded); - remotePipeline.PowerShell.Streams.Verbose.DataAdded -= - new EventHandler(HandleVerboseAdded); - remotePipeline.PowerShell.Streams.Debug.DataAdded -= - new EventHandler(HandleDebugAdded); - remotePipeline.PowerShell.Streams.Information.DataAdded -= - new EventHandler(HandleInformationAdded); + remotePipeline.PowerShell.Streams.Progress.DataAdded -= HandleProgressAdded; + remotePipeline.PowerShell.Streams.Warning.DataAdded -= HandleWarningAdded; + remotePipeline.PowerShell.Streams.Verbose.DataAdded -= HandleVerboseAdded; + remotePipeline.PowerShell.Streams.Debug.DataAdded -= HandleDebugAdded; + remotePipeline.PowerShell.Streams.Information.DataAdded -= HandleInformationAdded; remotePipeline.IsMethodExecutorStreamEnabled = false; } } @@ -3697,7 +3700,7 @@ protected void RemoveAggreateCallbacksFromHelper(ExecutionCmdletHelper helper) /// protected void RegisterThrottleComplete(ThrottleManager throttleManager) { - throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); + throttleManager.ThrottleComplete += HandleThrottleComplete; } /// @@ -3707,7 +3710,7 @@ protected void RegisterThrottleComplete(ThrottleManager throttleManager) /// protected void UnregisterThrottleComplete(ThrottleManager throttleManager) { - throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); + throttleManager.ThrottleComplete -= HandleThrottleComplete; } /// @@ -3870,12 +3873,12 @@ public RemotingJobDebugger( { if (debugger == null) { - throw new PSArgumentNullException("debugger"); + throw new PSArgumentNullException(nameof(debugger)); } if (runspace == null) { - throw new PSArgumentNullException("runspace"); + throw new PSArgumentNullException(nameof(runspace)); } _wrappedDebugger = debugger; @@ -4374,12 +4377,12 @@ public override void StopJob() /// protected override void DoFinish() { - if (_doFinishCalled == true) + if (_doFinishCalled) return; lock (SyncObject) { - if (_doFinishCalled == true) + if (_doFinishCalled) return; _doFinishCalled = true; diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index d2c3813a4cf..32923806cce 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -502,9 +502,11 @@ public sealed class ContainerParentJob : Job2 #region Private Members private const string TraceClassName = "ContainerParentJob"; + private bool _moreData = true; private readonly object _syncObject = new object(); private int _isDisposed = 0; + private const int DisposedTrue = 1; private const int DisposedFalse = 0; // This variable is set to true if atleast one child job failed. @@ -531,6 +533,7 @@ public sealed class ContainerParentJob : Job2 private readonly PSDataCollection _executionError = new PSDataCollection(); private PSEventManager _eventManager; + internal PSEventManager EventManager { get { return _eventManager; } @@ -543,6 +546,7 @@ internal PSEventManager EventManager } private ManualResetEvent _jobRunning; + private ManualResetEvent JobRunning { get @@ -567,6 +571,7 @@ private ManualResetEvent JobRunning } private ManualResetEvent _jobSuspendedOrAborted; + private ManualResetEvent JobSuspendedOrAborted { get @@ -704,7 +709,7 @@ public void AddChildJob(Job2 childJob) AssertNotDisposed(); if (childJob == null) { - throw new ArgumentNullException("childJob"); + throw new ArgumentNullException(nameof(childJob)); } _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : ", InstanceId.ToString()); @@ -715,7 +720,7 @@ public void AddChildJob(Job2 childJob) // Store job's state and subscribe to State Changed event. Locking here will // ensure that the jobstateinfo we get is the state before any state changed events are handled by ContainerParentJob. childJobStateInfo = childJob.JobStateInfo; - childJob.StateChanged += new EventHandler(HandleChildJobStateChanged); + childJob.StateChanged += HandleChildJobStateChanged; } ChildJobs.Add(childJob); @@ -2181,7 +2186,7 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index a81c5efdeff..6ef47c19752 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -178,7 +178,7 @@ public Job2 NewJob(JobDefinition definition) { if (definition == null) { - throw new ArgumentNullException("definition"); + throw new ArgumentNullException(nameof(definition)); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); @@ -218,12 +218,12 @@ public Job2 NewJob(JobInvocationInfo specification) { if (specification == null) { - throw new ArgumentNullException("specification"); + throw new ArgumentNullException(nameof(specification)); } if (specification.Definition == null) { - throw new ArgumentException(RemotingErrorIdStrings.NewJobSpecificationError, "specification"); + throw new ArgumentException(RemotingErrorIdStrings.NewJobSpecificationError, nameof(specification)); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(specification.Definition); @@ -263,12 +263,12 @@ public void PersistJob(Job2 job, JobDefinition definition) { if (job == null) { - throw new PSArgumentNullException("job"); + throw new PSArgumentNullException(nameof(job)); } if (definition == null) { - throw new PSArgumentNullException("definition"); + throw new PSArgumentNullException(nameof(definition)); } JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index b0538b33f37..f38ac4a39d0 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -405,7 +405,7 @@ public void StoreJobIdForReuse(Job2 job, bool recurse) { if (job == null) { - PSTraceSource.NewArgumentNullException("job", RemotingErrorIdStrings.JobSourceAdapterCannotSaveNullJob); + PSTraceSource.NewArgumentNullException(nameof(job), RemotingErrorIdStrings.JobSourceAdapterCannotSaveNullJob); } JobManager.SaveJobId(job.InstanceId, job.Id, this.GetType().Name); diff --git a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs index 038a8fc1763..288bc1449e9 100644 --- a/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs +++ b/src/System.Management.Automation/engine/remoting/client/PowerShellStreams.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 811baef9dc6..7c2aceec7d4 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -172,32 +172,19 @@ private void CreateDSHandler(TypeTable typeTable) DataStructureHandler = new ClientRunspacePoolDataStructureHandler(this, typeTable); // register for events from the data structure handler - DataStructureHandler.RemoteHostCallReceived += - new EventHandler>(HandleRemoteHostCalls); - DataStructureHandler.StateInfoReceived += - new EventHandler>(HandleStateInfoReceived); - DataStructureHandler.RSPoolInitInfoReceived += - new EventHandler>(HandleInitInfoReceived); - DataStructureHandler.ApplicationPrivateDataReceived += - new EventHandler>(HandleApplicationPrivateDataReceived); - DataStructureHandler.SessionClosing += - new EventHandler>(HandleSessionClosing); - DataStructureHandler.SessionClosed += - new EventHandler>(HandleSessionClosed); - DataStructureHandler.SetMaxMinRunspacesResponseReceived += - new EventHandler>(HandleResponseReceived); - DataStructureHandler.URIRedirectionReported += - new EventHandler>(HandleURIDirectionReported); - DataStructureHandler.PSEventArgsReceived += - new EventHandler>(HandlePSEventArgsReceived); - DataStructureHandler.SessionDisconnected += - new EventHandler>(HandleSessionDisconnected); - DataStructureHandler.SessionReconnected += - new EventHandler>(HandleSessionReconnected); - DataStructureHandler.SessionRCDisconnecting += - new EventHandler>(HandleSessionRCDisconnecting); - DataStructureHandler.SessionCreateCompleted += - new EventHandler(HandleSessionCreateCompleted); + DataStructureHandler.RemoteHostCallReceived += HandleRemoteHostCalls; + DataStructureHandler.StateInfoReceived += HandleStateInfoReceived; + DataStructureHandler.RSPoolInitInfoReceived += HandleInitInfoReceived; + DataStructureHandler.ApplicationPrivateDataReceived += HandleApplicationPrivateDataReceived; + DataStructureHandler.SessionClosing += HandleSessionClosing; + DataStructureHandler.SessionClosed += HandleSessionClosed; + DataStructureHandler.SetMaxMinRunspacesResponseReceived += HandleResponseReceived; + DataStructureHandler.URIRedirectionReported += HandleURIDirectionReported; + DataStructureHandler.PSEventArgsReceived += HandlePSEventArgsReceived; + DataStructureHandler.SessionDisconnected += HandleSessionDisconnected; + DataStructureHandler.SessionReconnected += HandleSessionReconnected; + DataStructureHandler.SessionRCDisconnecting += HandleSessionRCDisconnecting; + DataStructureHandler.SessionCreateCompleted += HandleSessionCreateCompleted; } #endregion Constructors @@ -1074,7 +1061,7 @@ public override void EndDisconnect(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; @@ -1083,7 +1070,7 @@ public override void EndDisconnect(IAsyncResult asyncResult) (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginOpen"); @@ -1184,7 +1171,7 @@ public override void EndConnect(IAsyncResult asyncResult) { if (asyncResult == null) { - throw PSTraceSource.NewArgumentNullException("asyncResult"); + throw PSTraceSource.NewArgumentNullException(nameof(asyncResult)); } RunspacePoolAsyncResult rsAsyncResult = asyncResult as RunspacePoolAsyncResult; @@ -1193,7 +1180,7 @@ public override void EndConnect(IAsyncResult asyncResult) (rsAsyncResult.OwnerId != instanceId) || (rsAsyncResult.IsAssociatedWithAsyncOpen)) { - throw PSTraceSource.NewArgumentException("asyncResult", + throw PSTraceSource.NewArgumentException(nameof(asyncResult), RunspacePoolStrings.AsyncResultNotOwned, "IAsyncResult", "BeginOpen"); @@ -2151,7 +2138,7 @@ private static object GetSessionOptions(WSManConnectionInfo wsmanConnectionInfo) private static bool CheckForSSL(WSManConnectionInfo wsmanConnectionInfo) { return (!string.IsNullOrEmpty(wsmanConnectionInfo.Scheme) && - wsmanConnectionInfo.Scheme.IndexOf(WSManConnectionInfo.HttpsScheme, StringComparison.OrdinalIgnoreCase) != -1); + wsmanConnectionInfo.Scheme.Contains(WSManConnectionInfo.HttpsScheme, StringComparison.OrdinalIgnoreCase)); } private static int ConvertPSAuthToWSManAuth(AuthenticationMechanism psAuth) diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index d38b67af1a5..7a7a70f9296 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -63,7 +63,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -143,7 +143,7 @@ public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originIn private static ProgressRecord Validate(ProgressRecord progressRecord) { - if (progressRecord == null) throw new ArgumentNullException("progressRecord"); + if (progressRecord == null) throw new ArgumentNullException(nameof(progressRecord)); return progressRecord; } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index 6c4b054e9c3..11ce70dd186 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -43,16 +43,11 @@ internal ClientRunspacePoolDataStructureHandler(RemoteRunspacePoolInternal clien // TODO: Assign remote session name.. should be passed from clientRunspacePool _transportManager = RemoteSession.SessionDataStructureHandler.TransportManager; _transportManager.TypeTable = typeTable; - RemoteSession.StateChanged += - new EventHandler( - HandleClientRemoteSessionStateChanged); + RemoteSession.StateChanged += HandleClientRemoteSessionStateChanged; _reconnecting = false; - _transportManager.RobustConnectionNotification += - new EventHandler(HandleRobustConnectionNotification); - - _transportManager.CreateCompleted += - new EventHandler(HandleSessionCreateCompleted); + _transportManager.RobustConnectionNotification += HandleRobustConnectionNotification; + _transportManager.CreateCompleted += HandleSessionCreateCompleted; } #endregion Constructors @@ -234,8 +229,7 @@ internal void CreatePowerShellOnServerAndInvoke(ClientRemotePowerShell shell) _associatedPowerShellDSHandlers.Add(shell.InstanceId, shell.DataStructureHandler); } - shell.DataStructureHandler.RemoveAssociation += - new EventHandler(HandleRemoveAssociation); + shell.DataStructureHandler.RemoveAssociation += HandleRemoveAssociation; // 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. @@ -266,7 +260,7 @@ internal void AddRemotePowerShellDSHandler(Guid psShellInstanceId, ClientPowerSh _associatedPowerShellDSHandlers[psShellInstanceId] = psDSHandler; } - psDSHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); + psDSHandler.RemoveAssociation += HandleRemoveAssociation; } /// @@ -876,6 +870,7 @@ private void HandleSessionCreateCompleted(object sender, CreateCompleteEventArgs private int _maxRunspaces; private PSHost _host; private PSPrimitiveDictionary _applicationArguments; + private Dictionary _associatedPowerShellDSHandlers = new Dictionary(); // data structure handlers of all ClientRemotePowerShell which are @@ -1192,7 +1187,7 @@ internal void SendInput(ObjectStreamBase inputstream) // registered lock (_inputSyncObject) { - inputstream.DataReady += new EventHandler(HandleInputDataReady); + inputstream.DataReady += HandleInputDataReady; WriteInput(inputstream); } } @@ -1497,7 +1492,7 @@ internal ClientPowerShellDataStructureHandler(BaseClientCommandTransportManager TransportManager = transportManager; this.clientRunspacePoolId = clientRunspacePoolId; this.clientPowerShellId = clientPowerShellId; - transportManager.SignalCompleted += new EventHandler(OnSignalCompleted); + transportManager.SignalCompleted += OnSignalCompleted; } #endregion Constructors diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index ebf24e1e757..270e24eb1bd 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -222,8 +222,7 @@ internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedP PowerShell shell = remotePipeline.PowerShell; if (shell.RemotePowerShell != null) { - shell.RemotePowerShell.RCConnectionNotification += - new EventHandler(HandleRCConnectionNotification); + shell.RemotePowerShell.RCConnectionNotification += HandleRCConnectionNotification; } // Add callback to write robust connection errors from stream. @@ -314,12 +313,11 @@ internal void Override(RemoteRunspace remoteRunspace, object syncObject, out boo powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; - bool isReleaseCandidateBackcompatibilityMode = - _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; + bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; - powerShell.RemotePowerShell.HostCallReceived += new EventHandler>(HandleHostCall); + powerShell.RemotePowerShell.HostCallReceived += HandleHostCall; IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection results = new PSDataCollection(); diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index ceeb8f745de..efb47508bcc 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -201,6 +201,7 @@ internal enum ChildJobFlags private bool _ownerWontSubmitNewChildJobs = false; private readonly HashSet _setOfChildJobsThatCanAddMoreChildJobs = new HashSet(); + private bool IsEndOfChildJobs { get @@ -232,6 +233,7 @@ private bool IsThrottlingJobCompleted private int _countOfFailedChildJobs; private int _countOfStoppedChildJobs; private int _countOfSuccessfullyCompletedChildJobs; + private int CountOfFinishedChildJobs { get @@ -296,7 +298,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var jobGotEnqueued = new ManualResetEventSlim(initialState: false)) { - if (childJob == null) throw new ArgumentNullException("childJob"); + if (childJob == null) throw new ArgumentNullException(nameof(childJob)); this.AddChildJobWithoutBlocking(childJob, flags, jobGotEnqueued.Set); jobGotEnqueued.Wait(); @@ -310,7 +312,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var forwardingCancellation = new CancellationTokenSource()) { - if (childJob == null) throw new ArgumentNullException("childJob"); + if (childJob == null) throw new ArgumentNullException(nameof(childJob)); this.AddChildJobWithoutBlocking(childJob, flags, forwardingCancellation.Cancel); this.ForwardAllResultsToCmdlet(cmdlet, forwardingCancellation.Token); @@ -318,6 +320,7 @@ internal void AddChildJobAndPotentiallyBlock( } private bool _alreadyDisabledFlowControlForPendingJobsQueue = false; + internal void DisableFlowControlForPendingJobsQueue() { if (!_cmdletMode || _alreadyDisabledFlowControlForPendingJobsQueue) @@ -343,6 +346,7 @@ internal void DisableFlowControlForPendingJobsQueue() } private bool _alreadyDisabledFlowControlForPendingCmdletActionsQueue = false; + internal void DisableFlowControlForPendingCmdletActionsQueue() { if (!_cmdletMode || _alreadyDisabledFlowControlForPendingCmdletActionsQueue) @@ -371,8 +375,8 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() /// internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { - if (childJob == null) throw new ArgumentNullException("childJob"); - if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, "childJob"); + if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); this.AssertNotDisposed(); JobStateInfo newJobStateInfo = null; @@ -420,7 +424,7 @@ internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags fl childJob.StateChanged += this.childJob_StateChanged; if (_cmdletMode) { - childJob.Results.DataAdded += new EventHandler(childJob_ResultsAdded); + childJob.Results.DataAdded += childJob_ResultsAdded; } this.EnqueueReadyToRunChildJob(childJob); @@ -448,6 +452,7 @@ private void childJob_ResultsAdded(object sender, DataAddedEventArgs e) private readonly object _alreadyWroteFlowControlBuffersHighMemoryUsageWarningLock = new object(); private bool _alreadyWroteFlowControlBuffersHighMemoryUsageWarning; + private const long FlowControlBuffersHighMemoryUsageThreshold = 30000; private void WriteWarningAboutHighUsageOfFlowControlBuffers(long currentCount) @@ -1153,6 +1158,7 @@ private void ForwardResults(Cmdlet cmdlet) } private bool _stoppedMonitoringAllJobs; + private void StopMonitoringAllJobs() { _cancellationTokenSource.Cancel(); diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index bbd47cf7925..a2875f819fe 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -221,10 +221,8 @@ internal ClientRemoteSessionImpl(RemoteRunspacePoolInternal rsPool, // Register handlers for various ClientSessiondata structure handler events SessionDataStructureHandler.NegotiationReceived += HandleNegotiationReceived; SessionDataStructureHandler.ConnectionStateChanged += HandleConnectionStateChanged; - SessionDataStructureHandler.EncryptedSessionKeyReceived += - new EventHandler>(HandleEncryptedSessionKeyReceived); - SessionDataStructureHandler.PublicKeyRequestReceived += - new EventHandler>(HandlePublicKeyRequestReceived); + SessionDataStructureHandler.EncryptedSessionKeyReceived += HandleEncryptedSessionKeyReceived; + SessionDataStructureHandler.PublicKeyRequestReceived += HandlePublicKeyRequestReceived; } #endregion Constructors @@ -299,7 +297,7 @@ private void HandleConnectionStateChanged(object sender, RemoteSessionStateEvent { if (arg == null) { - throw PSTraceSource.NewArgumentNullException("arg"); + throw PSTraceSource.NewArgumentNullException(nameof(arg)); } if (arg.SessionStateInfo.State == RemoteSessionState.EstablishedAndKeyReceived) // TODO - Client session would never get into this state... to be removed @@ -454,12 +452,12 @@ private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEv { if (arg == null) { - throw PSTraceSource.NewArgumentNullException("arg"); + throw PSTraceSource.NewArgumentNullException(nameof(arg)); } if (arg.RemoteSessionCapability == null) { - throw PSTraceSource.NewArgumentException("arg"); + throw PSTraceSource.NewArgumentException(nameof(arg)); } Context.ServerCapability = arg.RemoteSessionCapability; diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index f146beb3d4a..ec55f22fc22 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -190,7 +190,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e "State can be set to NegotiationReceived only when RemoteSessionCapability is not null"); if (eventArgs.RemoteSessionCapability == null) { - throw PSTraceSource.NewArgumentException("eventArgs"); + throw PSTraceSource.NewArgumentException(nameof(eventArgs)); } SetState(RemoteSessionState.NegotiationReceived, null); @@ -490,7 +490,7 @@ internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg) _state == RemoteSessionState.EstablishedAndKeyReceived || // TODO - Client session would never get into this state... to be removed _state == RemoteSessionState.EstablishedAndKeySent || _state == RemoteSessionState.Disconnecting || // There can be input data until disconnect has been completed - _state == RemoteSessionState.Disconnected) // Data can arrive while state machine is transitioning to disconnected, in a race. + _state == RemoteSessionState.Disconnected) // Data can arrive while state machine is transitioning to disconnected { return true; } @@ -554,7 +554,7 @@ private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs arg) { if (arg == null) { - throw PSTraceSource.NewArgumentNullException("arg"); + throw PSTraceSource.NewArgumentNullException(nameof(arg)); } EventHandler handler = _stateMachineHandle[(int)State, (int)arg.StateEvent]; diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index a599df2d4e3..58931499610 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -126,8 +126,7 @@ internal RemotePipeline(RemoteRunspace runspace, string command, bool addToHisto _powershell.SetIsNested(isNested); - _powershell.InvocationStateChanged += - new EventHandler(HandleInvocationStateChanged); + _powershell.InvocationStateChanged += HandleInvocationStateChanged; } /// @@ -153,8 +152,7 @@ internal RemotePipeline(RemoteRunspace runspace) _powershell = new PowerShell(_connectCmdInfo, _inputStream, _outputStream, _errorStream, ((RemoteRunspace)_runspace).RunspacePool); - _powershell.InvocationStateChanged += - new EventHandler(HandleInvocationStateChanged); + _powershell.InvocationStateChanged += HandleInvocationStateChanged; } /// @@ -173,7 +171,7 @@ private RemotePipeline(RemotePipeline pipeline) : // originally copied it from PipelineBase if (pipeline == null) { - throw PSTraceSource.NewArgumentNullException("pipeline"); + throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } if (pipeline._disposed) @@ -545,7 +543,7 @@ public override void Stop() catch (ObjectDisposedException) { throw PSTraceSource.NewObjectDisposedException("Pipeline"); - }; + } asyncresult.AsyncWaitHandle.WaitOne(); } @@ -894,8 +892,7 @@ private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) _powershell.InitForRemotePipeline(_commands, _inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); - _powershell.RemotePowerShell.HostCallReceived += - new EventHandler>(HandleHostCallReceived); + _powershell.RemotePowerShell.HostCallReceived += HandleHostCallReceived; } /// @@ -931,8 +928,7 @@ private void InitPowerShellForConnect(bool syncCall) _powershell.InitForRemotePipelineConnect(_inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); - _powershell.RemotePowerShell.HostCallReceived += - new EventHandler>(HandleHostCallReceived); + _powershell.RemotePowerShell.HostCallReceived += HandleHostCallReceived; } } diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 76e257373d4..a927b49481f 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -203,17 +203,11 @@ private void SetEventHandlers() _eventManager = new PSRemoteEventManager(_connectionInfo.ComputerName, this.InstanceId); - RunspacePool.StateChanged += - new EventHandler(HandleRunspacePoolStateChanged); - RunspacePool.RemoteRunspacePoolInternal.HostCallReceived += - new EventHandler>(HandleHostCallReceived); - RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported += - new EventHandler>(HandleURIDirectionReported); - RunspacePool.ForwardEvent += - new EventHandler(HandleRunspacePoolForwardEvent); - - RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted += - new EventHandler(HandleSessionCreateCompleted); + RunspacePool.StateChanged += HandleRunspacePoolStateChanged; + RunspacePool.RemoteRunspacePoolInternal.HostCallReceived += HandleHostCallReceived; + RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported += HandleURIDirectionReported; + RunspacePool.ForwardEvent += HandleRunspacePoolForwardEvent; + RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted += HandleSessionCreateCompleted; } #endregion Constructors @@ -656,17 +650,11 @@ protected override void Dispose(bool disposing) try { - RunspacePool.StateChanged -= - new EventHandler(HandleRunspacePoolStateChanged); - RunspacePool.RemoteRunspacePoolInternal.HostCallReceived -= - new EventHandler>(HandleHostCallReceived); - RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported -= - new EventHandler>(HandleURIDirectionReported); - RunspacePool.ForwardEvent -= - new EventHandler(HandleRunspacePoolForwardEvent); - - RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted -= - new EventHandler(HandleSessionCreateCompleted); + RunspacePool.StateChanged -= HandleRunspacePoolStateChanged; + RunspacePool.RemoteRunspacePoolInternal.HostCallReceived -= HandleHostCallReceived; + RunspacePool.RemoteRunspacePoolInternal.URIRedirectionReported -= HandleURIDirectionReported; + RunspacePool.ForwardEvent -= HandleRunspacePoolForwardEvent; + RunspacePool.RemoteRunspacePoolInternal.SessionCreateCompleted -= HandleSessionCreateCompleted; _eventManager = null; @@ -1041,7 +1029,7 @@ public override Pipeline CreatePipeline(string command) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } return CoreCreatePipeline(command, false, false); @@ -1062,7 +1050,7 @@ public override Pipeline CreatePipeline(string command, bool addToHistory) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } return CoreCreatePipeline(command, addToHistory, false); @@ -1097,7 +1085,7 @@ public override Pipeline CreateNestedPipeline(string command, bool addToHistory) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } return CoreCreatePipeline(command, addToHistory, true); @@ -1190,7 +1178,7 @@ internal void DoConcurrentCheckAndAddToRunningPipelines(RemotePipeline pipeline, // Concurrency check should be done under runspace lock lock (_syncRoot) { - if (_bSessionStateProxyCallInProgress == true) + if (_bSessionStateProxyCallInProgress) { throw PSTraceSource.NewInvalidOperationException(RunspaceStrings.NoPipelineWhenSessionStateProxyInProgress); } @@ -1853,7 +1841,7 @@ public RemoteDebugger(RemoteRunspace runspace) { if (runspace == null) { - throw new PSArgumentNullException("runspace"); + throw new PSArgumentNullException(nameof(runspace)); } _runspace = runspace; @@ -1882,12 +1870,12 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC if (command == null) { - throw new PSArgumentNullException("command"); + throw new PSArgumentNullException(nameof(command)); } if (output == null) { - throw new PSArgumentNullException("output"); + throw new PSArgumentNullException(nameof(output)); } if (!DebuggerStopped) @@ -2946,6 +2934,7 @@ private void CheckRemoteBreakpointManagementSupport(string breakpointCommandName internal class RemoteSessionStateProxy : SessionStateProxy { private RemoteRunspace _runspace; + internal RemoteSessionStateProxy(RemoteRunspace runspace) { Dbg.Assert(runspace != null, "Caller should validate the parameter"); @@ -2978,7 +2967,7 @@ public override void SetVariable(string name, object value) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } // Verify the runspace has the Set-Variable command. For performance, throw if we got an error @@ -3038,7 +3027,7 @@ public override object GetVariable(string name) { if (name == null) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } // Verify the runspace has the Get-Variable command. For performance, throw if we got an error diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs index b598d3ecbc9..1a975f5a785 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspaceinfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs index 6a640886300..04ac1eaeaa0 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocol.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Remoting.Client; diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index a9f3a7b6eca..8615bf3398a 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -17,6 +17,7 @@ internal class ClientRemoteSessionDSHandlerImpl : ClientRemoteSessionDataStructu { [TraceSourceAttribute("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl")] private static PSTraceSource s_trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl"); + private const string resBaseName = "remotingerroridstrings"; private BaseClientSessionTransportManager _transportManager; @@ -66,7 +67,7 @@ internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, if (session == null) { - throw PSTraceSource.NewArgumentNullException("session"); + throw PSTraceSource.NewArgumentNullException(nameof(session)); } _session = session; @@ -90,7 +91,7 @@ internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session, _transportManager.DisconnectCompleted += HandleDisconnectComplete; _transportManager.ReconnectCompleted += HandleReconnectComplete; - _transportManager.RobustConnectionNotification += new EventHandler(HandleRobustConnectionNotification); + _transportManager.RobustConnectionNotification += HandleRobustConnectionNotification; WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null) @@ -278,7 +279,7 @@ private void HandleStateChanged(object sender, RemoteSessionStateEventArgs arg) { if (arg == null) { - throw PSTraceSource.NewArgumentNullException("arg"); + throw PSTraceSource.NewArgumentNullException(nameof(arg)); } // Enqueue session related negotiation packets first @@ -540,14 +541,14 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataArg) { if (dataArg == null) { - throw PSTraceSource.NewArgumentNullException("dataArg"); + throw PSTraceSource.NewArgumentNullException(nameof(dataArg)); } RemoteDataObject rcvdData = dataArg.ReceivedData; if (rcvdData == null) { - throw PSTraceSource.NewArgumentException("dataArg"); + throw PSTraceSource.NewArgumentException(nameof(dataArg)); } RemotingDestination destination = rcvdData.Destination; @@ -610,7 +611,7 @@ private void ProcessSessionMessages(RemoteDataEventArgs arg) { if (arg == null || arg.ReceivedData == null) { - throw PSTraceSource.NewArgumentNullException("arg"); + throw PSTraceSource.NewArgumentNullException(nameof(arg)); } RemoteDataObject rcvdData = arg.ReceivedData; @@ -684,7 +685,7 @@ internal void ProcessNonSessionMessages(RemoteDataObject rcvdData) // TODO: Consider changing to Dbg.Assert() if (rcvdData == null) { - throw PSTraceSource.NewArgumentNullException("rcvdData"); + throw PSTraceSource.NewArgumentNullException(nameof(rcvdData)); } RemotingTargetInterface targetInterface = rcvdData.TargetInterface; diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index 77e1c8d0b8e..5f66afdfac1 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -354,7 +354,7 @@ protected override void BeginProcessing() base.BeginProcessing(); _throttleManager.ThrottleLimit = ThrottleLimit; - _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleConnectComplete); + _throttleManager.ThrottleComplete += HandleThrottleConnectComplete; } /// @@ -1072,7 +1072,7 @@ private void Dispose(bool disposing) _operationsComplete.WaitOne(); _operationsComplete.Dispose(); - _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleConnectComplete); + _throttleManager.ThrottleComplete -= HandleThrottleConnectComplete; _retryThrottleManager.Dispose(); _stream.Dispose(); diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index cfe092c639b..dde4422de45 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -271,6 +271,7 @@ function Register-PSSessionConfiguration Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -erroraction $args[14] }} "; + private static readonly ScriptBlock s_newPluginSb; private const string pluginXmlFormat = @" @@ -293,6 +294,7 @@ function Register-PSSessionConfiguration {11} "; + private const string architectureAttribFormat = @" Architecture='{0}'"; @@ -310,6 +312,7 @@ function Register-PSSessionConfiguration private const string initParamFormat = @" {2}"; + private const string privateDataFormat = @"{0}"; private const string securityElementFormat = ""; private const string SessionConfigDataFormat = @"{0}"; @@ -1658,6 +1661,7 @@ internal static string UpdateSDDLUsersWithGroupConditional( } private const string DACLPrefix = "D:"; + private static Collection ParseDACLACEs( string sddl, out string prologue, @@ -2518,6 +2522,7 @@ function Unregister-PSSessionConfiguration Unregister-PSSessionConfiguration -filter $args[0] -whatif:$args[1] -confirm:$args[2] -action $args[3] -targetTemplate $args[4] -shellNotErrMsgFormat $args[5] -force $args[6] -erroraction $args[7] }} "; + private static readonly ScriptBlock s_removePluginSb; private bool _isErrorReported; @@ -2787,6 +2792,7 @@ function ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) "; private const string MODULEPATH = "ModulesToImport"; + private static readonly ScriptBlock s_getPluginSb; #endregion @@ -2913,6 +2919,7 @@ public sealed class SetPSSessionConfigurationCommand : PSSessionConfigurationCom private const string getCurrentIdleTimeoutmsFormat = @"(Get-Item 'WSMan:\localhost\Plugin\{0}\Quotas\IdleTimeoutms').Value"; private const string getAssemblyNameDataFormat = @"(Get-Item 'WSMan:\localhost\Plugin\{0}\InitializationParameters\assemblyname').Value"; private const string getSessionConfigurationDataSbFormat = @"(Get-Item 'WSMan:\localhost\Plugin\{0}\InitializationParameters\SessionConfigurationData').Value"; + private const string setSessionConfigurationDataSbFormat = @" function Set-SessionConfigurationData([string] $scd) {{ if (test-path 'WSMan:\localhost\Plugin\{0}\InitializationParameters\" + ConfigurationDataFromXML.SESSIONCONFIGTOKEN + @"') @@ -3178,6 +3185,7 @@ function Set-RunAsCredential{{ Set-PSSessionConfiguration $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] $args[6] $args[7] $args[8] $args[9] $args[10] $args[11] "; + private const string initParamFormat = @""; private const string privateDataFormat = @"{0}"; @@ -4496,6 +4504,7 @@ function Disable-PSSessionConfiguration $_ | Disable-PSSessionConfiguration -force $args[0] -whatif:$args[1] -confirm:$args[2] -restartWinRMMessage $args[3] -setEnabledTarget $args[4] -setEnabledAction $args[5] -noServiceRestart $args[6] "; + private static ScriptBlock s_disablePluginSb; #endregion @@ -5126,6 +5135,7 @@ function Disable-PSRemoting Disable-PSRemoting -force:$args[0] -queryForSet $args[1] -captionForSet $args[2] -restartWinRMMessage $args[3] -whatif:$args[4] -confirm:$args[5] "; + private static ScriptBlock s_disableRemotingSb; #endregion Private Data diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 385182fc12f..979912619f2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -222,7 +222,7 @@ protected override void StopProcessing() private bool CheckForDebuggableJob() { // Check passed in job object. - bool debuggableJobFound = GetJobDebuggable(_job); ; + bool debuggableJobFound = GetJobDebuggable(_job); if (!debuggableJobFound) { diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index e664ee55ce0..0b9cfeb2d6e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -160,7 +160,7 @@ protected override void BeginProcessing() base.BeginProcessing(); _throttleManager.ThrottleLimit = ThrottleLimit; - _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleDisconnectComplete); + _throttleManager.ThrottleComplete += HandleThrottleDisconnectComplete; } /// @@ -546,7 +546,7 @@ private void Dispose(bool disposing) _operationsComplete.WaitOne(); _operationsComplete.Dispose(); - _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleDisconnectComplete); + _throttleManager.ThrottleComplete -= HandleThrottleDisconnectComplete; _stream.Dispose(); } } diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 727c5ef709e..3cf54997e5d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -648,7 +648,7 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc int pAppDomainIndex = namedPipe.IndexOf('.', pIdIndex + 1); if (pAppDomainIndex > -1) { - string idString = namedPipe.Substring(pIdIndex + 1, (pAppDomainIndex - pIdIndex - 1)); + ReadOnlySpan idString = namedPipe.AsSpan(pIdIndex + 1, (pAppDomainIndex - pIdIndex - 1)); int id = -1; if (int.TryParse(idString, out id)) { @@ -707,7 +707,7 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc else if (process.ProcessName.Equals(pName, StringComparison.Ordinal)) { // only add if the process name matches - procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName)); + procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName, namedPipe)); } } } @@ -736,6 +736,12 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc /// public sealed class PSHostProcessInfo { + #region Members + + private readonly string _pipeNameFilePath; + + #endregion + #region Properties /// @@ -765,7 +771,6 @@ public string AppDomainName private set; } -#if !CORECLR /// /// Main window title of the process. /// @@ -774,7 +779,6 @@ public string MainWindowTitle get; private set; } -#endif #endregion @@ -783,31 +787,60 @@ public string MainWindowTitle private PSHostProcessInfo() { } /// - /// Constructor. + /// Initializes a new instance of the PSHostProcessInfo type. /// /// Name of process. /// Id of process. /// Name of process AppDomain. - internal PSHostProcessInfo(string processName, int processId, string appDomainName) + /// File path of pipe name. + internal PSHostProcessInfo( + string processName, + int processId, + string appDomainName, + string pipeNameFilePath) { - if (string.IsNullOrEmpty(processName)) { throw new PSArgumentNullException("processName"); } + if (string.IsNullOrEmpty(processName)) + { + throw new PSArgumentNullException(nameof(processName)); + } - if (string.IsNullOrEmpty(appDomainName)) { throw new PSArgumentNullException("appDomainName"); } + if (string.IsNullOrEmpty(appDomainName)) + { + throw new PSArgumentNullException(nameof(appDomainName)); + } -#if !CORECLR MainWindowTitle = string.Empty; try { var proc = Process.GetProcessById(processId); MainWindowTitle = proc.MainWindowTitle ?? string.Empty; } - catch (ArgumentException) { } - catch (InvalidOperationException) { } -#endif + catch (ArgumentException) + { + // Window title is optional. + } + catch (InvalidOperationException) + { + // Window title is optional. + } this.ProcessName = processName; this.ProcessId = processId; this.AppDomainName = appDomainName; + _pipeNameFilePath = pipeNameFilePath; + } + + #endregion + + #region Methods + + /// + /// Retrieves the pipe name file path. + /// + /// Pipe name file path. + public string GetPipeNameFilePath() + { + return _pipeNameFilePath; } #endregion diff --git a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs index 2b41e3f39cf..17ee25c52cf 100644 --- a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index 0fa91661b02..daef292017f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1359,7 +1359,7 @@ private Debugger GetHostDebugger() private void HandleThrottleComplete(object sender, EventArgs eventArgs) { _operationsComplete.Set(); - _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); + _throttleManager.ThrottleComplete -= HandleThrottleComplete; } /// @@ -1389,14 +1389,14 @@ private void CreateAndRunSyncJob() if (!_nojob) { _throttleManager.ThrottleLimit = ThrottleLimit; - _throttleManager.ThrottleComplete += new EventHandler(HandleThrottleComplete); + _throttleManager.ThrottleComplete += HandleThrottleComplete; _operationsComplete.Reset(); Dbg.Assert(_disconnectComplete == null, "disconnectComplete event should only be used once."); _disconnectComplete = new ManualResetEvent(false); _job = new PSInvokeExpressionSyncJob(Operations, _throttleManager); _job.HideComputerName = _hideComputerName; - _job.StateChanged += new EventHandler(HandleJobStateChanged); + _job.StateChanged += HandleJobStateChanged; // Add robust connection retry notification handler. AddConnectionRetryHandler(_job); @@ -1435,7 +1435,7 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) state == JobState.Stopped || state == JobState.Failed) { - _job.StateChanged -= new EventHandler(HandleJobStateChanged); + _job.StateChanged -= HandleJobStateChanged; RemoveConnectionRetryHandler(sender as PSInvokeExpressionSyncJob); // Signal that this job has been disconnected, or has ended. @@ -1461,8 +1461,7 @@ private void AddConnectionRetryHandler(PSInvokeExpressionSyncJob job) { if (ps.RemotePowerShell != null) { - ps.RemotePowerShell.RCConnectionNotification += - new EventHandler(RCConnectionNotificationHandler); + ps.RemotePowerShell.RCConnectionNotification += RCConnectionNotificationHandler; } } } @@ -1482,8 +1481,7 @@ private void RemoveConnectionRetryHandler(PSInvokeExpressionSyncJob job) { if (ps.RemotePowerShell != null) { - ps.RemotePowerShell.RCConnectionNotification -= - new EventHandler(RCConnectionNotificationHandler); + ps.RemotePowerShell.RCConnectionNotification -= RCConnectionNotificationHandler; } } } @@ -2003,6 +2001,7 @@ private void PreProcessStreamObject(PSStreamObject streamObject) private bool _inputStreamClosed = false; private const string InProcParameterSet = "InProcess"; + private PSDataCollection _input = new PSDataCollection(); private bool _needToCollect = false; private bool _needToStartSteppablePipelineOnServer = false; @@ -2055,7 +2054,7 @@ private void Dispose(bool disposing) _job.Dispose(); } - _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); + _throttleManager.ThrottleComplete -= HandleThrottleComplete; _throttleManager.Dispose(); _throttleManager = null; } @@ -2137,7 +2136,7 @@ public void StartProgress( if (string.IsNullOrEmpty(computerName)) { - throw new ArgumentNullException("computerName"); + throw new ArgumentNullException(nameof(computerName)); } lock (_syncObject) diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index f4b2aff0be9..d06eabf25a3 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 4303a766d3c..8a7a9b88b88 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs index 19731beb1d4..c1b3b3b7326 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationOptionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -18,42 +18,52 @@ public class WSManConfigurationOption : PSTransportOption private const string QuotasToken = ""; internal const string AttribOutputBufferingMode = "OutputBufferingMode"; - internal static System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; + + internal static readonly System.Management.Automation.Runspaces.OutputBufferingMode? DefaultOutputBufferingMode = System.Management.Automation.Runspaces.OutputBufferingMode.Block; private System.Management.Automation.Runspaces.OutputBufferingMode? _outputBufferingMode = null; private const string AttribProcessIdleTimeout = "ProcessIdleTimeoutSec"; + internal static readonly int? DefaultProcessIdleTimeout_ForPSRemoting = 0; // in seconds private int? _processIdleTimeoutSec = null; internal const string AttribMaxIdleTimeout = "MaxIdleTimeoutms"; + internal static readonly int? DefaultMaxIdleTimeout = int.MaxValue; private int? _maxIdleTimeoutSec = null; internal const string AttribIdleTimeout = "IdleTimeoutms"; + internal static readonly int? DefaultIdleTimeout = 7200; // 2 hours in seconds private int? _idleTimeoutSec = null; private const string AttribMaxConcurrentUsers = "MaxConcurrentUsers"; + internal static readonly int? DefaultMaxConcurrentUsers = int.MaxValue; private int? _maxConcurrentUsers = null; private const string AttribMaxProcessesPerSession = "MaxProcessesPerShell"; + internal static readonly int? DefaultMaxProcessesPerSession = int.MaxValue; private int? _maxProcessesPerSession = null; private const string AttribMaxMemoryPerSessionMB = "MaxMemoryPerShellMB"; + internal static readonly int? DefaultMaxMemoryPerSessionMB = int.MaxValue; private int? _maxMemoryPerSessionMB = null; private const string AttribMaxSessions = "MaxShells"; + internal static readonly int? DefaultMaxSessions = int.MaxValue; private int? _maxSessions = null; private const string AttribMaxSessionsPerUser = "MaxShellsPerUser"; + internal static readonly int? DefaultMaxSessionsPerUser = int.MaxValue; private int? _maxSessionsPerUser = null; private const string AttribMaxConcurrentCommandsPerSession = "MaxConcurrentCommandsPerShell"; + internal static readonly int? DefaultMaxConcurrentCommandsPerSession = int.MaxValue; private int? _maxConcurrentCommandsPerSession = null; diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs index f6a7f215829..5ad0df8910c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 3654a67c3fd..de046236536 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -27,7 +27,7 @@ namespace Microsoft.PowerShell.Commands /// It contains tons of utility functions which are used all /// across the remoting cmdlets. /// - public abstract partial class PSRemotingCmdlet : PSCmdlet + public abstract class PSRemotingCmdlet : PSCmdlet { #region Overrides @@ -296,7 +296,7 @@ internal struct SSHConnection /// 2. Invoke-Expression /// 3. Start-PSJob. /// - public abstract partial class PSRemotingBaseCmdlet : PSRemotingCmdlet + public abstract class PSRemotingBaseCmdlet : PSRemotingCmdlet { #region Enums @@ -673,6 +673,7 @@ public virtual PSSessionOption SessionOption } private PSSessionOption _sessionOption; + internal const string DEFAULT_SESSION_OPTION = "PSSessionOption"; // Quota related variables. @@ -986,7 +987,7 @@ protected void ValidateRemoteRunspacesSpecified() { ThrowTerminatingError(new ErrorRecord(new ArgumentException( GetMessage(RemotingErrorIdStrings.RemoteRunspaceInfoHasDuplicates)), - PSRemotingErrorId.RemoteRunspaceInfoHasDuplicates.ToString(), + nameof(PSRemotingErrorId.RemoteRunspaceInfoHasDuplicates), ErrorCategory.InvalidArgument, Session)); } @@ -997,7 +998,7 @@ protected void ValidateRemoteRunspacesSpecified() { ThrowTerminatingError(new ErrorRecord(new ArgumentException( GetMessage(RemotingErrorIdStrings.RemoteRunspaceInfoLimitExceeded)), - PSRemotingErrorId.RemoteRunspaceInfoLimitExceeded.ToString(), + nameof(PSRemotingErrorId.RemoteRunspaceInfoLimitExceeded), ErrorCategory.InvalidArgument, Session)); } } @@ -1149,7 +1150,7 @@ protected override void BeginProcessing() /// 1. Invoke-Expression /// 2. Start-PSJob. /// - public abstract partial class PSExecutionCmdlet : PSRemotingBaseCmdlet + public abstract class PSExecutionCmdlet : PSRemotingBaseCmdlet { #region Strings @@ -1608,7 +1609,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() ThrowTerminatingError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), - PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), + nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); @@ -1656,7 +1657,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() ThrowTerminatingError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), - PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), + nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); @@ -1692,7 +1693,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, this.VMName[index])), - PSRemotingErrorId.InvalidVMNameNotSingle.ToString(), + nameof(PSRemotingErrorId.InvalidVMNameNotSingle), ErrorCategory.InvalidArgument, null)); @@ -1706,7 +1707,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, this.VMId[index].ToString(null))), - PSRemotingErrorId.InvalidVMIdNotSingle.ToString(), + nameof(PSRemotingErrorId.InvalidVMIdNotSingle), ErrorCategory.InvalidArgument, null)); @@ -1718,7 +1719,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName[index])), - PSRemotingErrorId.InvalidVMState.ToString(), + nameof(PSRemotingErrorId.InvalidVMState), ErrorCategory.InvalidArgument, null)); @@ -2013,12 +2014,12 @@ protected ScriptBlock GetScriptBlockFromFile(string filePath, bool isLiteralPath // Make sure filepath doesn't contain wildcards if ((!isLiteralPath) && WildcardPattern.ContainsWildcardCharacters(filePath)) { - throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter), "filePath"); + throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.WildCardErrorFilePathParameter), nameof(filePath)); } if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { - throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.FilePathShouldPS1Extension), "filePath"); + throw new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.FilePathShouldPS1Extension), nameof(filePath)); } // Resolve file path @@ -2430,7 +2431,7 @@ private List GetUsingVariables(ScriptBlock localScriptBlo { if (localScriptBlock == null) { - throw new ArgumentNullException("localScriptBlock", "Caller needs to make sure the parameter value is not null"); + throw new ArgumentNullException(nameof(localScriptBlock), "Caller needs to make sure the parameter value is not null"); } var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(localScriptBlock.Ast); @@ -2448,7 +2449,7 @@ private List GetUsingVariables(ScriptBlock localScriptBlo /// 3. Disconnect-PSSession /// 4. Connect-PSSession. /// - public abstract partial class PSRunspaceCmdlet : PSRemotingCmdlet + public abstract class PSRunspaceCmdlet : PSRemotingCmdlet { #region Parameters @@ -3222,7 +3223,7 @@ private void WriteInvalidArgumentError(PSRemotingErrorId errorId, string resourc /// Base class for both the helpers. This is an abstract class /// and the helpers need to derive from this. /// - internal abstract partial class ExecutionCmdletHelper : IThrottleOperation + internal abstract class ExecutionCmdletHelper : IThrottleOperation { /// /// Pipeline associated with this operation. @@ -3327,7 +3328,7 @@ internal ExecutionCmdletHelperRunspace(Pipeline pipeline) { this.pipeline = pipeline; PipelineRunspace = pipeline.Runspace; - this.pipeline.StateChanged += new EventHandler(HandlePipelineStateChanged); + this.pipeline.StateChanged += HandlePipelineStateChanged; } /// @@ -3435,7 +3436,7 @@ private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) { // Dispose the pipeline object and release data and remoting resources. // Pipeline object remains to provide information on final state and any errors incurred. - pipeline.StateChanged -= new EventHandler(HandlePipelineStateChanged); + pipeline.StateChanged -= HandlePipelineStateChanged; pipeline.Dispose(); } @@ -3495,15 +3496,13 @@ internal ExecutionCmdletHelperComputerName(RemoteRunspace remoteRunspace, Pipeli _invokeAndDisconnect = invokeAndDisconnect; RemoteRunspace = remoteRunspace; - remoteRunspace.StateChanged += - new EventHandler(HandleRunspaceStateChanged); + remoteRunspace.StateChanged += HandleRunspaceStateChanged; Dbg.Assert(pipeline != null, "Pipeline cannot be null or empty"); this.pipeline = pipeline; - pipeline.StateChanged += - new EventHandler(HandlePipelineStateChanged); + pipeline.StateChanged += HandlePipelineStateChanged; } /// @@ -3674,7 +3673,7 @@ private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) { // Dispose the pipeline object and release data and remoting resources. // Pipeline object remains to provide information on final state and any errors incurred. - pipeline.StateChanged -= new EventHandler(HandlePipelineStateChanged); + pipeline.StateChanged -= HandlePipelineStateChanged; pipeline.Dispose(); } @@ -4368,9 +4367,9 @@ public AuthenticationMechanism ProxyAuthentication default: string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyAmbiguousAuthentication, value, - AuthenticationMechanism.Basic.ToString(), - AuthenticationMechanism.Negotiate.ToString(), - AuthenticationMechanism.Digest.ToString()); + nameof(AuthenticationMechanism.Basic), + nameof(AuthenticationMechanism.Negotiate), + nameof(AuthenticationMechanism.Digest)); throw new ArgumentException(message); } } diff --git a/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs index d6da9d63f81..5f80dfb5d0c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PopRunspaceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -28,7 +28,7 @@ protected override void ProcessRecord() WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), - PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(), + nameof(PSRemotingErrorId.HostDoesNotSupportPushRunspace), ErrorCategory.InvalidArgument, null)); return; diff --git a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs index eb5b85659fa..a7751e0138d 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PushRunspaceCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -240,26 +240,7 @@ protected override void ProcessRecord() WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), - PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(), - ErrorCategory.InvalidArgument, - null)); - return; - } - - // Check if current host is remote host. Enter-PSSession on remote host is not - // currently supported. - if (!IsParameterSetForVM() && - !IsParameterSetForContainer() && - !IsParameterSetForVMContainerSession() && - this.Context != null && - this.Context.EngineHostInterface != null && - this.Context.EngineHostInterface.ExternalHost != null && - this.Context.EngineHostInterface.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost) - { - WriteError( - new ErrorRecord( - new ArgumentException(GetMessage(RemotingErrorIdStrings.RemoteHostDoesNotSupportPushRunspace)), - PSRemotingErrorId.RemoteHostDoesNotSupportPushRunspace.ToString(), + nameof(PSRemotingErrorId.HostDoesNotSupportPushRunspace), ErrorCategory.InvalidArgument, null)); return; @@ -392,7 +373,7 @@ protected override void ProcessRecord() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.EnterPSSessionBrokenSession, sessionName, remoteRunspace.ConnectionInfo.ComputerName, remoteRunspace.InstanceId)), - PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(), + nameof(PSRemotingErrorId.PushedRunspaceMustBeOpen), ErrorCategory.InvalidArgument, null)); } @@ -401,7 +382,7 @@ protected override void ProcessRecord() WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.PushedRunspaceMustBeOpen)), - PSRemotingErrorId.PushedRunspaceMustBeOpen.ToString(), + nameof(PSRemotingErrorId.PushedRunspaceMustBeOpen), ErrorCategory.InvalidArgument, null)); } @@ -556,7 +537,7 @@ protected override void StopProcessing() WriteError( new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.HostDoesNotSupportPushRunspace)), - PSRemotingErrorId.HostDoesNotSupportPushRunspace.ToString(), + nameof(PSRemotingErrorId.HostDoesNotSupportPushRunspace), ErrorCategory.InvalidArgument, null)); return; @@ -959,7 +940,7 @@ private RemoteRunspace GetRunspaceForVMSession() WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), - PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), + nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); @@ -971,7 +952,7 @@ private RemoteRunspace GetRunspaceForVMSession() WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.InvalidVMId), - PSRemotingErrorId.InvalidVMId.ToString(), + nameof(PSRemotingErrorId.InvalidVMId), ErrorCategory.InvalidArgument, null)); @@ -996,7 +977,7 @@ private RemoteRunspace GetRunspaceForVMSession() WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), - PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), + nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); @@ -1008,7 +989,7 @@ private RemoteRunspace GetRunspaceForVMSession() WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.InvalidVMNameNoVM), - PSRemotingErrorId.InvalidVMNameNoVM.ToString(), + nameof(PSRemotingErrorId.InvalidVMNameNoVM), ErrorCategory.InvalidArgument, null)); @@ -1019,7 +1000,7 @@ private RemoteRunspace GetRunspaceForVMSession() WriteError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.InvalidVMNameMultipleVM), - PSRemotingErrorId.InvalidVMNameMultipleVM.ToString(), + nameof(PSRemotingErrorId.InvalidVMNameMultipleVM), ErrorCategory.InvalidArgument, null)); @@ -1039,7 +1020,7 @@ private RemoteRunspace GetRunspaceForVMSession() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName)), - PSRemotingErrorId.InvalidVMState.ToString(), + nameof(PSRemotingErrorId.InvalidVMState), ErrorCategory.InvalidArgument, null)); diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index f375b356df4..aa804f68691 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1493,6 +1493,7 @@ private void WriteResultsForJobsInCollection(List jobs, bool checkForRecurs } private readonly Dictionary _eventArgsWritten = new Dictionary(); + private void WriteJobStateInformation(Job job, JobStateEventArgs args = null) { // at any point there will be only one thread which will have diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index 039427c7170..e36fb633783 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index 4771a86c1af..2eed427a6ff 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -1013,6 +1013,7 @@ private void HandleStopJobCompleted(object sender, AsyncCompletedEventArgs event private HashSet _pendingJobs = new HashSet(); private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); + private readonly Dictionary> _cleanUpActions = new Dictionary>(); diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs index 84bddf6439f..1b5fcd7bbe4 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 89a96b938af..29e6640279f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs index 54df5b8b748..7890bdc54f0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -253,6 +253,7 @@ var e in private readonly HashSet _pendingJobs = new HashSet(); private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); + private readonly Dictionary> _cleanUpActions = new Dictionary>(); diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs index 06015f2b139..1c729d8df74 100644 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs index 3add796b3c8..3e013caa05b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/TestPSSessionConfigurationFile.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index 45df8a25706..dd04519eb19 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index af1005faa6f..2a3c92dfcf3 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 1d1c6e5533b..5645272bbe2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -181,8 +181,7 @@ protected override void BeginProcessing() base.BeginProcessing(); _operationsComplete.Reset(); _throttleManager.ThrottleLimit = ThrottleLimit; - _throttleManager.ThrottleComplete += - new EventHandler(HandleThrottleComplete); + _throttleManager.ThrottleComplete += HandleThrottleComplete; if (string.IsNullOrEmpty(ConfigurationName)) { @@ -286,8 +285,7 @@ protected override void ProcessRecord() OpenRunspaceOperation operation = new OpenRunspaceOperation(remoteRunspace); // HandleRunspaceStateChanged callback is added before ThrottleManager complete // callback handlers so HandleRunspaceStateChanged will always be called first. - operation.OperationComplete += - new EventHandler(HandleRunspaceStateChanged); + operation.OperationComplete += HandleRunspaceStateChanged; remoteRunspace.URIRedirectionReported += HandleURIDirectionReported; operations.Add(operation); } @@ -416,12 +414,12 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s { if (sender == null) { - throw PSTraceSource.NewArgumentNullException("sender"); + throw PSTraceSource.NewArgumentNullException(nameof(sender)); } if (stateEventArgs == null) { - throw PSTraceSource.NewArgumentNullException("stateEventArgs"); + throw PSTraceSource.NewArgumentNullException(nameof(stateEventArgs)); } RunspaceStateEventArgs runspaceStateEventArgs = @@ -909,7 +907,7 @@ private List CreateRunspacesWhenVMParameterSpecified() ThrowTerminatingError( new ErrorRecord( new ArgumentException(RemotingErrorIdStrings.HyperVModuleNotAvailable), - PSRemotingErrorId.HyperVModuleNotAvailable.ToString(), + nameof(PSRemotingErrorId.HyperVModuleNotAvailable), ErrorCategory.NotInstalled, null)); @@ -927,7 +925,7 @@ private List CreateRunspacesWhenVMParameterSpecified() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMIdNotSingle, this.VMId[index].ToString(null))), - PSRemotingErrorId.InvalidVMIdNotSingle.ToString(), + nameof(PSRemotingErrorId.InvalidVMIdNotSingle), ErrorCategory.InvalidArgument, null)); @@ -941,7 +939,7 @@ private List CreateRunspacesWhenVMParameterSpecified() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMNameNotSingle, this.VMName[index])), - PSRemotingErrorId.InvalidVMNameNotSingle.ToString(), + nameof(PSRemotingErrorId.InvalidVMNameNotSingle), ErrorCategory.InvalidArgument, null)); @@ -962,7 +960,7 @@ private List CreateRunspacesWhenVMParameterSpecified() new ErrorRecord( new ArgumentException(GetMessage(RemotingErrorIdStrings.InvalidVMState, this.VMName[index])), - PSRemotingErrorId.InvalidVMState.ToString(), + nameof(PSRemotingErrorId.InvalidVMState), ErrorCategory.InvalidArgument, null)); @@ -1212,7 +1210,7 @@ protected void Dispose(bool disposing) _operationsComplete.WaitOne(); _operationsComplete.Dispose(); - _throttleManager.ThrottleComplete -= new EventHandler(HandleThrottleComplete); + _throttleManager.ThrottleComplete -= HandleThrottleComplete; _throttleManager = null; foreach (RemoteRunspace remoteRunspace in _toDispose) @@ -1321,8 +1319,7 @@ internal OpenRunspaceOperation(RemoteRunspace runspace) _startComplete = true; _stopComplete = true; OperatedRunspace = runspace; - OperatedRunspace.StateChanged += - new EventHandler(HandleRunspaceStateChanged); + OperatedRunspace.StateChanged += HandleRunspaceStateChanged; } /// @@ -1379,6 +1376,7 @@ internal override void StopOperation() // any exceptions thrown on this thread. (ThrottleManager will not respond if it doesn't // get a start/stop complete callback). private List> _internalCallbacks = new List>(); + internal override event EventHandler OperationComplete { add diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 57f38139d24..ad233ccb481 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -36,12 +36,12 @@ internal static bool HasRepeatingRunspaces(PSSession[] runspaceInfos) { if (runspaceInfos == null) { - throw PSTraceSource.NewArgumentNullException("runspaceInfos"); + throw PSTraceSource.NewArgumentNullException(nameof(runspaceInfos)); } if (runspaceInfos.GetLength(0) == 0) { - throw PSTraceSource.NewArgumentException("runspaceInfos"); + throw PSTraceSource.NewArgumentException(nameof(runspaceInfos)); } for (int i = 0; i < runspaceInfos.GetLength(0); i++) @@ -65,12 +65,12 @@ internal static bool ExceedMaximumAllowableRunspaces(PSSession[] runspaceInfos) { if (runspaceInfos == null) { - throw PSTraceSource.NewArgumentNullException("runspaceInfos"); + throw PSTraceSource.NewArgumentNullException(nameof(runspaceInfos)); } if (runspaceInfos.GetLength(0) == 0) { - throw PSTraceSource.NewArgumentException("runspaceInfos"); + throw PSTraceSource.NewArgumentException(nameof(runspaceInfos)); } return false; diff --git a/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs index f81570bd5d8..d4cf3877fd4 100644 --- a/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/removerunspacecommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs b/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs index f3961cb688d..3f1f20b4c6c 100644 --- a/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/runspacerepository.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs b/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs index 4e2ec57d264..a68a6f78869 100644 --- a/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/AsyncObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Threading; diff --git a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs index ef41f1985ee..035d39ac84e 100644 --- a/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs +++ b/src/System.Management.Automation/engine/remoting/common/DispatchTable.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/common/Indexer.cs b/src/System.Management.Automation/engine/remoting/common/Indexer.cs index 96c31e7b17f..0f6b70482c8 100644 --- a/src/System.Management.Automation/engine/remoting/common/Indexer.cs +++ b/src/System.Management.Automation/engine/remoting/common/Indexer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs index 6ad0dbd581e..25534b59a30 100644 --- a/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs +++ b/src/System.Management.Automation/engine/remoting/common/ObjectRef.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs index d2e08ad68c7..5eb9c5fc338 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs b/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs index 4c34f1d4d3b..616ca252d07 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSSessionConfigurationTypeOption.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index e618532f125..12bd7e1ad63 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; @@ -278,7 +278,7 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) throw new PSInvalidOperationException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketServerConstructorFailure), ex, - PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure.ToString(), + nameof(PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure), ErrorCategory.InvalidOperation, null); } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index eefe2f51f73..3a75567c10f 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -27,7 +27,6 @@ internal static class NamedPipeUtils { #region Strings - internal const string NamedPipeNamePrefix = "PSHost."; #if UNIX internal const string DefaultAppDomainName = "None"; @@ -96,7 +95,7 @@ internal static string CreateProcessPipeName( { if (proc == null) { - throw new PSArgumentNullException("proc"); + throw new PSArgumentNullException(nameof(proc)); } if (string.IsNullOrEmpty(appDomainName)) @@ -453,7 +452,7 @@ internal RemoteSessionNamedPipeServer( { if (pipeName == null) { - throw new PSArgumentNullException("pipeName"); + throw new PSArgumentNullException(nameof(pipeName)); } _syncObject = new object(); @@ -481,11 +480,11 @@ private NamedPipeServerStream CreateNamedPipe( string coreName, CommonSecurityDescriptor securityDesc) { - if (serverName == null) { throw new PSArgumentNullException("serverName"); } + if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); } - if (namespaceName == null) { throw new PSArgumentNullException("namespaceName"); } + if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); } - if (coreName == null) { throw new PSArgumentNullException("coreName"); } + if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); } #if !UNIX string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; @@ -560,9 +559,7 @@ static RemoteSessionNamedPipeServer() CreateIPCNamedPipeServerSingleton(); -#if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default - CreateAppDomainUnloadHandler(); -#endif + CreateProcessExitHandler(); } #endregion @@ -684,7 +681,7 @@ internal void StartListening( { if (clientConnectCallback == null) { - throw new PSArgumentNullException("clientConnectCallback"); + throw new PSArgumentNullException(nameof(clientConnectCallback)); } lock (_syncObject) @@ -961,30 +958,31 @@ internal static void CreateIPCNamedPipeServerSingleton() } } -#if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default - private static void CreateAppDomainUnloadHandler() + private static void CreateProcessExitHandler() { - // Subscribe to the app domain unload event. - AppDomain.CurrentDomain.DomainUnload += (sender, args) => + AppDomain.CurrentDomain.ProcessExit += (sender, args) => + { + IPCNamedPipeServerEnabled = false; + RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer; + if (namedPipeServer != null) { - IPCNamedPipeServerEnabled = false; - RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer; - if (namedPipeServer != null) + try { - try - { - // Terminate the IPC thread. - namedPipeServer.Dispose(); - } - catch (ObjectDisposedException) { } - catch (Exception) - { - // Don't throw an exception on the app domain unload event thread. - } + // Terminate the IPC thread. + namedPipeServer.Dispose(); } - }; + catch (ObjectDisposedException) + { + // Ignore if object already disposed. + } + catch (Exception) + { + // Don't throw an exception on the app domain unload event thread. + } + } + }; } -#endif + private static void OnIPCNamedPipeServerEnded(object sender, ListenerEndedEventArgs args) { if (args.RestartListener) @@ -1178,7 +1176,7 @@ internal RemoteSessionNamedPipeClient( { if (pipeName == null) { - throw new PSArgumentNullException("pipeName"); + throw new PSArgumentNullException(nameof(pipeName)); } _pipeName = pipeName; @@ -1198,11 +1196,11 @@ internal RemoteSessionNamedPipeClient( string namespaceName, string coreName) { - if (serverName == null) { throw new PSArgumentNullException("serverName"); } + if (serverName == null) { throw new PSArgumentNullException(nameof(serverName)); } - if (namespaceName == null) { throw new PSArgumentNullException("namespaceName"); } + if (namespaceName == null) { throw new PSArgumentNullException(nameof(namespaceName)); } - if (coreName == null) { throw new PSArgumentNullException("coreName"); } + if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); } _pipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; @@ -1284,7 +1282,7 @@ public ContainerSessionNamedPipeClient( { if (string.IsNullOrEmpty(containerObRoot)) { - throw new PSArgumentNullException("containerObRoot"); + throw new PSArgumentNullException(nameof(containerObRoot)); } // diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index f7312183c71..7f46151a857 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -232,6 +232,7 @@ public int OpenTimeout } private int _openTimeout = DefaultOpenTimeout; + internal const int DefaultOpenTimeout = 3 * 60 * 1000; // 3 minutes internal const int DefaultTimeout = -1; internal const int InfiniteTimeout = 0; @@ -280,7 +281,7 @@ public virtual void SetSessionOptions(PSSessionOption options) { if (options == null) { - throw new ArgumentNullException("options"); + throw new ArgumentNullException(nameof(options)); } if (options.Culture != null) @@ -688,9 +689,9 @@ public AuthenticationMechanism ProxyAuthentication default: string message = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ProxyAmbiguousAuthentication, value, - AuthenticationMechanism.Basic.ToString(), - AuthenticationMechanism.Negotiate.ToString(), - AuthenticationMechanism.Digest.ToString()); + nameof(AuthenticationMechanism.Basic), + nameof(AuthenticationMechanism.Negotiate), + nameof(AuthenticationMechanism.Digest)); throw new ArgumentException(message); } } @@ -974,7 +975,7 @@ public override void SetSessionOptions(PSSessionOption options) { if (options == null) { - throw new ArgumentNullException("options"); + throw new ArgumentNullException(nameof(options)); } if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential != null)) @@ -1348,7 +1349,7 @@ private void UpdateUri(Uri uri) #if NOT_APPLY_PORT_DCR private static string DEFAULT_SCHEME = HTTP_SCHEME; - internal static string DEFAULT_SSL_SCHEME = HTTPS_SCHEME; + internal static readonly string DEFAULT_SSL_SCHEME = HTTPS_SCHEME; private static string DEFAULT_APP_NAME = "wsman"; /// /// See below for explanation. @@ -1439,7 +1440,7 @@ internal bool IsLocalhostAndNetworkAccess return (EnableNetworkAccess && // Interactive token requested (Credential == null && // No credential provided (ComputerName.Equals(DefaultComputerName, StringComparison.OrdinalIgnoreCase) || // Localhost computer name - ComputerName.IndexOf('.') == -1))); // Not FQDN computer name + !ComputerName.Contains('.')))); // Not FQDN computer name } } @@ -1570,7 +1571,7 @@ public override AuthenticationMechanism AuthenticationMechanism if (value != AuthenticationMechanism.Default) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth, - value.ToString(), AuthenticationMechanism.Default.ToString()); + value.ToString(), nameof(AuthenticationMechanism.Default)); } _authMechanism = value; @@ -1645,6 +1646,7 @@ public sealed class NamedPipeConnectionInfo : RunspaceConnectionInfo private PSCredential _credential; private AuthenticationMechanism _authMechanism; private string _appDomainName = string.Empty; + private const int _defaultOpenTimeout = 60000; /* 60 seconds. */ #endregion @@ -1801,7 +1803,7 @@ public override AuthenticationMechanism AuthenticationMechanism if (value != Runspaces.AuthenticationMechanism.Default) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth, - value.ToString(), AuthenticationMechanism.Default.ToString()); + value.ToString(), nameof(AuthenticationMechanism.Default)); } _authMechanism = value; @@ -1912,7 +1914,7 @@ public SSHConnectionInfo( string computerName, string keyFilePath) { - if (computerName == null) { throw new PSArgumentNullException("computerName"); } + if (computerName == null) { throw new PSArgumentNullException(nameof(computerName)); } this.UserName = userName; this.ComputerName = computerName; @@ -2452,7 +2454,7 @@ private static int StartSSHProcessImpl( if ((ex != null) || (sshProcess == null) || - (sshProcess.HasExited == true)) + (sshProcess.HasExited)) { throw new InvalidOperationException( StringUtil.Format(RemotingErrorIdStrings.CannotStartSSHClient, (ex != null) ? ex.Message : string.Empty), @@ -2548,7 +2550,12 @@ private static Process CreateProcessWithRedirectedStd( try { - var cmdLine = string.Format(CultureInfo.InvariantCulture, @"""{0}"" {1}", startInfo.FileName, startInfo.Arguments); + // Create process start command line with filename and argument list. + var cmdLine = string.Format( + CultureInfo.InvariantCulture, + @"""{0}"" {1}", + startInfo.FileName, + string.Join(' ', startInfo.ArgumentList)); lpStartupInfo.hStdInput = new SafeFileHandle(stdInPipeClient.DangerousGetHandle(), false); lpStartupInfo.hStdOutput = new SafeFileHandle(stdOutPipeClient.DangerousGetHandle(), false); @@ -2656,7 +2663,7 @@ private static SafePipeHandle CreateNamedPipe( byte[] securityDescBuffer = new byte[securityDesc.BinaryLength]; securityDesc.GetBinaryForm(securityDescBuffer, 0); securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned); - securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value, true); ; + securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value, true); } // Create async named pipe. @@ -2699,6 +2706,7 @@ public sealed class VMConnectionInfo : RunspaceConnectionInfo private AuthenticationMechanism _authMechanism; private PSCredential _credential; + private const int _defaultOpenTimeout = 20000; /* 20 seconds. */ #endregion @@ -2735,7 +2743,7 @@ public override AuthenticationMechanism AuthenticationMechanism if (value != AuthenticationMechanism.Default) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth, - value.ToString(), AuthenticationMechanism.Default.ToString()); + value.ToString(), nameof(AuthenticationMechanism.Default)); } _authMechanism = value; @@ -2828,6 +2836,7 @@ public sealed class ContainerConnectionInfo : RunspaceConnectionInfo private AuthenticationMechanism _authMechanism; private PSCredential _credential; + private const int _defaultOpenTimeout = 20000; /* 20 seconds. */ #endregion @@ -2859,7 +2868,7 @@ public override AuthenticationMechanism AuthenticationMechanism if (value != AuthenticationMechanism.Default) { throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.IPCSupportsOnlyDefaultAuth, - value.ToString(), AuthenticationMechanism.Default.ToString()); + value.ToString(), nameof(AuthenticationMechanism.Default)); } _authMechanism = value; diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs index 629a046b492..ad193fc914b 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceInitInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs index cac5184e075..e863a7c795e 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Runspaces; 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 eb997d8a44e..85ba02b2e7b 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -1414,7 +1414,7 @@ internal static RemoteDataObject GeneratePowerShellInformational(ProgressRecord { if (progressRecord == null) { - throw PSTraceSource.NewArgumentNullException("progressRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } return RemoteDataObject.CreateFrom(RemotingDestination.Client, @@ -1447,7 +1447,7 @@ internal static RemoteDataObject GeneratePowerShellInformational(InformationReco { if (informationRecord == null) { - throw PSTraceSource.NewArgumentNullException("informationRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(informationRecord)); } return RemoteDataObject.CreateFrom(RemotingDestination.Client, @@ -1637,7 +1637,7 @@ private static T ConvertPropertyValueTo(string propertyName, object propertyV { if (propertyName == null) // comes from internal caller { - throw PSTraceSource.NewArgumentNullException("propertyName"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } if (typeof(T).IsEnum) @@ -1745,12 +1745,12 @@ private static PSPropertyInfo GetProperty(PSObject psObject, string propertyName { if (psObject == null) { - throw PSTraceSource.NewArgumentNullException("psObject"); + throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } if (propertyName == null) { - throw PSTraceSource.NewArgumentNullException("propertyName"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } PSPropertyInfo property = psObject.Properties[propertyName]; @@ -1767,12 +1767,12 @@ internal static T GetPropertyValue(PSObject psObject, string propertyName) { if (psObject == null) { - throw PSTraceSource.NewArgumentNullException("psObject"); + throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } if (propertyName == null) { - throw PSTraceSource.NewArgumentNullException("propertyName"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } PSPropertyInfo property = GetProperty(psObject, propertyName); @@ -1784,12 +1784,12 @@ internal static IEnumerable EnumerateListProperty(PSObject psObject, strin { if (psObject == null) { - throw PSTraceSource.NewArgumentNullException("psObject"); + throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } if (propertyName == null) { - throw PSTraceSource.NewArgumentNullException("propertyName"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } IEnumerable e = GetPropertyValue(psObject, propertyName); @@ -1806,12 +1806,12 @@ internal static IEnumerable> EnumerateHashtable { if (psObject == null) { - throw PSTraceSource.NewArgumentNullException("psObject"); + throw PSTraceSource.NewArgumentNullException(nameof(psObject)); } if (propertyName == null) { - throw PSTraceSource.NewArgumentNullException("propertyName"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyName)); } Hashtable h = GetPropertyValue(psObject, propertyName); @@ -1836,7 +1836,7 @@ internal static RunspacePoolStateInfo GetRunspacePoolStateInfo(PSObject dataAsPS { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } RunspacePoolState state = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.RunspaceState); @@ -1855,7 +1855,7 @@ internal static PSPrimitiveDictionary GetApplicationPrivateData(PSObject dataAsP { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.ApplicationPrivateData); @@ -1870,7 +1870,7 @@ internal static string GetPublicKey(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.PublicKey); @@ -1885,7 +1885,7 @@ internal static string GetEncryptedSessionKey(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.EncryptedSessionKey); @@ -1901,7 +1901,7 @@ internal static PSEventArgs GetPSEventArgs(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } int eventIdentifier = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.PSEventArgsEventIdentifier); @@ -1941,7 +1941,7 @@ internal static int GetMinRunspaces(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MinRunspaces); @@ -1957,7 +1957,7 @@ internal static int GetMaxRunspaces(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MaxRunspaces); @@ -1973,7 +1973,7 @@ internal static PSPrimitiveDictionary GetApplicationArguments(PSObject dataAsPSO { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } // rehydration might not work yet (there is no type table before a runspace is created) @@ -1990,7 +1990,7 @@ internal static RunspacePoolInitInfo GetRunspacePoolInitInfo(PSObject dataAsPSOb { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } int maxRS = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.MaxRunspaces); @@ -2009,7 +2009,7 @@ internal static PSThreadOptions GetThreadOptions(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } return GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.ThreadOptions); @@ -2025,7 +2025,7 @@ internal static HostInfo GetHostInfo(PSObject dataAsPSObject) { if (dataAsPSObject == null) { - throw PSTraceSource.NewArgumentNullException("dataAsPSObject"); + throw PSTraceSource.NewArgumentNullException(nameof(dataAsPSObject)); } PSObject propertyValue = GetPropertyValue(dataAsPSObject, RemoteDataNameStrings.HostInfo); @@ -2109,7 +2109,7 @@ internal static ErrorRecord GetPowerShellError(object data) { if (data == null) { - throw PSTraceSource.NewArgumentNullException("data"); + throw PSTraceSource.NewArgumentNullException(nameof(data)); } PSObject dataAsPSObject = data as PSObject; @@ -2126,7 +2126,7 @@ internal static WarningRecord GetPowerShellWarning(object data) { if (data == null) { - throw PSTraceSource.NewArgumentNullException("data"); + throw PSTraceSource.NewArgumentNullException(nameof(data)); } return new WarningRecord((PSObject)data); @@ -2139,7 +2139,7 @@ internal static VerboseRecord GetPowerShellVerbose(object data) { if (data == null) { - throw PSTraceSource.NewArgumentNullException("data"); + throw PSTraceSource.NewArgumentNullException(nameof(data)); } return new VerboseRecord((PSObject)data); @@ -2152,7 +2152,7 @@ internal static DebugRecord GetPowerShellDebug(object data) { if (data == null) { - throw PSTraceSource.NewArgumentNullException("data"); + throw PSTraceSource.NewArgumentNullException(nameof(data)); } return new DebugRecord((PSObject)data); diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs index b4d5072e046..8314337b77a 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs index 562e58db8bc..414676dffed 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs index ef27c874c42..8a60ce277a8 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index bde35ad9de1..bc5d47c8a83 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs index f4e9a943837..664c2a91ae0 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index a2b34d5fb8c..2ebe434ea04 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -467,6 +467,7 @@ internal class SerializedDataStream : Stream, IDisposable /// true if data represents EndFragment of an object. /// internal delegate void OnDataAvailableCallback(byte[] data, bool isEndFragment); + private OnDataAvailableCallback _onDataAvailableCallback; #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/misc.cs b/src/System.Management.Automation/engine/remoting/common/misc.cs index 9d515b2c7c9..e5b1f1edc04 100644 --- a/src/System.Management.Automation/engine/remoting/common/misc.cs +++ b/src/System.Management.Automation/engine/remoting/common/misc.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Remoting; @@ -17,7 +17,7 @@ internal RemoteSessionNegotiationEventArgs(RemoteSessionCapability remoteSession if (remoteSessionCapability == null) { - throw PSTraceSource.NewArgumentNullException("remoteSessionCapability"); + throw PSTraceSource.NewArgumentNullException(nameof(remoteSessionCapability)); } RemoteSessionCapability = remoteSessionCapability; @@ -50,7 +50,7 @@ internal RemoteDataEventArgs(RemoteDataObject receivedData) if (receivedData == null) { - throw PSTraceSource.NewArgumentNullException("receivedData"); + throw PSTraceSource.NewArgumentNullException(nameof(receivedData)); } ReceivedData = receivedData; @@ -314,7 +314,7 @@ internal RemoteSessionStateEventArgs(RemoteSessionStateInfo remoteSessionStateIn if (remoteSessionStateInfo == null) { - PSTraceSource.NewArgumentNullException("remoteSessionStateInfo"); + PSTraceSource.NewArgumentNullException(nameof(remoteSessionStateInfo)); } SessionStateInfo = remoteSessionStateInfo; diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index e08c768f95a..fa1bcb7da86 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Runspaces; diff --git a/src/System.Management.Automation/engine/remoting/common/remotesession.cs b/src/System.Management.Automation/engine/remoting/common/remotesession.cs index e0d6ff4687c..662a7344068 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotesession.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotesession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Remoting; diff --git a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs index 928bf627284..72f404bce10 100644 --- a/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs +++ b/src/System.Management.Automation/engine/remoting/common/remotingexceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -209,7 +209,6 @@ internal enum PSRemotingErrorId : uint RemoteRunspaceHasMultipleMatchesForSpecifiedName = 955, RemoteRunspaceDoesNotSupportPushRunspace = 956, HostInNestedPrompt = 957, - RemoteHostDoesNotSupportPushRunspace = 958, InvalidVMId = 959, InvalidVMNameNoVM = 960, InvalidVMNameMultipleVM = 961, @@ -476,7 +475,7 @@ protected PSRemotingTransportException(SerializationInfo info, StreamingContext { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } _errorCode = info.GetInt32("ErrorCode"); @@ -495,7 +494,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -619,7 +618,7 @@ protected PSRemotingTransportRedirectException(SerializationInfo info, Streaming { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } RedirectLocation = info.GetString("RedirectLocation"); @@ -660,7 +659,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index ed133110b7f..9fa2233153f 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -527,8 +527,7 @@ private void StartOneOperationFromQueue() { operation = _operationsQueue[0]; _operationsQueue.RemoveAt(0); - operation.OperationComplete += - new EventHandler(OperationCompleteHandler); + operation.OperationComplete += OperationCompleteHandler; _startOperationQueue.Add(operation); } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 082a8852552..0f7f46438cd 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* @@ -818,7 +818,7 @@ internal void ServicePendingCallbacks(object objectToProcess) { // If queue is empty or if queue servicing is suspended // then break out of loop. - if (_callbackNotificationQueue.Count <= 0 || _suspendQueueServicing) + if (_callbackNotificationQueue.Count == 0 || _suspendQueueServicing) { break; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 27bd8066da8..1a9642ca7c2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -138,7 +138,7 @@ private void Update(string optionName, string optionValue) case CONFIGFILEPATH: { AssertValueNotAssigned(CONFIGFILEPATH, ConfigFilePath); - ConfigFilePath = optionValue.ToString(); + ConfigFilePath = optionValue; } break; @@ -243,9 +243,6 @@ internal static ConfigurationDataFromXML Create(string initializationParameters) readerSettings.IgnoreProcessingInstructions = true; readerSettings.MaxCharactersInDocument = 10000; readerSettings.ConformanceLevel = ConformanceLevel.Fragment; -#if !CORECLR // No XmlReaderSettings.XmlResolver in CoreCLR - readerSettings.XmlResolver = null; -#endif using (XmlReader reader = XmlReader.Create(new StringReader(initializationParameters), readerSettings)) { @@ -531,7 +528,7 @@ private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBas assembly = LoadSsnStateProviderAssembly(applicationBase, assemblyName); if (assembly == null) { - throw PSTraceSource.NewArgumentException("assemblyName", RemotingErrorIdStrings.UnableToLoadAssembly, + throw PSTraceSource.NewArgumentException(nameof(assemblyName), RemotingErrorIdStrings.UnableToLoadAssembly, assemblyName, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } } @@ -548,7 +545,7 @@ private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBas Type type = assembly.GetType(typeToLoad, true, true); if (type == null) { - throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType, + throw PSTraceSource.NewArgumentException(nameof(typeToLoad), RemotingErrorIdStrings.UnableToLoadType, typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } @@ -575,7 +572,7 @@ private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBas // if we are here, that means we are unable to load the type specified // in the config xml.. notify the same. - throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType, + throw PSTraceSource.NewArgumentException(nameof(typeToLoad), RemotingErrorIdStrings.UnableToLoadType, typeToLoad, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } @@ -766,19 +763,19 @@ private static string Dbg.Assert(registryKey != null, "Caller should validate the registryKey parameter"); object value = registryKey.GetValue(name); - if (value == null && mandatory == true) + if (value == null && mandatory) { s_tracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, registryKey.Name); - throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotPresent, name, registryKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), RemotingErrorIdStrings.MandatoryValueNotPresent, name, registryKey.Name); } string s = value as string; - if (string.IsNullOrEmpty(s) && mandatory == true) + if (string.IsNullOrEmpty(s) && mandatory) { s_tracer.TraceError("Value is null or empty for mandatory property {0} in {1}", name, registryKey.Name); - throw PSTraceSource.NewArgumentException("name", RemotingErrorIdStrings.MandatoryValueNotInCorrectFormat, name, registryKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), RemotingErrorIdStrings.MandatoryValueNotInCorrectFormat, name, registryKey.Name); } return s; @@ -787,8 +784,10 @@ private static string private const string configProvidersKeyName = "PSConfigurationProviders"; private const string configProviderApplicationBaseKeyName = "ApplicationBase"; private const string configProviderAssemblyNameKeyName = "AssemblyName"; + private static Dictionary s_ssnStateProviders = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static object s_syncObject = new object(); #endregion @@ -815,13 +814,13 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { if (sessionConfigurationData == null) - throw new ArgumentNullException("sessionConfigurationData"); + throw new ArgumentNullException(nameof(sessionConfigurationData)); if (senderInfo == null) - throw new ArgumentNullException("senderInfo"); + throw new ArgumentNullException(nameof(senderInfo)); if (configProviderId == null) - throw new ArgumentNullException("configProviderId"); + throw new ArgumentNullException(nameof(configProviderId)); InitialSessionState sessionState = InitialSessionState.CreateDefault2(); // now get all the modules in the specified path and import the same @@ -949,7 +948,7 @@ internal static class ConfigFileConstants internal static readonly string VisibleProviders = "VisibleProviders"; internal static readonly string VisibleExternalCommands = "VisibleExternalCommands"; - internal static ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] { + internal static readonly ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] { new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)), new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), @@ -1789,6 +1788,7 @@ private void MergeRoleRulesIntoConfigHash(Func roleVerifier) // Takes the "RoleCapabilities" node in the config hash, and merges its values into the base configuration. private const string PSRCExtension = ".psrc"; + private void MergeRoleCapabilitiesIntoConfigHash() { List psrcFiles = new List(); @@ -1899,7 +1899,7 @@ private void MergeConfigHashIntoConfigHash(IDictionary childConfigHash) private string GetRoleCapabilityPath(string roleCapability) { string moduleName = "*"; - if (roleCapability.IndexOf('\\') != -1) + if (roleCapability.Contains('\\')) { string[] components = roleCapability.Split(Utils.Separators.Backslash, 2); moduleName = components[0]; @@ -2392,7 +2392,7 @@ public override InitialSessionState GetInitialSessionState(PSSenderInfo senderIn // Process User Drive if (_configHash.ContainsKey(ConfigFileConstants.MountUserDrive)) { - if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture) == true) + if (Convert.ToBoolean(_configHash[ConfigFileConstants.MountUserDrive], CultureInfo.InvariantCulture)) { iss.UserDriveEnabled = true; iss.UserDriveUserName = (senderInfo != null) ? senderInfo.UserInfo.Identity.Name : null; diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index 35913a1f7ba..bc39b8f6937 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* @@ -196,8 +196,8 @@ internal static void ProcessData(string data, DataProcessingDelegates callbacks) default: throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownNodeType, RemotingErrorIdStrings.IPCUnknownNodeType, reader.NodeType.ToString(), - XmlNodeType.Element.ToString(), - XmlNodeType.EndElement.ToString()); + nameof(XmlNodeType.Element), + nameof(XmlNodeType.EndElement)); } } } @@ -544,7 +544,7 @@ internal override void CloseAsync() bool shouldRaiseCloseCompleted = false; lock (syncObject) { - if (isClosed == true) + if (isClosed) { return; } @@ -760,7 +760,7 @@ protected void HandleOutputDataReceived(string data) try { // Route protocol message based on whether it is a session or command message. - if (data.IndexOf(SESSIONDMESSAGETAG, StringComparison.OrdinalIgnoreCase) > -1) + if (data.Contains(SESSIONDMESSAGETAG, StringComparison.OrdinalIgnoreCase)) { // Session message _sessionMessageQueue.Add(data); @@ -903,7 +903,7 @@ private void OnRemoteSessionSendCompleted() private void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid) { string streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_STDOUT; - if (stream.Equals(DataPriorityType.PromptResponse.ToString(), StringComparison.OrdinalIgnoreCase)) + if (stream.Equals(nameof(DataPriorityType.PromptResponse), StringComparison.OrdinalIgnoreCase)) { streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE; } @@ -1098,7 +1098,6 @@ internal override void CreateAsync() { _processCreated = false; } - // _processInstance.Start(); } PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, @@ -1123,28 +1122,10 @@ internal override void CreateAsync() _processInstance.RunspacePool.Dispose(); } - stdInWriter = _processInstance.StdInWriter; - // if (stdInWriter == null) - { - _serverProcess.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); - _serverProcess.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); - } - - _serverProcess.Exited += new EventHandler(OnExited); - - // serverProcess.Start(); + _serverProcess.Exited += OnExited; _processInstance.Start(); - if (stdInWriter != null) - { - _serverProcess.CancelErrorRead(); - _serverProcess.CancelOutputRead(); - } - - // Start asynchronous reading of output/errors - _serverProcess.BeginOutputReadLine(); - _serverProcess.BeginErrorReadLine(); - + StartRedirectionReaderThreads(_serverProcess); stdInWriter = new OutOfProcessTextWriter(_serverProcess.StandardInput); _processInstance.StdInWriter = stdInWriter; } @@ -1172,6 +1153,86 @@ internal override void CreateAsync() SendOneItem(); } + private void StartRedirectionReaderThreads(Process serverProcess) + { + Thread outputThread = new Thread(ProcessOutputData); + outputThread.IsBackground = true; + outputThread.Name = "Out-of-Proc Job Output Thread"; + + Thread errorThread = new Thread(ProcessErrorData); + errorThread.IsBackground = true; + errorThread.Name = "Out-of-Proc Job Error Thread"; + + outputThread.Start(serverProcess.StandardOutput); + errorThread.Start(serverProcess.StandardError); + } + + private void ProcessOutputData(object arg) + { + if (arg is StreamReader reader) + { + try + { + string data = reader.ReadLine(); + while (data != null) + { + HandleOutputDataReceived(data); + data = reader.ReadLine(); + } + } + catch (IOException) + { + // Treat this as EOF, the same as what 'Process.BeginOutputReadLine()' does. + } + catch (Exception e) + { + _tracer.WriteMessage( + "OutOfProcessClientSessionTransportManager", + "ProcessOutputThread", + Guid.Empty, + "Transport manager output reader thread ended with error: {0}", + e.Message ?? string.Empty); + } + } + else + { + Dbg.Assert(false, "Invalid argument. Expecting a StreamReader object."); + } + } + + private void ProcessErrorData(object arg) + { + if (arg is StreamReader reader) + { + try + { + string data = reader.ReadLine(); + while (data != null) + { + HandleErrorDataReceived(data); + data = reader.ReadLine(); + } + } + catch (IOException) + { + // Treat this as EOF, the same as what 'Process.BeginErrorReadLine()' does. + } + catch (Exception e) + { + _tracer.WriteMessage( + "OutOfProcessClientSessionTransportManager", + "ProcessErrorThread", + Guid.Empty, + "Transport manager error reader thread ended with error: {0}", + e.Message ?? string.Empty); + } + } + else + { + Dbg.Assert(false, "Invalid argument. Expecting a StreamReader object."); + } + } + /// /// Kills the server process and disposes other resources. /// @@ -1198,20 +1259,6 @@ protected override void CleanupConnection() #endregion - #region Event Handlers - - private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) - { - HandleOutputDataReceived(e.Data); - } - - private void OnErrorDataReceived(object sender, DataReceivedEventArgs e) - { - HandleErrorDataReceived(e.Data); - } - - #endregion - #region Helper Methods private void KillServerProcess() @@ -1230,13 +1277,8 @@ private void KillServerProcess() if (_processCreated) { - _serverProcess.CancelOutputRead(); - _serverProcess.CancelErrorRead(); _serverProcess.Kill(); } - - _serverProcess.OutputDataReceived -= new DataReceivedEventHandler(OnOutputDataReceived); - _serverProcess.ErrorDataReceived -= new DataReceivedEventHandler(OnErrorDataReceived); } } catch (System.ComponentModel.Win32Exception) @@ -1267,6 +1309,7 @@ internal abstract class HyperVSocketClientSessionTransportManagerBase : OutOfPro #region Data protected RemoteSessionHyperVSocketClient _client; + private const string _threadName = "HyperVSocketTransport Reader Thread"; #endregion @@ -1402,7 +1445,7 @@ internal VMHyperVSocketClientSessionTransportManager( { if (connectionInfo == null) { - throw new PSArgumentNullException("connectionInfo"); + throw new PSArgumentNullException(nameof(connectionInfo)); } _connectionInfo = connectionInfo; @@ -1436,7 +1479,7 @@ internal override void CreateAsync() throw new PSInvalidOperationException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.VMSessionConnectFailed), null, - PSRemotingErrorId.VMSessionConnectFailed.ToString(), + nameof(PSRemotingErrorId.VMSessionConnectFailed), ErrorCategory.InvalidOperation, null); } @@ -1450,7 +1493,7 @@ internal override void CreateAsync() throw new PSInvalidOperationException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.VMSessionConnectFailed), null, - PSRemotingErrorId.VMSessionConnectFailed.ToString(), + nameof(PSRemotingErrorId.VMSessionConnectFailed), ErrorCategory.InvalidOperation, null); } @@ -1485,7 +1528,7 @@ internal ContainerHyperVSocketClientSessionTransportManager( { if (connectionInfo == null) { - throw new PSArgumentNullException("connectionInfo"); + throw new PSArgumentNullException(nameof(connectionInfo)); } _connectionInfo = connectionInfo; @@ -1509,7 +1552,7 @@ internal override void CreateAsync() throw new PSInvalidOperationException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ContainerSessionConnectFailed), null, - PSRemotingErrorId.ContainerSessionConnectFailed.ToString(), + nameof(PSRemotingErrorId.ContainerSessionConnectFailed), ErrorCategory.InvalidOperation, null); } @@ -1534,6 +1577,7 @@ internal sealed class SSHClientSessionTransportManager : OutOfProcessClientSessi private StreamReader _stdOutReader; private StreamReader _stdErrReader; private bool _connectionEstablished; + private const string _threadName = "SSHTransport Reader Thread"; #endregion @@ -1708,7 +1752,7 @@ private static string ReadError(StreamReader reader) } if ((error.Length == 0) || - error.IndexOf("WARNING:", StringComparison.OrdinalIgnoreCase) > -1) + error.Contains("WARNING:", StringComparison.OrdinalIgnoreCase)) { // Handle as interactive warning message Console.WriteLine(error); @@ -1833,7 +1877,7 @@ internal NamedPipeClientSessionTransportManagerBase( { if (connectionInfo == null) { - throw new PSArgumentNullException("connectionInfo"); + throw new PSArgumentNullException(nameof(connectionInfo)); } _connectionInfo = connectionInfo; @@ -1944,6 +1988,7 @@ internal sealed class NamedPipeClientSessionTransportManager : NamedPipeClientSe #region Private Data private NamedPipeConnectionInfo _connectionInfo; + private const string _threadName = "NamedPipeTransport Reader Thread"; #endregion @@ -1958,7 +2003,7 @@ internal NamedPipeClientSessionTransportManager( { if (connectionInfo == null) { - throw new PSArgumentNullException("connectionInfo"); + throw new PSArgumentNullException(nameof(connectionInfo)); } _connectionInfo = connectionInfo; @@ -2011,6 +2056,7 @@ internal sealed class ContainerNamedPipeClientSessionTransportManager : NamedPip #region Private Data private ContainerConnectionInfo _connectionInfo; + private const string _threadName = "ContainerNamedPipeTransport Reader Thread"; #endregion @@ -2025,7 +2071,7 @@ internal ContainerNamedPipeClientSessionTransportManager( { if (connectionInfo == null) { - throw new PSArgumentNullException("connectionInfo"); + throw new PSArgumentNullException(nameof(connectionInfo)); } _connectionInfo = connectionInfo; @@ -2121,7 +2167,7 @@ internal override void CloseAsync() { lock (syncObject) { - if (isClosed == true) + if (isClosed) { return; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index 32ce3834bce..1341c9e0a83 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index 52a2a9ed805..17aac7adfdf 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -189,7 +189,7 @@ private void Update(string optionName, string optionValue) AssertValueNotAssigned(ModulesToImportToken, _modulesToImport); _modulesToImport = new List(); _modulesToImportInternal = new List(); - object[] modulesToImport = optionValue.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); + object[] modulesToImport = optionValue.Split(',', StringSplitOptions.RemoveEmptyEntries); foreach (var module in modulesToImport) { var s = module as string; diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 5c559536435..6c2b64479f4 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index f8f21fc03a0..1b1fe2b2163 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -23,7 +23,9 @@ internal static class WSManNativeApi internal const string ResourceURIPrefix = @"http://schemas.microsoft.com/powershell/"; internal const string NoProfile = "WINRS_NOPROFILE"; internal const string CodePage = "WINRS_CODEPAGE"; + internal static readonly Version WSMAN_STACK_VERSION = new Version(3, 0); + internal const int WSMAN_FLAG_REQUESTED_API_VERSION_1_1 = 1; // WSMan's default max env size in V2 internal const int WSMAN_DEFAULT_MAX_ENVELOPE_SIZE_KB_V2 = 150; @@ -623,6 +625,7 @@ internal class WSManDataStruct internal class WSManBinaryOrTextDataStruct { internal int bufferLength; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr data; } @@ -633,8 +636,10 @@ internal class WSManBinaryOrTextDataStruct internal class WSManData_ManToUn : IDisposable { private WSManDataStruct _internalData; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _marshalledObject = IntPtr.Zero; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _marshalledBuffer = IntPtr.Zero; @@ -766,6 +771,7 @@ internal class WSManData_UnToMan /// Gets the type of data. /// private uint _type; + internal uint Type { get { return _type; } @@ -777,6 +783,7 @@ internal uint Type /// Gets the buffer length of data. /// private int _bufferLength; + internal int BufferLength { get { return _bufferLength; } @@ -785,6 +792,7 @@ internal int BufferLength } private string _text; + internal string Text { get @@ -797,6 +805,7 @@ internal string Text } private byte[] _data; + internal byte[] Data { get @@ -927,6 +936,7 @@ private struct WSManDWordDataInternal internal struct WSManStreamIDSetStruct { internal int streamIDsCount; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr streamIDs; } @@ -1081,6 +1091,7 @@ internal struct WSManOptionSetStruct /// [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr options; + internal bool optionsMustUnderstand; } @@ -1215,11 +1226,13 @@ internal struct WSManCommandArgSet : IDisposable internal struct WSManCommandArgSetInternal { internal int argsCount; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr args; } private WSManCommandArgSetInternal _internalData; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private MarshalledObject _data; @@ -1547,6 +1560,7 @@ internal struct WSManEnvironmentVariableInternal { [MarshalAs(UnmanagedType.LPWStr)] internal string name; + [MarshalAs(UnmanagedType.LPWStr)] internal string value; } @@ -1722,6 +1736,7 @@ internal struct WSManShellAsyncCallback { // GC handle which prevents garbage collector from collecting this delegate. private GCHandle _gcHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _asyncCallback; @@ -1959,9 +1974,12 @@ private struct WSManReceiveDataResultInternal { [MarshalAs(UnmanagedType.LPWStr)] internal string streamId; + internal WSManDataStruct data; + [MarshalAs(UnmanagedType.LPWStr)] internal string commandState; + internal int exitCode; } @@ -2066,8 +2084,10 @@ private struct WSManPluginRequestInternal /// WSManSenderDetails. /// internal IntPtr senderDetails; + [MarshalAs(UnmanagedType.LPWStr)] internal string locale; + [MarshalAs(UnmanagedType.LPWStr)] internal string resourceUri; /// @@ -2119,6 +2139,7 @@ private struct WSManSenderDetailsInternal { [MarshalAs(UnmanagedType.LPWStr)] internal string senderName; + [MarshalAs(UnmanagedType.LPWStr)] internal string authenticationMechanism; /// @@ -2126,6 +2147,7 @@ private struct WSManSenderDetailsInternal /// internal IntPtr certificateDetails; internal IntPtr clientToken; + [MarshalAs(UnmanagedType.LPWStr)] internal string httpUrl; } @@ -2168,10 +2190,13 @@ private struct WSManCertificateDetailsInternal { [MarshalAs(UnmanagedType.LPWStr)] internal string subject; + [MarshalAs(UnmanagedType.LPWStr)] internal string issuerName; + [MarshalAs(UnmanagedType.LPWStr)] internal string issuerThumbprint; + [MarshalAs(UnmanagedType.LPWStr)] internal string subjectName; } @@ -2228,6 +2253,7 @@ internal struct WSManFragmentInternal { [MarshalAs(UnmanagedType.LPWStr)] internal string path; + [MarshalAs(UnmanagedType.LPWStr)] internal string dialect; } @@ -2240,6 +2266,7 @@ internal struct WSManFilterInternal { [MarshalAs(UnmanagedType.LPWStr)] internal string filter; + [MarshalAs(UnmanagedType.LPWStr)] internal string dialect; } @@ -2299,6 +2326,7 @@ internal struct WSManKeyStruct { [MarshalAs(UnmanagedType.LPWStr)] internal string key; + [MarshalAs(UnmanagedType.LPWStr)] internal string value; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 692288e74f6..d5eb990ec57 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ---------------------------------------------------------------------- // Contents: Entry points for managed PowerShell plugin worker used to @@ -137,7 +137,7 @@ internal class WSManPluginInstance /// It is static because static instances of this class use the facade. Otherwise, /// it would be passed in via a parameterized constructor. /// - internal static IWSManNativeApiFacade wsmanPinvokeStatic = new WSManNativeApiFacade(); + internal static readonly IWSManNativeApiFacade wsmanPinvokeStatic = new WSManNativeApiFacade(); #endregion @@ -187,6 +187,15 @@ internal void CreateShell( WSManNativeApi.WSManShellStartupInfo_UnToMan startupInfo, WSManNativeApi.WSManData_UnToMan inboundShellInformation) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateRemoteSession, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + "null", + "CreateShell: Create a new shell in the plugin context", + string.Empty); + if (requestDetails == null) { // Nothing can be done because requestDetails are required to report operation complete @@ -228,6 +237,15 @@ internal void CreateShell( return; } + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateRemoteSession, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + requestDetails.ToString(), + "CreateShell: NULL checks being performed", + string.Empty); + if ((0 == startupInfo.inputStreamSet.streamIDsCount) || (0 == startupInfo.outputStreamSet.streamIDsCount)) { ReportOperationComplete( @@ -282,11 +300,12 @@ internal void CreateShell( serverTransportMgr = new WSManPluginServerTransportManager(BaseTransportManager.DefaultFragmentSize, null); } - PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateRemoteSession, + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateRemoteSession, PSOpcode.Connect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, requestDetails.ToString(), senderInfo.UserInfo.Identity.Name, requestDetails.resourceUri); - ServerRemoteSession remoteShellSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo, + ServerRemoteSession remoteShellSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo, requestDetails.resourceUri, extraInfo, serverTransportMgr); @@ -309,7 +328,7 @@ internal void CreateShell( // Create a shell session wrapper to track and service future interactions. mgdShellSession = new WSManPluginShellSession(requestDetails, serverTransportMgr, remoteShellSession, context); AddToActiveShellSessions(mgdShellSession); - mgdShellSession.SessionClosed += new EventHandler(HandleShellSessionClosed); + mgdShellSession.SessionClosed += HandleShellSessionClosed; if (inboundShellInformation != null) { @@ -334,7 +353,8 @@ internal void CreateShell( } // now report the shell context to WSMan. - PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext, + PSEtwLog.LogAnalyticInformational( + PSEventId.ReportContext, PSOpcode.Connect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, requestDetails.ToString(), requestDetails.ToString()); @@ -445,6 +465,15 @@ internal void CreateShell( return; } + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateRemoteSession, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + requestDetails.ToString(), + "CreateShell: Completed", + string.Empty); + return; } @@ -455,9 +484,11 @@ internal void CreateShell( internal void CloseShellOperation( WSManPluginOperationShutdownContext context) { - PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation, - PSOpcode.Disconnect, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCloseOperation, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, ((IntPtr)context.shellContext).ToString(), ((IntPtr)context.commandContext).ToString(), context.isReceiveOperation.ToString()); @@ -478,13 +509,23 @@ internal void CloseShellOperation( System.Exception reasonForClose = new System.Exception(RemotingErrorIdStrings.WSManPluginOperationClose); mgdShellSession.CloseOperation(context, reasonForClose); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCloseOperation, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + "CloseShellOperation: Completed", + string.Empty); } internal void CloseCommandOperation( WSManPluginOperationShutdownContext context) { - PSEtwLog.LogAnalyticInformational(PSEventId.ServerCloseOperation, - PSOpcode.Disconnect, PSTask.None, + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCloseOperation, + PSOpcode.Disconnect, + PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, context.shellContext.ToString(), context.commandContext.ToString(), @@ -499,6 +540,14 @@ internal void CloseCommandOperation( } mgdShellSession.CloseCommandOperation(context); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCloseOperation, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + "CloseCommandOperation: Completed", + string.Empty); } /// @@ -598,7 +647,8 @@ private bool validateIncomingContexts( if (requestDetails == null) { // Nothing can be done because requestDetails are required to report operation complete - PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete, + PSEtwLog.LogAnalyticInformational( + PSEventId.ReportOperationComplete, PSOpcode.Close, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, "null", @@ -643,6 +693,15 @@ internal void CreateCommand( string commandLine, WSManNativeApi.WSManCommandArgSet arguments) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateCommandSession, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "CreateCommand: Create a new command in the shell context", + string.Empty); + if (!validateIncomingContexts(requestDetails, shellContext, "WSManRunShellCommandEx")) { return; @@ -650,9 +709,10 @@ internal void CreateCommand( SetThreadProperties(requestDetails); - PSEtwLog.LogAnalyticInformational(PSEventId.ServerCreateCommandSession, - PSOpcode.Connect, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateCommandSession, + PSOpcode.Connect, PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, ((IntPtr)shellContext).ToString(), requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); @@ -667,6 +727,15 @@ internal void CreateCommand( } mgdShellSession.CreateCommand(pluginContext, requestDetails, flags, commandLine, arguments); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerCreateCommandSession, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "CreateCommand: Create a new command in the shell context completed", + string.Empty); } internal void StopCommand( @@ -677,7 +746,8 @@ internal void StopCommand( if (requestDetails == null) { // Nothing can be done because requestDetails are required to report operation complete - PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete, + PSEtwLog.LogAnalyticInformational( + PSEventId.ReportOperationComplete, PSOpcode.Close, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, "null", @@ -692,12 +762,14 @@ internal void StopCommand( SetThreadProperties(requestDetails); - PSEtwLog.LogAnalyticInformational(PSEventId.ServerStopCommand, - PSOpcode.Disconnect, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - ((IntPtr)shellContext).ToString(), - ((IntPtr)commandContext).ToString(), - requestDetails.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerStopCommand, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), + requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); if (mgdShellSession == null) @@ -722,13 +794,22 @@ internal void StopCommand( } mgdCommandSession.Stop(requestDetails); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerStopCommand, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + "StopCommand: completed", + string.Empty); } internal void Shutdown() { - PSEtwLog.LogAnalyticInformational(PSEventId.WSManPluginShutdown, - PSOpcode.ShuttingDown, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManPluginShutdown, + PSOpcode.ShuttingDown, PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic); // all active shells should be closed at this point Dbg.Assert(_activeShellSessions.Count == 0, "All active shells should be closed"); @@ -752,6 +833,15 @@ internal void ConnectShellOrCommand( IntPtr commandContext, WSManNativeApi.WSManData_UnToMan inboundConnectInformation) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "ConnectShellOrCommand: Connect", + string.Empty); + if (!validateIncomingContexts(requestDetails, shellContext, "ConnectShellOrCommand")) { return; @@ -759,10 +849,15 @@ internal void ConnectShellOrCommand( // TODO... What does this mean from a new client that has specified diff locale from original client? SetThreadProperties(requestDetails); - // TODO.. Add new ETW events and log - /*etwTracer.AnalyticChannel.WriteInformation(PSEventId.ServerReceivedData, - PSOpcode.Open, PSTask.None, - ((IntPtr)shellContext).ToString(), ((IntPtr)commandContext).ToString(), ((IntPtr)requestDetails).ToString());*/ + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), + requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); if (mgdShellSession == null) @@ -793,7 +888,25 @@ internal void ConnectShellOrCommand( return; } + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), + requestDetails.ToString()); + mgdCmdSession.ExecuteConnect(requestDetails, flags, inboundConnectInformation); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Connect, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "ConnectShellOrCommand: ExecuteConnect invoked", + string.Empty); } /// @@ -813,6 +926,15 @@ internal void SendOneItemToShellOrCommand( string stream, WSManNativeApi.WSManData_UnToMan inboundData) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "SendOneItemToShellOrCommand: Send data to the shell / command specified", + string.Empty); + if (!validateIncomingContexts(requestDetails, shellContext, "SendOneItemToShellOrCommand")) { return; @@ -820,10 +942,14 @@ internal void SendOneItemToShellOrCommand( SetThreadProperties(requestDetails); - PSEtwLog.LogAnalyticInformational(PSEventId.ServerReceivedData, - PSOpcode.Open, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - ((IntPtr)shellContext).ToString(), ((IntPtr)commandContext).ToString(), requestDetails.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), + requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); if (mgdShellSession == null) @@ -856,7 +982,25 @@ internal void SendOneItemToShellOrCommand( return; } + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), + requestDetails.ToString()); + mgdCmdSession.SendOneItemToSession(requestDetails, flags, stream, inboundData); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "SendOneItemToShellOrCommand: SendOneItemToSession invoked", + string.Empty); } /// @@ -877,6 +1021,15 @@ internal void EnableShellOrCommandToSendDataToClient( IntPtr commandContext, WSManNativeApi.WSManStreamIDSet_UnToMan streamSet) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerClientReceiveRequest, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "EnableShellOrCommandToSendDataToClient: unlock the shell / command specified so that the shell / command starts sending data to the client.", + string.Empty); + if (!validateIncomingContexts(requestDetails, shellContext, "EnableShellOrCommandToSendDataToClient")) { return; @@ -884,12 +1037,14 @@ internal void EnableShellOrCommandToSendDataToClient( SetThreadProperties(requestDetails); - PSEtwLog.LogAnalyticInformational(PSEventId.ServerClientReceiveRequest, - PSOpcode.Open, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - ((IntPtr)shellContext).ToString(), - ((IntPtr)commandContext).ToString(), - requestDetails.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerClientReceiveRequest, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + ((IntPtr)shellContext).ToString(), + ((IntPtr)commandContext).ToString(), + requestDetails.ToString()); WSManPluginShellSession mgdShellSession = GetFromActiveShellSessions(shellContext); if (mgdShellSession == null) @@ -910,6 +1065,15 @@ internal void EnableShellOrCommandToSendDataToClient( return; } + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerClientReceiveRequest, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "EnableShellOrCommandToSendDataToClient: Instruction destined to shell or for command", + string.Empty); + if (IntPtr.Zero == commandContext) { // the instruction is destined for shell (runspace) session. so let shell handle it @@ -1135,6 +1299,15 @@ internal static void PerformWSManPluginShell( IntPtr startupInfo, // WSMAN_SHELL_STARTUP_INFO* IntPtr inboundShellInformation) // WSMAN_DATA* { + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginShell: static func to take care of unmanaged to managed transitions.", + string.Empty); + WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); if (pluginToUse == null) @@ -1157,7 +1330,24 @@ internal static void PerformWSManPluginShell( WSManNativeApi.WSManShellStartupInfo_UnToMan startupInfoInstance = WSManNativeApi.WSManShellStartupInfo_UnToMan.UnMarshal(startupInfo); WSManNativeApi.WSManData_UnToMan inboundShellInfo = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundShellInformation); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + requestDetailsInstance.ToString(), + requestDetailsInstance.resourceUri); + pluginToUse.CreateShell(pluginContext, requestDetailsInstance, flags, extraInfo, startupInfoInstance, inboundShellInfo); + + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginShell: Completed", + string.Empty); } internal static void PerformWSManPluginCommand( @@ -1168,6 +1358,15 @@ internal static void PerformWSManPluginCommand( [MarshalAs(UnmanagedType.LPWStr)] string commandLine, IntPtr arguments) // WSMAN_COMMAND_ARG_SET* { + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginCommand: static func to take care of unmanaged to managed transitions.", + string.Empty); + WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); if (pluginToUse == null) @@ -1184,7 +1383,24 @@ internal static void PerformWSManPluginCommand( WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); WSManNativeApi.WSManCommandArgSet argSet = WSManNativeApi.WSManCommandArgSet.UnMarshal(arguments); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + request.ToString(), + request.resourceUri); + pluginToUse.CreateCommand(pluginContext, request, flags, shellContext, commandLine, argSet); + + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginCommand: Completed", + string.Empty); } internal static void PerformWSManPluginConnect( @@ -1195,6 +1411,15 @@ internal static void PerformWSManPluginConnect( IntPtr commandContext, IntPtr inboundConnectInformation) { + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginConnect: static func to take care of unmanaged to managed transitions.", + string.Empty); + WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); if (pluginToUse == null) @@ -1211,7 +1436,24 @@ internal static void PerformWSManPluginConnect( WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); WSManNativeApi.WSManData_UnToMan connectInformation = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundConnectInformation); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + request.ToString(), + request.resourceUri); + pluginToUse.ConnectShellOrCommand(request, flags, shellContext, commandContext, connectInformation); + + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginConnect: Completed", + string.Empty); } internal static void PerformWSManPluginSend( @@ -1223,6 +1465,15 @@ internal static void PerformWSManPluginSend( string stream, IntPtr inboundData) // WSMAN_DATA* { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginSend: Invoked", + string.Empty); + WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); if (pluginToUse == null) @@ -1240,6 +1491,15 @@ internal static void PerformWSManPluginSend( WSManNativeApi.WSManData_UnToMan data = WSManNativeApi.WSManData_UnToMan.UnMarshal(inboundData); pluginToUse.SendOneItemToShellOrCommand(request, flags, shellContext, commandContext, stream, data); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginSend: Completed", + string.Empty); } internal static void PerformWSManPluginReceive( @@ -1250,6 +1510,15 @@ internal static void PerformWSManPluginReceive( IntPtr commandContext, IntPtr streamSet) // WSMAN_STREAM_ID_SET* { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginReceive: Invoked", + string.Empty); + WSManPluginInstance pluginToUse = GetFromActivePlugins(pluginContext); if (pluginToUse == null) @@ -1266,7 +1535,24 @@ internal static void PerformWSManPluginReceive( WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); WSManNativeApi.WSManStreamIDSet_UnToMan streamIdSet = WSManNativeApi.WSManStreamIDSet_UnToMan.UnMarshal(streamSet); + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + request.ToString(), + request.resourceUri); + pluginToUse.EnableShellOrCommandToSendDataToClient(pluginContext, request, flags, shellContext, commandContext, streamIdSet); + + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginReceive: Completed", + string.Empty); } internal static void PerformWSManPluginSignal( @@ -1277,6 +1563,15 @@ internal static void PerformWSManPluginSignal( IntPtr commandContext, // PVOID string code) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformWSManPluginSignal: Invoked", + string.Empty); + WSManNativeApi.WSManPluginRequest request = WSManNativeApi.WSManPluginRequest.UnMarshal(requestDetails); // Close Command @@ -1328,6 +1623,15 @@ internal static void PerformWSManPluginSignal( internal static void PerformCloseOperation( WSManPluginOperationShutdownContext context) { + PSEtwLog.LogAnalyticInformational( + PSEventId.ServerReceivedData, + PSOpcode.Open, + PSTask.None, + PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, + string.Empty, + "PerformCloseOperation: Invoked", + string.Empty); + WSManPluginInstance pluginToUse = GetFromActivePlugins(context.pluginContext); if (pluginToUse == null) @@ -1399,7 +1703,8 @@ internal static void ReportWSManOperationComplete( { Dbg.Assert(requestDetails != null, "requestDetails cannot be null in operation complete."); - PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete, + PSEtwLog.LogAnalyticInformational( + PSEventId.ReportOperationComplete, PSOpcode.Close, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, (requestDetails.unmanagedHandle).ToString(), @@ -1432,7 +1737,8 @@ internal static void ReportWSManOperationComplete( stackTrace = reasonForClose.StackTrace; } - PSEtwLog.LogAnalyticInformational(PSEventId.ReportOperationComplete, + PSEtwLog.LogAnalyticInformational( + PSEventId.ReportOperationComplete, PSOpcode.Close, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, requestDetails.ToString(), diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index 3700da98e89..ed5bf0a4a3e 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ---------------------------------------------------------------------- // Contents: Entry points for managed PowerShell plugin worker used to @@ -170,6 +170,7 @@ internal sealed class WSManPluginEntryDelegates : IDisposable // Holds the delegate pointers in a structure that has identical layout to the native structure. private WSManPluginEntryDelegatesInternal _unmanagedStruct = new WSManPluginEntryDelegatesInternal(); + internal WSManPluginEntryDelegatesInternal UnmanagedStruct { get { return _unmanagedStruct; } @@ -418,7 +419,7 @@ private WSManPluginManagedEntryWrapper() { } /// /// Immutable container that holds the delegates and their unmanaged pointers. /// - internal static WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates(); + internal static readonly WSManPluginEntryDelegates workerPtrs = new WSManPluginEntryDelegates(); #region Managed Entry Points @@ -435,27 +436,7 @@ public static int InitPlugin( { return WSManPluginConstants.ExitCodeFailure; } -#if !CORECLR - // For long-path support, Full .NET requires some AppContext switches; - // (for CoreCLR this is Not needed, because CoreCLR supports long paths by default) - // internally in .NET they are cached once retrieved and are typically hit very early during an application run; - // so per .NET team's recommendation, we are setting them as soon as we enter managed code. - // We build against CLR4.5 so we can run on Win7/Win8, but we want to use apis added to CLR 4.6, so we use reflection - try - { - Type appContextType = Type.GetType("System.AppContext"); // type is in mscorlib, so it is sufficient to supply the type name qualified by its namespace - object[] blockLongPathsSwitch = new object[] { "Switch.System.IO.BlockLongPaths", false }; - object[] useLegacyPathHandlingSwitch = new object[] { "Switch.System.IO.UseLegacyPathHandling", false }; - - appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, blockLongPathsSwitch, CultureInfo.InvariantCulture); - appContextType.InvokeMember("SetSwitch", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, null, null, useLegacyPathHandlingSwitch, CultureInfo.InvariantCulture); - } - catch (Exception) - { - // If there are any non-critical exceptions (e.g. we are running on CLR prior to 4.6.2), we won't be able to use long paths - } -#endif Marshal.StructureToPtr(workerPtrs.UnmanagedStruct, wkrPtrs, false); return WSManPluginConstants.ExitCodeSuccess; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 3d18ff69dc3..f4dabc11558 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ---------------------------------------------------------------------- // Contents: Entry points for managed PowerShell plugin worker used to @@ -59,10 +59,8 @@ protected WSManPluginServerSession( this.creationRequestDetails = creationRequestDetails; this.transportMgr = transportMgr; - transportMgr.PrepareCalled += - new EventHandler(this.HandlePrepareFromTransportManager); - transportMgr.WSManTransportErrorOccured += - new EventHandler(this.HandleTransportError); + transportMgr.PrepareCalled += this.HandlePrepareFromTransportManager; + transportMgr.WSManTransportErrorOccured += this.HandleTransportError; } public void Dispose() @@ -167,7 +165,7 @@ internal void SendOneItemToSession( lock (_syncObject) { - if (true == isClosed) + if (isClosed) { WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); return; @@ -196,7 +194,7 @@ internal bool EnableSessionToSendDataToClient( WSManNativeApi.WSManStreamIDSet_UnToMan streamSet, WSManPluginOperationShutdownContext ctxtToReport) { - if (true == isClosed) + if (isClosed) { WSManPluginInstance.ReportWSManOperationComplete(requestDetails, lastErrorReported); return false; @@ -241,7 +239,7 @@ internal void ReportContext() lock (_syncObject) { - if (true == isClosed) + if (isClosed) { return; } @@ -254,7 +252,7 @@ internal void ReportContext() PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, creationRequestDetails.ToString(), creationRequestDetails.ToString()); - // RACE TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime + // TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime // If Signal comes and executes before registering the notification handle, cleanup will be messed result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle); if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result)) @@ -327,7 +325,7 @@ internal void HandlePrepareFromTransportManager(object sender, EventArgs eventAr { ReportContext(); ReportSendOperationComplete(); - transportMgr.PrepareCalled -= new EventHandler(this.HandlePrepareFromTransportManager); + transportMgr.PrepareCalled -= this.HandlePrepareFromTransportManager; } internal void Close(bool isShuttingDown) @@ -350,8 +348,7 @@ internal void Close(bool isShuttingDown) shutDownContext = null; } - transportMgr.WSManTransportErrorOccured -= - new EventHandler(this.HandleTransportError); + transportMgr.WSManTransportErrorOccured -= this.HandleTransportError; // We should not use request details again after so releasing the resource. // Remember not to free this memory as this memory is allocated and owned by WSMan. @@ -386,6 +383,7 @@ internal void ReportSendOperationComplete() #region Pure virtual methods internal abstract void CloseOperation(WSManPluginOperationShutdownContext context, Exception reasonForClose); + internal abstract void ExecuteConnect( WSManNativeApi.WSManPluginRequest requestDetails, // in int flags, // in @@ -522,7 +520,7 @@ internal void CreateCommand( WSManPluginCommandSession mgdCmdSession = new WSManPluginCommandSession(requestDetails, serverCmdTransportMgr, _remoteSession); AddToActiveCmdSessions(mgdCmdSession); - mgdCmdSession.SessionClosed += new EventHandler(this.HandleCommandSessionClosed); + mgdCmdSession.SessionClosed += this.HandleCommandSessionClosed; mgdCmdSession.shutDownContext = new WSManPluginOperationShutdownContext( pluginContext, @@ -639,7 +637,7 @@ private void CloseAndClearCommandSessions( WSManPluginCommandSession cmdSession = cmdSessionEnumerator.Current; // we are not interested in session closed events anymore as we are initiating the close // anyway/ - cmdSession.SessionClosed -= new EventHandler(this.HandleCommandSessionClosed); + cmdSession.SessionClosed -= this.HandleCommandSessionClosed; cmdSession.Close(reasonForClose); } @@ -687,7 +685,7 @@ internal override void CloseOperation( // let command sessions to close. lock (shellSyncObject) { - if (true == isClosed) + if (isClosed) { return; } @@ -787,7 +785,7 @@ internal override void CloseOperation( // let command sessions to close. lock (cmdSyncObject) { - if (true == isClosed) + if (isClosed) { return; } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs index c73cb1c4bfd..a02f6623e0a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginTransportManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ---------------------------------------------------------------------- // Contents: Entry points for managed PowerShell plugin worker used to @@ -157,7 +157,7 @@ internal void DoClose( /// internal override void ReportExecutionStatusAsRunning() { - if (true == _isClosed) + if (_isClosed) { return; } @@ -200,7 +200,7 @@ protected override void SendDataToClient( bool reportAsPending, bool reportAsDataBoundary) { - if (true == _isClosed) + if (_isClosed) { return; } @@ -399,7 +399,7 @@ internal WSManPluginCommandTransportManager(WSManPluginServerTransportManager sr internal void Initialize() { - this.PowerShellGuidObserver += new System.EventHandler(OnPowershellGuidReported); + this.PowerShellGuidObserver += OnPowershellGuidReported; this.MigrateDataReadyEventHandlers(_serverTransportMgr); } @@ -407,7 +407,7 @@ private void OnPowershellGuidReported(object src, System.EventArgs args) { _cmdId = (System.Guid)src; _serverTransportMgr.ReportTransportMgrForCmd(_cmdId, this); - this.PowerShellGuidObserver -= new System.EventHandler(this.OnPowershellGuidReported); + this.PowerShellGuidObserver -= this.OnPowershellGuidReported; } } } diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 46ac2063192..1fad7ccb3e8 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* @@ -321,10 +321,13 @@ internal CompletionEventArgs(CompletionNotification notification) // operation handles are owned by WSMan [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManSessionHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManShellOperationHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManReceiveOperationHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManSendOperationHandle; // this is used with WSMan callbacks to represent a session transport manager. @@ -451,6 +454,7 @@ private void ProcessShellData(string data) // callbacks. private static Dictionary s_sessionTMHandles = new Dictionary(); + private static long s_sessionTMSeed; // generate unique session id private static long GetNextSessionTMHandleId() @@ -1005,7 +1009,8 @@ internal override void StartReceivingData() receiveDataInitiated = true; tracer.WriteLine("Client Session TM: Placing Receive request using WSManReceiveShellOutputEx"); - PSEtwLog.LogAnalyticInformational(PSEventId.WSManReceiveShellOutputEx, + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManReceiveShellOutputEx, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), Guid.Empty.ToString()); @@ -1109,7 +1114,9 @@ internal override void CreateAsync() _createSessionCallbackGCHandle = GCHandle.Alloc(_createSessionCallback); } - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShell, + PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString()); @@ -1184,7 +1191,7 @@ internal override void CloseAsync() // let other threads release the lock before we clean up the resources. lock (syncObject) { - if (isClosed == true) + if (isClosed) { return; } @@ -1227,7 +1234,8 @@ internal override void CloseAsync() } // TODO - On unexpected failures on a reconstructed session... we dont want to close server session - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseShell, + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseShell, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString()); _closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionCloseCallback); @@ -1306,9 +1314,13 @@ internal override void Redirect(Uri newUri, RunspaceConnectionInfo connectionInf { CloseSessionAndClearResources(); tracer.WriteLine("Redirecting to URI: {0}", newUri); - PSEtwLog.LogAnalyticInformational(PSEventId.URIRedirection, - PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), newUri.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.URIRedirection, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + RunspacePoolInstanceId.ToString(), + newUri.ToString()); Initialize(newUri, (WSManConnectionInfo)connectionInfo); // reset startmode _startMode = WSManTransportManagerUtils.tmStartModes.None; @@ -1638,14 +1650,16 @@ internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArg } // Write errors into both Operational and Analytical channels - PSEtwLog.LogOperationalError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, + PSEtwLog.LogOperationalError( + PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, RunspacePoolInstanceId.ToString(), Guid.Empty.ToString(), eventArgs.Exception.ErrorCode.ToString(CultureInfo.InvariantCulture), eventArgs.Exception.Message, stackTrace); - PSEtwLog.LogAnalyticError(PSEventId.TransportError_Analytic, + PSEtwLog.LogAnalyticError( + PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), @@ -1852,8 +1866,11 @@ private static void OnCreateSessionCallback(IntPtr operationContext, return; } - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShellCallbackReceived, - PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateShellCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, sessionTM.RunspacePoolInstanceId.ToString()); // TODO: 188098 wsManShellOperationHandle should be populated by WSManCreateShellEx, @@ -1965,9 +1982,13 @@ private static void OnCloseSessionCompleted(IntPtr operationContext, return; } - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseShellCallbackReceived, - PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - sessionTM.RunspacePoolInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseShellCallbackReceived, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + sessionTM.RunspacePoolInstanceId.ToString(), + "OnCloseSessionCompleted"); if (IntPtr.Zero != error) { @@ -2013,6 +2034,13 @@ private static void OnRemoteSessionDisconnectCompleted(IntPtr operationContext, } // LOG ETW EVENTS + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseShellCallbackReceived, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + sessionTM.RunspacePoolInstanceId.ToString(), + "OnRemoteSessionDisconnectCompleted"); // Dispose the OnDisconnect callback as it is not needed anymore if (sessionTM._disconnectSessionCompleted != null) @@ -2055,7 +2083,14 @@ private static void OnRemoteSessionDisconnectCompleted(IntPtr operationContext, sessionTM.EnqueueAndStartProcessingThread(null, null, new CompletionEventArgs(CompletionNotification.DisconnectCompleted)); - // Log ETW traces + // Log ETW traces + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseShellCallbackReceived, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + sessionTM.RunspacePoolInstanceId.ToString(), + "OnRemoteSessionReconnectCompleted: DisconnectCompleted"); } return; @@ -2081,6 +2116,13 @@ private static void OnRemoteSessionReconnectCompleted(IntPtr operationContext, } // Add ETW events + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseShellCallbackReceived, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + sessionTM.RunspacePoolInstanceId.ToString(), + "OnRemoteSessionReconnectCompleted"); // Dispose the OnCreate callback as it is not needed anymore if (sessionTM._reconnectSessionCompleted != null) @@ -2176,6 +2218,13 @@ private static void OnRemoteSessionConnectCallback(IntPtr operationContext, { tracer.WriteLine("Client Session TM: Connect callback received"); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManSendShellInputExCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + "OnRemoteSessionConnectCallback:Client Session TM: Connect callback received"); + long sessionTMHandle = 0; WSManClientSessionTransportManager sessionTM = null; if (!TryGetSessionTransportManager(operationContext, out sessionTM, out sessionTMHandle)) @@ -2269,9 +2318,13 @@ private static void OnRemoteSessionSendCompleted(IntPtr operationContext, } // do the logging for this send - PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, - PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - sessionTM.RunspacePoolInstanceId.ToString(), Guid.Empty.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManSendShellInputExCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + sessionTM.RunspacePoolInstanceId.ToString(), + Guid.Empty.ToString()); if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle)) { @@ -2730,12 +2783,16 @@ internal sealed class WSManClientCommandTransportManager : BaseClientCommandTran // operation handles private IntPtr _wsManShellOperationHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManCmdOperationHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _cmdSignalOperationHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManReceiveOperationHandle; + [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManSendOperationHandle; // this is used with WSMan callbacks to represent a command transport manager. @@ -2981,9 +3038,13 @@ internal override void CreateAsync() _cmdContextId = GetNextCmdTMHandleId(); AddCmdTransportManager(_cmdContextId, this); - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommand, PSOpcode.Connect, - PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateCommand, + PSOpcode.Connect, + PSTask.CreateRunspace, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + RunspacePoolInstanceId.ToString(), + powershellInstanceId.ToString()); _createCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdCreateCallback); _createCmdCompletedGCHandle = GCHandle.Alloc(_createCmdCompleted); @@ -3044,7 +3105,7 @@ internal override void SendStopSignal() { lock (syncObject) { - if (isClosed == true) + if (isClosed) { return; } @@ -3061,9 +3122,14 @@ internal override void SendStopSignal() _isStopSignalPending = false; tracer.WriteLine("Sending stop signal with command context: {0} Operation Context {1}", _cmdContextId, _wsManCmdOperationHandle); - PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignal, - PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString(), StopSignal); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManSignal, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + RunspacePoolInstanceId.ToString(), + powershellInstanceId.ToString(), + StopSignal); _signalCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdSignalCallback); WSManNativeApi.WSManSignalShellEx(_wsManShellOperationHandle, _wsManCmdOperationHandle, 0, @@ -3082,7 +3148,7 @@ internal override void CloseAsync() // then let other threads release the lock before we cleaning up the resources. lock (syncObject) { - if (isClosed == true) + if (isClosed) { return; } @@ -3115,9 +3181,13 @@ internal override void CloseAsync() return; } - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommand, - PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseCommand, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + RunspacePoolInstanceId.ToString(), + powershellInstanceId.ToString()); _closeCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdCloseCallback); Dbg.Assert((IntPtr)_closeCmdCompleted != IntPtr.Zero, "closeCmdCompleted callback is null in cmdTM.CloseAsync()"); WSManNativeApi.WSManCloseCommand(_wsManCmdOperationHandle, 0, _closeCmdCompleted); @@ -3292,9 +3362,13 @@ private static void OnCreateCmdCompleted(IntPtr operationContext, return; } - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommandCallbackReceived, - PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateCommandCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + cmdTM.RunspacePoolInstanceId.ToString(), + cmdTM.powershellInstanceId.ToString()); // dispose the cmdCompleted callback as it is not needed any more if (cmdTM._createCmdCompleted != null) @@ -3384,6 +3458,13 @@ private static void OnConnectCmdCompleted(IntPtr operationContext, { tracer.WriteLine("OnConnectCmdCompleted callback received"); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCreateCommandCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + "OnConnectCmdCompleted: OnConnectCmdCompleted callback received"); + long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) @@ -3473,6 +3554,13 @@ private static void OnCloseCmdCompleted(IntPtr operationContext, { tracer.WriteLine("OnCloseCmdCompleted callback received for operation context {0}", commandOperationHandle); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseCommandCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + "OnCloseCmdCompleted: OnCloseCmdCompleted callback received"); + long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) @@ -3483,9 +3571,13 @@ private static void OnCloseCmdCompleted(IntPtr operationContext, } tracer.WriteLine("Close completed callback received for command: {0}", cmdTM._cmdContextId); - PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommandCallbackReceived, - PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManCloseCommandCallbackReceived, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + cmdTM.RunspacePoolInstanceId.ToString(), + cmdTM.powershellInstanceId.ToString()); if (cmdTM._isDisconnectPending) { @@ -3505,6 +3597,13 @@ private static void OnRemoteCmdSendCompleted(IntPtr operationContext, { tracer.WriteLine("SendComplete callback received"); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManSendShellInputExCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + "OnRemoteCmdSendCompleted: SendComplete callback received"); + long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) @@ -3517,9 +3616,13 @@ private static void OnRemoteCmdSendCompleted(IntPtr operationContext, cmdTM._isSendingInput = false; // do the logging for this send - PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, - PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManSendShellInputExCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + cmdTM.RunspacePoolInstanceId.ToString(), + cmdTM.powershellInstanceId.ToString()); if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) @@ -3588,6 +3691,13 @@ private static void OnRemoteCmdDataReceived(IntPtr operationContext, { tracer.WriteLine("Remote Command DataReceived callback."); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManReceiveShellOutputExCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + "OnRemoteCmdDataReceived: Remote Command DataReceived callback"); + long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) @@ -3672,6 +3782,14 @@ private static void OnReconnectCmdCompleted(IntPtr operationContext, { long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; + + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManReceiveShellOutputExCallbackReceived, + PSOpcode.Connect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + "OnReconnectCmdCompleted"); + if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) { // We dont have the command TM handle..just return. @@ -3731,6 +3849,8 @@ private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, { tracer.WriteLine("Signal Completed callback received."); + PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignalCallbackReceived, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, "OnRemoteCmdSignalCompleted"); + long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) @@ -3741,9 +3861,13 @@ private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, } // log the callback received event. - PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignalCallbackReceived, - PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManSignalCallbackReceived, + PSOpcode.Disconnect, + PSTask.None, + PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + cmdTM.RunspacePoolInstanceId.ToString(), + cmdTM.powershellInstanceId.ToString()); if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) @@ -3920,9 +4044,11 @@ private void SendData(byte[] data, DataPriorityType priorityType) internal override void StartReceivingData() { - PSEtwLog.LogAnalyticInformational(PSEventId.WSManReceiveShellOutputEx, - PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); + PSEtwLog.LogAnalyticInformational( + PSEventId.WSManReceiveShellOutputEx, + PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, + RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); + // We should call Receive only once.. WSMan will call the callback multiple times. _shouldStartReceivingData = false; lock (syncObject) @@ -3992,6 +4118,7 @@ internal override void Dispose(bool isDisposing) // callbacks. private static Dictionary s_cmdTMHandles = new Dictionary(); + private static long s_cmdTMSeed; // Generate command transport manager unique id diff --git a/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs b/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs index 149cf133194..63185ebc13f 100644 --- a/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs +++ b/src/System.Management.Automation/engine/remoting/host/RemoteHostMethodInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index 4d564ab4d21..a89f1a9d285 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; @@ -120,7 +120,7 @@ protected void ProcessingThreadStart(object state) protected void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid) { string streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_STDIN; - if (stream.Equals(DataPriorityType.PromptResponse.ToString(), StringComparison.OrdinalIgnoreCase)) + if (stream.Equals(nameof(DataPriorityType.PromptResponse), StringComparison.OrdinalIgnoreCase)) { streamTemp = System.Management.Automation.Remoting.Client.WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE; } @@ -569,14 +569,7 @@ internal static void Run(string initialCommand) s_singletonInstance = new SSHProcessMediator(); } - PSRemotingCryptoHelperServer cryptoHelper; -#if !UNIX - cryptoHelper = new PSRemotingCryptoHelperServer(); -#else - cryptoHelper = null; -#endif - - s_singletonInstance.Start(initialCommand, cryptoHelper); + s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer()); } #endregion @@ -610,7 +603,7 @@ private NamedPipeProcessMediator( { if (namedPipeServer == null) { - throw new PSArgumentNullException("namedPipeServer"); + throw new PSArgumentNullException(nameof(namedPipeServer)); } _namedPipeServer = namedPipeServer; diff --git a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs index 3228d1fad83..0c0fb0a0c42 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerMethodExecutor.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Remoting.Server; diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index ce5f69ee6a3..e52cffd5ce0 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -130,7 +130,7 @@ internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShel { InputCollection = new PSDataCollection(); InputCollection.ReleaseOnEnumeration = true; - InputCollection.IdleEvent += new EventHandler(HandleIdleEvent); + InputCollection.IdleEvent += HandleIdleEvent; } RegisterPipelineOutputEventHandlers(_localPowerShellOutput); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index 7c375bb18a3..921f9f456f1 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; @@ -151,17 +151,6 @@ public virtual bool IsRunspacePushed /// internal HostInfo HostInfo { get; } - /// - /// Allows a push runspace on this remote server host instance, regardless of - /// transport being used. - /// - internal virtual bool AllowPushRunspace - { - get { return (_serverDriverRemoteHost != null) ? _serverDriverRemoteHost.AllowPushRunspace : false; } - - set { if (_serverDriverRemoteHost != null) { _serverDriverRemoteHost.AllowPushRunspace = value; } } - } - #endregion #region Method Overrides @@ -328,18 +317,6 @@ public override bool IsRunspacePushed /// RemoteRunspace. public override void PushRunspace(Runspace runspace) { - // Double session hop is currently allowed only for WSMan (non-OutOfProc) sessions, where - // the second session is either through a named pipe or hyperV socket connection. - if (!AllowPushRunspace && - ((_transportManager is OutOfProcessServerSessionTransportManager) || - !(runspace.ConnectionInfo is NamedPipeConnectionInfo || - runspace.ConnectionInfo is VMConnectionInfo || - runspace.ConnectionInfo is ContainerConnectionInfo)) - ) - { - throw new PSNotSupportedException(); - } - if (_debugger == null) { throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNoDebuggerToPush); @@ -417,16 +394,6 @@ internal Runspace PushedRunspace get { return _pushedRunspace; } } - /// - /// Allows a push runspace on this remote server host instance, regardless of - /// transport being used. - /// - internal override bool AllowPushRunspace - { - get; - set; - } - /// /// When true will propagate pop call to client after popping runspace from this /// host. Used for OutOfProc remote sessions in a restricted (pushed) remote runspace, diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index be421ec7603..1a709b11246 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; @@ -345,7 +345,7 @@ public override int LengthInBufferCells(string source) { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } return source.Length; @@ -356,7 +356,7 @@ public override int LengthInBufferCells(string source, int offset) { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } Dbg.Assert(offset >= 0, "offset >= 0"); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs index 694876f8c32..6b69bb07b84 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -197,6 +197,17 @@ public override void WriteWarningLine(string message) _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteWarningLine, new object[] { message }); } + /// + /// Read line as string masked. + /// + /// + /// Not implemented. It throws an exception. + /// + public override string ReadLineMaskedAsString() + { + throw new PSNotImplementedException(); + } + /// /// Read line as secure string. /// diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index a1ae5bb67cb..72e7db24ae5 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -110,7 +110,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { if (receivedData == null) { - throw PSTraceSource.NewArgumentNullException("receivedData"); + throw PSTraceSource.NewArgumentNullException(nameof(receivedData)); } Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool, @@ -224,7 +224,7 @@ internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandl _associatedShells.Add(dsHandler.PowerShellId, dsHandler); } - dsHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation); + dsHandler.RemoveAssociation += HandleRemoveAssociation; return dsHandler; } @@ -414,6 +414,7 @@ private void HandleRemoveAssociation(object sender, EventArgs e) // runspace pool driver handles all client // communication private AbstractServerSessionTransportManager _transportManager; + private Dictionary _associatedShells = new Dictionary(); // powershell data structure handlers associated with this @@ -464,8 +465,7 @@ internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePool if (localPowerShell != null) { - localPowerShell.RunspaceAssigned += - new EventHandler>(LocalPowerShell_RunspaceAssigned); + localPowerShell.RunspaceAssigned += LocalPowerShell_RunspaceAssigned; } } @@ -617,7 +617,7 @@ internal void ProcessReceivedData(RemoteDataObject receivedData) { if (receivedData == null) { - throw PSTraceSource.NewArgumentNullException("receivedData"); + throw PSTraceSource.NewArgumentNullException(nameof(receivedData)); } Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.PowerShell, diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index f1b6e9ea51c..10814c3ea2b 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -204,30 +204,21 @@ internal ServerRunspacePoolDriver( DataStructureHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager); // handle the StateChanged event of the runspace pool - RunspacePool.StateChanged += - new EventHandler(HandleRunspacePoolStateChanged); + RunspacePool.StateChanged += HandleRunspacePoolStateChanged; // listen for events on the runspace pool - RunspacePool.ForwardEvent += - new EventHandler(HandleRunspacePoolForwardEvent); + RunspacePool.ForwardEvent += HandleRunspacePoolForwardEvent; RunspacePool.RunspaceCreated += HandleRunspaceCreated; // register for all the events from the data structure handler - DataStructureHandler.CreateAndInvokePowerShell += - new EventHandler>>(HandleCreateAndInvokePowerShell); - DataStructureHandler.GetCommandMetadata += - new EventHandler>>(HandleGetCommandMetadata); - DataStructureHandler.HostResponseReceived += - new EventHandler>(HandleHostResponseReceived); - DataStructureHandler.SetMaxRunspacesReceived += - new EventHandler>(HandleSetMaxRunspacesReceived); - DataStructureHandler.SetMinRunspacesReceived += - new EventHandler>(HandleSetMinRunspacesReceived); - DataStructureHandler.GetAvailableRunspacesReceived += - new EventHandler>(HandleGetAvailableRunspacesReceived); - DataStructureHandler.ResetRunspaceState += - new EventHandler>(HandleResetRunspaceState); + DataStructureHandler.CreateAndInvokePowerShell += HandleCreateAndInvokePowerShell; + DataStructureHandler.GetCommandMetadata += HandleGetCommandMetadata; + DataStructureHandler.HostResponseReceived += HandleHostResponseReceived; + DataStructureHandler.SetMaxRunspacesReceived += HandleSetMaxRunspacesReceived; + DataStructureHandler.SetMinRunspacesReceived += HandleSetMinRunspacesReceived; + DataStructureHandler.GetAvailableRunspacesReceived += HandleGetAvailableRunspacesReceived; + DataStructureHandler.ResetRunspaceState += HandleResetRunspaceState; } #endregion Constructors @@ -364,10 +355,8 @@ internal void Close() DisposeRemoteDebugger(); RunspacePool.Close(); - RunspacePool.StateChanged -= - new EventHandler(HandleRunspacePoolStateChanged); - RunspacePool.ForwardEvent -= - new EventHandler(HandleRunspacePoolForwardEvent); + RunspacePool.StateChanged -= HandleRunspacePoolStateChanged; + RunspacePool.ForwardEvent -= HandleRunspacePoolForwardEvent; RunspacePool.Dispose(); RunspacePool = null; @@ -457,10 +446,7 @@ private void HandleRunspaceCreatedForTypeTable(object sender, RunspaceCreatedEve { // Let exceptions propagate. RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(_configurationName, _remoteHost); - - _remoteHost.AllowPushRunspace = true; _remoteHost.PropagatePop = true; - _remoteHost.PushRunspace(remoteRunspace); } } @@ -893,8 +879,8 @@ private void HandleCreateAndInvokePowerShell(object _, RemoteDataEventArgs>(HandleInputReceived); - DataStructureHandler.StopPowerShellReceived += new EventHandler(HandleStopReceived); - DataStructureHandler.HostResponseReceived += - new EventHandler>(HandleHostResponseReceived); - DataStructureHandler.OnSessionConnected += new EventHandler(HandleSessionConnected); + DataStructureHandler.InputEndReceived += HandleInputEndReceived; + DataStructureHandler.InputReceived += HandleInputReceived; + DataStructureHandler.StopPowerShellReceived += HandleStopReceived; + DataStructureHandler.HostResponseReceived += HandleHostResponseReceived; + DataStructureHandler.OnSessionConnected += HandleSessionConnected; if (rsToUse == null) { diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 611a0719a5d..850993cf162 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs b/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs index d0aedc2c9f4..3b1174f0fff 100644 --- a/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs +++ b/src/System.Management.Automation/engine/remoting/server/WSManChannelEvents.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Remoting.WSMan diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index dc740ec962a..16978ff04e3 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; @@ -132,12 +132,8 @@ internal ServerRemoteSession(PSSenderInfo senderInfo, _senderInfo = senderInfo; _configProviderId = configurationProviderId; _initParameters = initializationParameters; -#if !UNIX _cryptoHelper = (PSRemotingCryptoHelperServer)transportManager.CryptoHelper; _cryptoHelper.Session = this; -#else - _cryptoHelper = null; -#endif Context = new ServerRemoteSessionContext(); SessionDataStructureHandler = new ServerRemoteSessionDSHandlerImpl(this, transportManager); @@ -145,8 +141,7 @@ internal ServerRemoteSession(PSSenderInfo senderInfo, SessionDataStructureHandler.CreateRunspacePoolReceived += HandleCreateRunspacePool; SessionDataStructureHandler.NegotiationReceived += HandleNegotiationReceived; SessionDataStructureHandler.SessionClosing += HandleSessionDSHandlerClosing; - SessionDataStructureHandler.PublicKeyReceived += - new EventHandler>(HandlePublicKeyReceived); + SessionDataStructureHandler.PublicKeyReceived += HandlePublicKeyReceived; transportManager.Closing += HandleResourceClosing; // update the quotas from sessionState..start with default size..and @@ -302,14 +297,14 @@ internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataEven { if (dataEventArg == null) { - throw PSTraceSource.NewArgumentNullException("dataEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(dataEventArg)); } RemoteDataObject rcvdData = dataEventArg.ReceivedData; if (rcvdData == null) { - throw PSTraceSource.NewArgumentException("dataEventArg"); + throw PSTraceSource.NewArgumentException(nameof(dataEventArg)); } RemotingDestination destination = rcvdData.Destination; @@ -638,9 +633,9 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) { RunServerNegotiationAlgorithm(clientCapability, true); } - catch (PSRemotingDataStructureException ex) + catch (PSRemotingDataStructureException) { - throw ex; + throw; } // validate client connect_runspacepool request @@ -680,9 +675,9 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) } // we currently dont support adjusting runspace count on a connect operation. - // there is a potential race here where in the runspace pool driver is still yet to process a queued + // there is a potential conflict here where in the runspace pool driver is still yet to process a queued // setMax or setMinrunspaces request. - // TODO: resolve this race.. probably by letting the runspace pool consume all messages before we execute this. + // TODO: resolve this.. probably by letting the runspace pool consume all messages before we execute this. if (clientRequestedRunspaceCount && (_runspacePoolDriver.RunspacePool.GetMaxRunspaces() != clientRequestedMaxRunspaces) && (_runspacePoolDriver.RunspacePool.GetMinRunspaces() != clientRequestedMinRunspaces)) @@ -748,7 +743,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR { if (createRunspaceEventArg == null) { - throw PSTraceSource.NewArgumentNullException("createRunspaceEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(createRunspaceEventArg)); } RemoteDataObject rcvdData = createRunspaceEventArg.ReceivedData; @@ -926,7 +921,7 @@ private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEv { if (negotiationEventArg == null) { - throw PSTraceSource.NewArgumentNullException("negotiationEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(negotiationEventArg)); } try diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index 3aa174df7db..b943444dd0a 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -36,6 +36,7 @@ internal class ServerRemoteSessionDSHandlerStateMachine private ServerRemoteSession _session; private object _syncObject; + private Queue _processPendingEventsQueue = new Queue(); // whether some thread is actively processing events @@ -71,7 +72,7 @@ internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session) { if (session == null) { - throw PSTraceSource.NewArgumentNullException("session"); + throw PSTraceSource.NewArgumentNullException(nameof(session)); } _session = session; @@ -257,7 +258,7 @@ private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs fsmEventArg) { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } EventHandler handler = _stateMachineHandle[(int)_state, (int)fsmEventArg.StateEvent]; @@ -291,7 +292,7 @@ private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs f { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CreateSession, "StateEvent must be CreateSession"); @@ -320,7 +321,7 @@ private void DoNegotiationPending(object sender, RemoteSessionStateMachineEventA { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert((_state == RemoteSessionState.Idle) || (_state == RemoteSessionState.NegotiationSent), @@ -352,7 +353,7 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationReceived, "StateEvent must be NegotiationReceived"); @@ -361,12 +362,12 @@ private void DoNegotiationReceived(object sender, RemoteSessionStateMachineEvent if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationReceived) { - throw PSTraceSource.NewArgumentException("fsmEventArg"); + throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } if (fsmEventArg.RemoteSessionCapability == null) { - throw PSTraceSource.NewArgumentException("fsmEventArg"); + throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } SetState(RemoteSessionState.NegotiationReceived, null); @@ -390,7 +391,7 @@ private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventA { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationSending, "Event must be NegotiationSending"); @@ -419,7 +420,7 @@ private void DoNegotiationCompleted(object sender, RemoteSessionStateMachineEven { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(_state == RemoteSessionState.NegotiationSending, "State must be NegotiationSending"); @@ -447,7 +448,7 @@ private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsm { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(_state == RemoteSessionState.NegotiationSent, "State must be NegotiationReceived"); @@ -455,7 +456,7 @@ private void DoEstablished(object sender, RemoteSessionStateMachineEventArgs fsm if (fsmEventArg.StateEvent != RemoteSessionEvent.NegotiationCompleted) { - throw PSTraceSource.NewArgumentException("fsmEventArg"); + throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } if (_state != RemoteSessionState.NegotiationSent) @@ -487,12 +488,12 @@ internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArg { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } if (fsmEventArg.RemoteData == null) { - throw PSTraceSource.NewArgumentException("fsmEventArg"); + throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } Dbg.Assert(_state == RemoteSessionState.Established || @@ -592,14 +593,14 @@ private void DoConnectFailed(object sender, RemoteSessionStateMachineEventArgs f { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ConnectFailed, "StateEvent must be ConnectFailed"); if (fsmEventArg.StateEvent != RemoteSessionEvent.ConnectFailed) { - throw PSTraceSource.NewArgumentException("fsmEventArg"); + throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } Dbg.Assert(_state == RemoteSessionState.Connecting, "session State must be Connecting"); @@ -629,14 +630,14 @@ private void DoFatalError(object sender, RemoteSessionStateMachineEventArgs fsmE { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.FatalError, "StateEvent must be FatalError"); if (fsmEventArg.StateEvent != RemoteSessionEvent.FatalError) { - throw PSTraceSource.NewArgumentException("fsmEventArg"); + throw PSTraceSource.NewArgumentException(nameof(fsmEventArg)); } DoClose(this, fsmEventArg); @@ -674,7 +675,7 @@ private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventA { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } RemoteSessionState oldState = _state; @@ -728,7 +729,7 @@ private void DoCloseFailed(object sender, RemoteSessionStateMachineEventArgs fsm { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseFailed, "StateEvent must be CloseFailed"); @@ -758,7 +759,7 @@ private void DoCloseCompleted(object sender, RemoteSessionStateMachineEventArgs { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.CloseCompleted, "StateEvent must be CloseCompleted"); @@ -788,7 +789,7 @@ private void DoNegotiationFailed(object sender, RemoteSessionStateMachineEventAr { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationFailed, "StateEvent must be NegotiationFailed"); @@ -817,7 +818,7 @@ private void DoNegotiationTimeout(object sender, RemoteSessionStateMachineEventA { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.NegotiationTimeout, "StateEvent must be NegotiationTimeout"); @@ -852,7 +853,7 @@ private void DoSendFailed(object sender, RemoteSessionStateMachineEventArgs fsmE { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.SendFailed, "StateEvent must be SendFailed"); @@ -881,7 +882,7 @@ private void DoReceiveFailed(object sender, RemoteSessionStateMachineEventArgs f { if (fsmEventArg == null) { - throw PSTraceSource.NewArgumentNullException("fsmEventArg"); + throw PSTraceSource.NewArgumentNullException(nameof(fsmEventArg)); } Dbg.Assert(fsmEventArg.StateEvent == RemoteSessionEvent.ReceiveFailed, "StateEvent must be ReceivedFailed"); diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs index 3120b3b17f4..cb8b8060a52 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocol.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs index 475b6399e93..1e72be279c7 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotingprotocolimplementation.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Remoting.Server; @@ -172,7 +172,7 @@ internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) { if (dataArg == null) { - throw PSTraceSource.NewArgumentNullException("dataArg"); + throw PSTraceSource.NewArgumentNullException(nameof(dataArg)); } RemoteDataObject rcvdData = dataArg.ReceivedData; diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 3aaf877e882..cc5dcad1805 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -1178,7 +1178,7 @@ private class KeyComparer : IEqualityComparer new List()); @@ -5246,7 +5249,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (adapterData.member.DeclaringType.IsGenericTypeDefinition || adapterData.propertyType.IsByRefLike) { - // This is kinda lame - we really should throw an error, but accessing property getter + // We really should throw an error, but accessing property getter // doesn't throw error in PowerShell since V2, even in strict mode. expr = ExpressionCache.NullConstant; } diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index c3416bb321a..76a8d8a1081 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -283,6 +283,7 @@ bool IsScriptBlockInFactASafeHashtable() // We delay parsing scripts loaded on startup, so we save the text. private string _scriptText; + internal IParameterMetadataProvider Ast { get => _ast ?? DelayParseScriptText(); } private IParameterMetadataProvider _ast; @@ -324,6 +325,7 @@ private IParameterMetadataProvider DelayParseScriptText() internal Action UnoptimizedEndBlock { get; set; } internal IScriptExtent[] SequencePoints { get; set; } + private RuntimeDefinedParameterDictionary _runtimeDefinedParameterDictionary; private Attribute[] _attributes; private bool _usesCmdletBinding; @@ -331,6 +333,7 @@ private IParameterMetadataProvider DelayParseScriptText() private bool _compiledUnoptimized; private bool _hasSuspiciousContent; private bool? _isProductCode; + internal bool DebuggerHidden { get; set; } internal bool DebuggerStepThrough { get; set; } internal Guid Id { get; private set; } @@ -555,6 +558,7 @@ protected ScriptBlock(SerializationInfo info, StreamingContext context) private static readonly ConcurrentDictionary, ScriptBlock> s_cachedScripts = new ConcurrentDictionary, ScriptBlock>(); + internal static ScriptBlock TryGetCachedScriptBlock(string fileName, string fileContents) { if (InternalTestHooks.IgnoreScriptBlockCache) @@ -579,7 +583,7 @@ private static bool IsDynamicKeyword(Ast ast) => ast is CommandAst cmdAst && cmdAst.DefiningKeyword != null; private static bool IsUsingTypes(Ast ast) - => ast is UsingStatementAst cmdAst && cmdAst.IsUsingModuleOrAssembly() == true; + => ast is UsingStatementAst cmdAst && cmdAst.IsUsingModuleOrAssembly(); internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, string fileContents) { @@ -619,7 +623,7 @@ internal static void ClearScriptBlockCache() s_cachedScripts.Clear(); } - internal static ScriptBlock EmptyScriptBlock = + internal static readonly ScriptBlock EmptyScriptBlock = ScriptBlock.CreateDelayParsedScriptBlock(string.Empty, isProductCode: true); internal static ScriptBlock Create(Parser parser, string fileName, string fileContents) @@ -719,7 +723,6 @@ internal PowerShell GetPowerShellImpl( args); } - internal SteppablePipeline GetSteppablePipelineImpl(CommandOrigin commandOrigin, object[] args) { var pipelineAst = GetSimplePipeline( @@ -979,10 +982,10 @@ internal void InvokeWithPipeImpl( // Validate at the arguments are consistent. The only public API that gets you here never sets createLocalScope to false... Diagnostics.Assert( - createLocalScope == true || functionsToDefine == null, + createLocalScope || functionsToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' != null then 'createLocalScope' must be true"); Diagnostics.Assert( - createLocalScope == true || variablesToDefine == null, + createLocalScope || variablesToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' != null then 'createLocalScope' must be true"); if (args == null) @@ -1717,6 +1720,7 @@ private static bool GetAndValidateEncryptionRecipients( private static string s_lastSeenCertificate = string.Empty; private static bool s_hasProcessedCertificate = false; private static CmsMessageRecipient[] s_encryptionRecipients = null; + private static Lazy s_sbLoggingSettingCache = new Lazy( () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); @@ -1774,7 +1778,7 @@ internal static string CheckSuspiciousContent(Ast scriptBlockAst) return null; } - class SuspiciousContentChecker + private class SuspiciousContentChecker { // Based on a (bad) random number generator, but good enough // for our simple needs. @@ -1789,7 +1793,7 @@ class SuspiciousContentChecker /// code - needed only to generate this switch statement below.) /// /// The string matching the hash, or null. - static string LookupHash(uint h) + private static string LookupHash(uint h) { switch (h) { @@ -2154,7 +2158,7 @@ private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext _scriptText = info.GetValue("ScriptText", typeof(string)) as string; if (_scriptText == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } } diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index 2982cdf53d6..de923e2df8b 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -30,6 +30,7 @@ namespace System.Management.Automation internal abstract class MutableTuple { private const int MaxSize = 128; + private static readonly Dictionary s_sizeDict = new Dictionary(); private int _size; @@ -307,6 +308,7 @@ public static int GetSize(Type tupleType) private static readonly ConcurrentDictionary> s_tupleCreators = new ConcurrentDictionary>(concurrencyLevel: 3, capacity: 100); + public static Func TupleCreator(Type type) { return s_tupleCreators.GetOrAdd(type, diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index 911c6b9a688..d340f8c2667 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ReSharper disable UnusedMember.Global diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index be30fe10310..7b06697afa1 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 8466c6b1794..7077ebeacbe 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -551,7 +551,7 @@ internal static void InvokePipelineInBackground( "^(global:){0,1}(PID|PSVersionTable|PSEdition|PSHOME|HOST|TRUE|FALSE|NULL)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant).Success == false) { - updatedScriptblock.Append(scriptblockBodyString.Substring(position, v.Extent.StartOffset - pipelineOffset - position)); + updatedScriptblock.Append(scriptblockBodyString.AsSpan(position, v.Extent.StartOffset - pipelineOffset - position)); updatedScriptblock.Append("${using:"); updatedScriptblock.Append(CodeGeneration.EscapeVariableName(variableName)); updatedScriptblock.Append('}'); @@ -559,7 +559,7 @@ internal static void InvokePipelineInBackground( } } - updatedScriptblock.Append(scriptblockBodyString.Substring(position)); + updatedScriptblock.Append(scriptblockBodyString.AsSpan(position)); var sb = ScriptBlock.Create(updatedScriptblock.ToString()); var commandInfo = new CmdletInfo("Start-Job", typeof(StartJobCommand)); commandProcessor = context.CommandDiscovery.LookupCommandProcessor(commandInfo, CommandOrigin.Internal, false, context.EngineSessionState); @@ -1575,15 +1575,23 @@ private static int FindMatchingHandlerByType(Type exceptionType, Type[] types) internal static bool SuspendStoppingPipeline(ExecutionContext context) { LocalPipeline lpl = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); - bool oldIsStopping = lpl.Stopper.IsStopping; - lpl.Stopper.IsStopping = false; - return oldIsStopping; + if (lpl != null) + { + bool oldIsStopping = lpl.Stopper.IsStopping; + lpl.Stopper.IsStopping = false; + return oldIsStopping; + } + + return false; } internal static void RestoreStoppingPipeline(ExecutionContext context, bool oldIsStopping) { LocalPipeline lpl = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); - lpl.Stopper.IsStopping = oldIsStopping; + if (lpl != null) + { + lpl.Stopper.IsStopping = oldIsStopping; + } } internal static void CheckActionPreference(FunctionContext funcContext, Exception exception) @@ -2530,7 +2538,7 @@ internal static object Where(IEnumerator enumerator, ScriptBlock expressionSB, W if (numberToReturn < 0) { - throw new ArgumentOutOfRangeException("numberToReturn", numberToReturn, ParserStrings.NumberToReturnMustBeGreaterThanZero); + throw new ArgumentOutOfRangeException(nameof(numberToReturn), numberToReturn, ParserStrings.NumberToReturnMustBeGreaterThanZero); } var context = Runspace.DefaultRunspace.ExecutionContext; @@ -2763,7 +2771,7 @@ internal static object ForEach(IEnumerator enumerator, object expression, object Diagnostics.Assert(arguments != null, "The ForEach() operator should never receive a null value for the 'arguments' parameter from the runtime."); if (expression == null) { - throw new ArgumentNullException("expression"); + throw new ArgumentNullException(nameof(expression)); } var context = Runspace.DefaultRunspace.ExecutionContext; @@ -3291,17 +3299,28 @@ internal object GetNonEnumerableObject() internal static IEnumerator GetCOMEnumerator(object obj) { object targetValue = PSObject.Base(obj); + try + { + var enumerator = (targetValue as IEnumerable)?.GetEnumerator(); + if (enumerator != null) + { + return enumerator; + } + } + catch (Exception) + { + } // We use ComEnumerator to enumerate COM collections because the following code doesn't work in .NET Core - // IEnumerable enumerable = targetValue as IEnumerable; - // if (enumerable != null) + // IEnumerator enumerator = targetValue as IEnumerator; + // if (enumerator != null) // { - // var enumerator = enumerable.GetEnumerator(); + // enumerable.MoveNext(); // ... // } - // The call to 'GetEnumerator()' throws exception because COM is not supported in .NET Core. - // See https://github.com/dotnet/corefx/issues/19731 for more information. - // When COM support is back to .NET Core, we need to change back to the original implementation. + // The call to 'MoveNext()' throws exception because COM is not fully supported in .NET Core. + // See https://github.com/dotnet/runtime/issues/21690 for more information. + // When COM support is fully back to .NET Core, we need to change back to directly use the type cast. return ComEnumerator.Create(targetValue) ?? NonEnumerableObjectEnumerator.Create(obj); } diff --git a/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs b/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs index e687e4c7f43..f5670899c23 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/NumericOps.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // ReSharper disable UnusedMember.Global @@ -8,8 +8,8 @@ namespace System.Management.Automation { internal static class Boxed { - internal static object True = (object)true; - internal static object False = (object)false; + internal static readonly object True = (object)true; + internal static readonly object False = (object)false; } internal static class IntOps diff --git a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs index eeb71366be0..0c4658cc14d 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; @@ -31,7 +31,7 @@ internal static string Multiply(string s, int times) if (times < 0) { // TODO: this should be a runtime error. - throw new ArgumentOutOfRangeException("times"); + throw new ArgumentOutOfRangeException(nameof(times)); } if (times == 0 || s.Length == 0) @@ -53,12 +53,16 @@ internal static string Multiply(string s, int times) return new string(s[0], times); } - // Convert the string to a char array, use the array multiplication code, - // then construct a new string from the resulting char array. This uses - // extra memory compared to the naive algorithm, but is faster (measured - // against a V2 CLR, should be measured against V4 as the StringBuilder - // implementation changed.) - return new string(ArrayOps.Multiply(s.ToCharArray(), (uint)times)); + return string.Create(s.Length * times, (s, times), (dst, args) => + { + ReadOnlySpan src = args.s.AsSpan(); + int length = src.Length; + for (int i = 0; i < args.times; i++) + { + src.CopyTo(dst); + dst = dst.Slice(length); + } + }); } internal static string FormatOperator(string formatString, object formatArgs) diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index f26fce16a00..d337c56ab2b 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Linq; diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 0b2dae82d1e..e2409eba626 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -409,10 +409,7 @@ private static Tuple, object[]> GetUsingValues(Ast bo // Collect UsingExpression value as a dictionary string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst); - if (!usingValueMap.ContainsKey(usingAstKey)) - { - usingValueMap.Add(usingAstKey, value); - } + usingValueMap.TryAdd(usingAstKey, value); } } catch (RuntimeException rte) @@ -646,7 +643,9 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) { var constantExprAst = ast as ConstantExpressionAst; object argument; - if (constantExprAst != null && LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType))) + if (constantExprAst != null + && (LanguagePrimitives.IsNumeric(LanguagePrimitives.GetTypeCode(constantExprAst.StaticType)) + || constantExprAst.StaticType == typeof(System.Numerics.BigInteger))) { var commandArgumentText = constantExprAst.Extent.Text; argument = constantExprAst.Value; diff --git a/src/System.Management.Automation/engine/scriptparameterbinder.cs b/src/System.Management.Automation/engine/scriptparameterbinder.cs index 6e580507684..c9944678ad8 100644 --- a/src/System.Management.Automation/engine/scriptparameterbinder.cs +++ b/src/System.Management.Automation/engine/scriptparameterbinder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -48,6 +48,7 @@ internal ScriptParameterBinder( private readonly CallSite> _copyMutableValueSite = CallSite>.Create(PSVariableAssignmentBinder.Get()); + internal object CopyMutableValues(object o) { // The variable assignment binder copies mutable values and returns other values as is. diff --git a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs index d1f8ba6ff25..9a63b1969a8 100644 --- a/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs +++ b/src/System.Management.Automation/engine/scriptparameterbindercontroller.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -274,7 +274,7 @@ private void HandleRemainingArguments(Collection argum // foo "-abc" // This is important when splatting, we reconstruct the parameter if the // value is splatted. - var parameterText = new PSObject(new string(parameter.ParameterText.ToCharArray())); + var parameterText = new PSObject(new string(parameter.ParameterText)); if (parameterText.Properties[NotePropertyNameForSplattingParametersInArgs] == null) { var noteProperty = new PSNoteProperty(NotePropertyNameForSplattingParametersInArgs, diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index f419968144f..31ec2e348d2 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -218,12 +218,12 @@ internal Serializer(XmlWriter writer, SerializationContext context) { if (writer == null) { - throw PSTraceSource.NewArgumentException("writer"); + throw PSTraceSource.NewArgumentException(nameof(writer)); } if (context == null) { - throw PSTraceSource.NewArgumentException("context"); + throw PSTraceSource.NewArgumentException(nameof(context)); } _serializer = new InternalSerializer(writer, context); @@ -355,7 +355,7 @@ internal void LogExtraMemoryUsage(int amountOfExtraMemory) internal readonly DeserializationOptions options; internal readonly PSRemotingCryptoHelper cryptoHelper; - internal static int MaxItemsInCimClassCache = 100; + internal static readonly int MaxItemsInCimClassCache = 100; internal readonly CimClassDeserializationCache cimClassSerializationIdCache = new CimClassDeserializationCache(); } @@ -484,7 +484,7 @@ internal Deserializer(XmlReader reader, DeserializationContext context) { if (reader == null) { - throw PSTraceSource.NewArgumentNullException("reader"); + throw PSTraceSource.NewArgumentNullException(nameof(reader)); } _reader = reader; @@ -666,7 +666,7 @@ internal static bool IsInstanceOfType(object o, Type type) { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } if (o == null) @@ -687,7 +687,7 @@ internal static bool IsDeserializedInstanceOfType(object o, Type type) { if (type == null) { - throw PSTraceSource.NewArgumentNullException("type"); + throw PSTraceSource.NewArgumentNullException(nameof(type)); } if (o == null) @@ -1888,6 +1888,7 @@ int depth } private Collection> _extendedMembersCollection; + private Collection> ExtendedMembersCollection { get @@ -1899,6 +1900,7 @@ private Collection> ExtendedMembersCollection } private Collection> _allPropertiesCollection; + private Collection> AllPropertiesCollection { get @@ -3110,7 +3112,7 @@ private object ReadOneDeserializedObject(out string streamName, out bool isKnown if (_reader.NodeType != XmlNodeType.Element) { throw NewXmlException(Serialization.InvalidNodeType, null, - _reader.NodeType.ToString(), XmlNodeType.Element.ToString()); + _reader.NodeType.ToString(), nameof(XmlNodeType.Element)); } s_trace.WriteLine("Processing start node {0}", _reader.LocalName); @@ -5905,7 +5907,7 @@ public PSPrimitiveDictionary(Hashtable other) { if (other == null) { - throw new ArgumentNullException("other"); + throw new ArgumentNullException(nameof(other)); } foreach (DictionaryEntry entry in other) @@ -6691,14 +6693,14 @@ public override object ConvertFrom(PSObject sourceValue, Type destinationType, I { if (destinationType == null) { - throw PSTraceSource.NewArgumentNullException("destinationType"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationType)); } if (sourceValue == null) { throw new PSInvalidCastException( "InvalidCastWhenRehydratingFromNull", - PSTraceSource.NewArgumentNullException("sourceValue"), + PSTraceSource.NewArgumentNullException(nameof(sourceValue)), ExtendedTypeSystem.InvalidCastFromNull, destinationType.ToString()); } @@ -7274,13 +7276,13 @@ public static UInt32 GetParameterSetMetadataFlags(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } ParameterSetMetadata parameterSetMetadata = instance.BaseObject as ParameterSetMetadata; if (parameterSetMetadata == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } return (UInt32)(parameterSetMetadata.Flags); @@ -7296,13 +7298,13 @@ public static PSObject GetInvocationInfo(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } DebuggerStopEventArgs dbgStopEventArgs = instance.BaseObject as DebuggerStopEventArgs; if (dbgStopEventArgs == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } if (dbgStopEventArgs.InvocationInfo == null) @@ -7474,7 +7476,7 @@ private static CustomItemBase RehydrateCustomItemBase(PSObject deserializedItem) } else { - throw PSTraceSource.NewArgumentException("deserializedItem"); + throw PSTraceSource.NewArgumentException(nameof(deserializedItem)); } return result; @@ -7556,13 +7558,13 @@ public static Guid GetFormatViewDefinitionInstanceId(PSObject instance) { if (instance == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } FormatViewDefinition formatViewDefinition = instance.BaseObject as FormatViewDefinition; if (formatViewDefinition == null) { - throw PSTraceSource.NewArgumentNullException("instance"); + throw PSTraceSource.NewArgumentNullException(nameof(instance)); } return formatViewDefinition.InstanceId; diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index d0fd56d0f49..b51d1b192dc 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; // for fxcop diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index 17be8bb3f3f..db7e4056d1e 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index e1147c0780f..0c70b815928 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/help/CabinetAPI.cs b/src/System.Management.Automation/help/CabinetAPI.cs index c308de10049..eb407f2ec62 100644 --- a/src/System.Management.Automation/help/CabinetAPI.cs +++ b/src/System.Management.Automation/help/CabinetAPI.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -81,7 +81,7 @@ internal abstract class ICabinetExtractorLoader internal class CabinetExtractorFactory { private static ICabinetExtractorLoader s_cabinetLoader; - internal static ICabinetExtractor EmptyExtractor = new EmptyCabinetExtractor(); + internal static readonly ICabinetExtractor EmptyExtractor = new EmptyCabinetExtractor(); /// /// Static constructor. diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 0ef22c88dc8..4b19861e473 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index 24acee030d7..52e6b3e2916 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -566,7 +566,7 @@ private string FindHelpFile(CmdletInfo cmdletInfo) if (cmdletInfo == null) { - throw PSTraceSource.NewArgumentNullException("cmdletInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(cmdletInfo)); } // Get the help file name from the cmdlet metadata diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index 2646276725b..b8be27e99a0 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -42,7 +42,7 @@ public int Compare(object x, object y) /// internal class DefaultCommandHelpObjectBuilder { - internal static string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo"; + internal static readonly string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo"; /// /// Generates a HelpInfo PSObject from a CmdletInfo object. /// diff --git a/src/System.Management.Automation/help/DefaultHelpProvider.cs b/src/System.Management.Automation/help/DefaultHelpProvider.cs index d1e63f6e9b8..9bbaea3f08d 100644 --- a/src/System.Management.Automation/help/DefaultHelpProvider.cs +++ b/src/System.Management.Automation/help/DefaultHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/help/DscResourceHelpProvider.cs b/src/System.Management.Automation/help/DscResourceHelpProvider.cs index c337705d46d..b0cdc239fb8 100644 --- a/src/System.Management.Automation/help/DscResourceHelpProvider.cs +++ b/src/System.Management.Automation/help/DscResourceHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index fc1071ec4a0..4d2a8100d0c 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -128,7 +128,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index 9b7ad5edd96..852db86c267 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 3bfa0181297..77347527ab4 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -70,6 +70,7 @@ private HelpCommentsParser(CommandInfo commandInfo, List parameterDescri internal static readonly string mamlURI = "http://schemas.microsoft.com/maml/2004/10"; internal static readonly string commandURI = "http://schemas.microsoft.com/maml/dev/command/2004/10"; internal static readonly string devURI = "http://schemas.microsoft.com/maml/dev/2004/10"; + private const string directive = @"^\s*\.(\w+)(\s+(\S.*))?\s*$"; private const string blankline = @"^\s*$"; // Although "http://msh" is the default namespace, it still must be explicitly qualified with non-empty prefix, diff --git a/src/System.Management.Automation/help/HelpErrorTracer.cs b/src/System.Management.Automation/help/HelpErrorTracer.cs index 6a2ae124955..9c9fd0165b5 100644 --- a/src/System.Management.Automation/help/HelpErrorTracer.cs +++ b/src/System.Management.Automation/help/HelpErrorTracer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -156,7 +156,7 @@ internal IDisposable Trace(string helpFile) /// internal void TraceError(ErrorRecord errorRecord) { - if (_traceFrames.Count <= 0) + if (_traceFrames.Count == 0) return; TraceFrame traceFrame = _traceFrames[_traceFrames.Count - 1]; @@ -171,7 +171,7 @@ internal void TraceError(ErrorRecord errorRecord) /// internal void TraceErrors(Collection errorRecords) { - if (_traceFrames.Count <= 0) + if (_traceFrames.Count == 0) return; TraceFrame traceFrame = _traceFrames[_traceFrames.Count - 1]; @@ -181,7 +181,7 @@ internal void TraceErrors(Collection errorRecords) internal void PopFrame(TraceFrame traceFrame) { - if (_traceFrames.Count <= 0) + if (_traceFrames.Count == 0) return; TraceFrame lastFrame = _traceFrames[_traceFrames.Count - 1]; diff --git a/src/System.Management.Automation/help/HelpFileHelpInfo.cs b/src/System.Management.Automation/help/HelpFileHelpInfo.cs index bbab589e776..1df1b70411b 100644 --- a/src/System.Management.Automation/help/HelpFileHelpInfo.cs +++ b/src/System.Management.Automation/help/HelpFileHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index e1e0a438526..2c527d2f95a 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/HelpInfo.cs b/src/System.Management.Automation/help/HelpInfo.cs index e8dbc08d9dc..207d8b54d51 100644 --- a/src/System.Management.Automation/help/HelpInfo.cs +++ b/src/System.Management.Automation/help/HelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -203,7 +203,7 @@ protected void AddCommonHelpProperties() if (this.FullHelp.Properties["Name"] == null) { - this.FullHelp.Properties.Add(new PSNoteProperty("Name", this.Name.ToString())); + this.FullHelp.Properties.Add(new PSNoteProperty("Name", this.Name)); } if (this.FullHelp.Properties["Category"] == null) @@ -213,7 +213,7 @@ protected void AddCommonHelpProperties() if (this.FullHelp.Properties["Synopsis"] == null) { - this.FullHelp.Properties.Add(new PSNoteProperty("Synopsis", this.Synopsis.ToString())); + this.FullHelp.Properties.Add(new PSNoteProperty("Synopsis", this.Synopsis)); } if (this.FullHelp.Properties["Component"] == null) diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index 3bb400119a3..355be44fd7c 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -134,7 +134,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/help/HelpProvider.cs b/src/System.Management.Automation/help/HelpProvider.cs index 6da72b1f542..76ce3168432 100644 --- a/src/System.Management.Automation/help/HelpProvider.cs +++ b/src/System.Management.Automation/help/HelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -225,15 +225,9 @@ internal string GetDefaultShellSearchPath() { string shellID = this.HelpSystem.ExecutionContext.ShellID; // Beginning in PowerShell 6.0.0.12, the $pshome is no longer registry specified, we search the application base instead. - string returnValue = Utils.GetApplicationBase(shellID); - - if (returnValue == null) - { - // use executing assemblies location in case registry entry not found - returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); - } - - return returnValue; + // We use executing assemblies location in case registry entry not found + return Utils.GetApplicationBase(shellID) + ?? Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); } /// diff --git a/src/System.Management.Automation/help/HelpProviderWithCache.cs b/src/System.Management.Automation/help/HelpProviderWithCache.cs index 6c54eb577d9..99dc3fa7a19 100644 --- a/src/System.Management.Automation/help/HelpProviderWithCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithCache.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/HelpProviderWithFullCache.cs b/src/System.Management.Automation/help/HelpProviderWithFullCache.cs index 52a4d21e54c..379ee0ac1c6 100644 --- a/src/System.Management.Automation/help/HelpProviderWithFullCache.cs +++ b/src/System.Management.Automation/help/HelpProviderWithFullCache.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/help/HelpRequest.cs b/src/System.Management.Automation/help/HelpRequest.cs index 83113a4ca9d..7e4de9f1569 100644 --- a/src/System.Management.Automation/help/HelpRequest.cs +++ b/src/System.Management.Automation/help/HelpRequest.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index 3e3c4080a85..fb92ed1c19c 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/HelpUtils.cs b/src/System.Management.Automation/help/HelpUtils.cs index 7892ec26af8..0c0770173be 100644 --- a/src/System.Management.Automation/help/HelpUtils.cs +++ b/src/System.Management.Automation/help/HelpUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.IO; diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index 354cc9c4d10..2101e268dc1 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/MamlClassHelpInfo.cs b/src/System.Management.Automation/help/MamlClassHelpInfo.cs index 36d337474f3..002eecb3bfe 100644 --- a/src/System.Management.Automation/help/MamlClassHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlClassHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Xml; diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index aea0ed47936..998e647cd05 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Globalization; diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index 332a7953087..712dc2325ea 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/MamlUtil.cs b/src/System.Management.Automation/help/MamlUtil.cs index 999cbe2e255..7ace664b728 100644 --- a/src/System.Management.Automation/help/MamlUtil.cs +++ b/src/System.Management.Automation/help/MamlUtil.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -192,7 +192,7 @@ internal static void PrependNotes(PSObject maml1, PSObject maml2) /// internal static PSPropertyInfo GetPropertyInfo(PSObject psObject, string[] path) { - if (path.Length <= 0) + if (path.Length == 0) { return null; } @@ -290,7 +290,7 @@ internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string /// internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path) { - if (path.Length <= 0) + if (path.Length == 0) { return; } diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index 6ee8107afa7..b6ec7a0db69 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs index 1c9d43cf9a2..6d9bedf4fac 100644 --- a/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderCommandHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation.Diagnostics; diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs index cfe2aeafbcc..184ad5526fa 100644 --- a/src/System.Management.Automation/help/ProviderContext.cs +++ b/src/System.Management.Automation/help/ProviderContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; diff --git a/src/System.Management.Automation/help/ProviderHelpInfo.cs b/src/System.Management.Automation/help/ProviderHelpInfo.cs index b1fb779a3da..39eebe0c23a 100644 --- a/src/System.Management.Automation/help/ProviderHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index 71331657461..a7d92f58f24 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -149,7 +149,7 @@ private void LoadHelpFile(ProviderInfo providerInfo) { if (providerInfo == null) { - throw PSTraceSource.NewArgumentNullException("providerInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInfo)); } string helpFile = providerInfo.HelpFile; diff --git a/src/System.Management.Automation/help/RemoteHelpInfo.cs b/src/System.Management.Automation/help/RemoteHelpInfo.cs index 3a69a84d8dc..a80ba7a7736 100644 --- a/src/System.Management.Automation/help/RemoteHelpInfo.cs +++ b/src/System.Management.Automation/help/RemoteHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index b87ff03a3dc..3c4d18af00a 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs index 119c51d67dd..5071451962e 100644 --- a/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs +++ b/src/System.Management.Automation/help/ScriptCommandHelpProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/help/SyntaxHelpInfo.cs b/src/System.Management.Automation/help/SyntaxHelpInfo.cs index 8b97b1a98a1..469ab94a913 100644 --- a/src/System.Management.Automation/help/SyntaxHelpInfo.cs +++ b/src/System.Management.Automation/help/SyntaxHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index ad6a1af315e..e9f601aba52 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -175,13 +175,13 @@ static UpdatableHelpCommandBase() // TODO: assign real TechNet addresses - s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://go.microsoft.com/fwlink/?linkid=2113532"); - s_metadataCache.Add("Microsoft.PowerShell.Core", "https://go.microsoft.com/fwlink/?linkid=2113534"); - s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://go.microsoft.com/fwlink/?linkid=2113633"); - s_metadataCache.Add("Microsoft.PowerShell.Host", "https://go.microsoft.com/fwlink/?linkid=2113538"); - s_metadataCache.Add("Microsoft.PowerShell.Management", "https://go.microsoft.com/fwlink/?linkid=2113632"); - s_metadataCache.Add("Microsoft.PowerShell.Security", "https://go.microsoft.com/fwlink/?linkid=2113533"); - s_metadataCache.Add("Microsoft.WSMan.Management", "https://go.microsoft.com/fwlink/?linkid=2113537"); + s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.PowerShell.Core", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.PowerShell.Host", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.PowerShell.Management", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.PowerShell.Security", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.WSMan.Management", "https://aka.ms/powershell71-help"); } /// @@ -204,7 +204,7 @@ internal UpdatableHelpCommandBase(UpdatableHelpCommandType commandType) _commandType = commandType; _helpSystem = new UpdatableHelpSystem(this, _useDefaultCredentials); _exceptions = new Dictionary(); - _helpSystem.OnProgressChanged += new EventHandler(HandleProgressChanged); + _helpSystem.OnProgressChanged += HandleProgressChanged; Random rand = new Random(); @@ -823,12 +823,8 @@ internal void ValidatePathProvider(PathInfo path) /// Message to log. internal void LogMessage(string message) { -#if !CORECLR // TODO:CORECLR Uncomment when we add PSEtwLog support - List details = new List(); - - details.Add(message); + List details = new List() { message }; PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details); -#endif } #endregion diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index e4eea1ef9cb..46026529df6 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -93,7 +93,7 @@ internal bool IsNewerVersion(UpdatableHelpInfo helpInfo, CultureInfo culture) return true; } - return v1 > v2; ; + return v1 > v2; } /// diff --git a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs index 893f46344e9..9f0c32d679a 100644 --- a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics; diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index eba8c8583d1..0a45b9a7605 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -510,6 +510,7 @@ private string ResolveUri(string baseUri, bool verbose) "; + private const string HelpInfoXmlNamespace = "http://schemas.microsoft.com/powershell/help/2010/05"; private const string HelpInfoXmlValidationFailure = "HelpInfoXmlValidationFailure"; diff --git a/src/System.Management.Automation/help/UpdatableHelpUri.cs b/src/System.Management.Automation/help/UpdatableHelpUri.cs index eea27f0534c..28683a3e2a8 100644 --- a/src/System.Management.Automation/help/UpdatableHelpUri.cs +++ b/src/System.Management.Automation/help/UpdatableHelpUri.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics; diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 88efa16f0da..bccd7418476 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/logging/LogContext.cs b/src/System.Management.Automation/logging/LogContext.cs index aa07e805e3d..84df2e34be4 100644 --- a/src/System.Management.Automation/logging/LogContext.cs +++ b/src/System.Management.Automation/logging/LogContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index 46f4bcb19cd..a46f181b262 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -228,7 +228,7 @@ protected static PSLevel GetPSLevelFromSeverity(string severity) // Estimated length of all Strings.* values // Rough estimate of values // max path for Command path - const int LogContextInitialSize = 30 * 16 + 13 * 20 + 255; + private const int LogContextInitialSize = 30 * 16 + 13 * 20 + 255; /// /// Converts log context to string. diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index e48b3fb28c4..23c687b58ee 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; @@ -101,7 +101,7 @@ private static IEnumerable GetLogProvider(ExecutionContext executio { if (executionContext == null) { - throw PSTraceSource.NewArgumentNullException("executionContext"); + throw PSTraceSource.NewArgumentNullException(nameof(executionContext)); } string shellId = executionContext.ShellID; @@ -205,13 +205,13 @@ internal static void LogEngineHealthEvent(ExecutionContext executionContext, { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } if (exception == null) { - PSTraceSource.NewArgumentNullException("exception"); + PSTraceSource.NewArgumentNullException(nameof(exception)); return; } @@ -320,13 +320,13 @@ Dictionary additionalInfo { if (logContext == null) { - PSTraceSource.NewArgumentNullException("logContext"); + PSTraceSource.NewArgumentNullException(nameof(logContext)); return; } if (exception == null) { - PSTraceSource.NewArgumentNullException("exception"); + PSTraceSource.NewArgumentNullException(nameof(exception)); return; } @@ -359,7 +359,7 @@ internal static void LogEngineLifecycleEvent(ExecutionContext executionContext, { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } @@ -407,13 +407,13 @@ Severity severity { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } if (exception == null) { - PSTraceSource.NewArgumentNullException("exception"); + PSTraceSource.NewArgumentNullException(nameof(exception)); return; } @@ -448,13 +448,13 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } if (invocationInfo == null) { - PSTraceSource.NewArgumentNullException("invocationInfo"); + PSTraceSource.NewArgumentNullException(nameof(invocationInfo)); return; } @@ -490,7 +490,7 @@ internal static void LogCommandLifecycleEvent(ExecutionContext executionContext, { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } @@ -531,7 +531,7 @@ internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionC { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } @@ -562,7 +562,7 @@ internal static void LogPipelineExecutionDetailEvent(ExecutionContext executionC { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } @@ -598,13 +598,13 @@ Severity severity { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } if (exception == null) { - PSTraceSource.NewArgumentNullException("exception"); + PSTraceSource.NewArgumentNullException(nameof(exception)); return; } @@ -639,7 +639,7 @@ internal static void LogProviderLifecycleEvent(ExecutionContext executionContext { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } @@ -675,7 +675,7 @@ internal static void LogSettingsEvent(ExecutionContext executionContext, { if (executionContext == null) { - PSTraceSource.NewArgumentNullException("executionContext"); + PSTraceSource.NewArgumentNullException(nameof(executionContext)); return; } diff --git a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs index 52711fee895..e6f301a04ac 100644 --- a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs +++ b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index 376cf0f8eda..d6b99155630 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -244,7 +244,7 @@ internal override void SetSessionStateItem(string name, object value, bool write break; } - throw PSTraceSource.NewArgumentException("value"); + throw PSTraceSource.NewArgumentException(nameof(value)); } while (false); } diff --git a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs index 0ff37f207ad..c70fe238b44 100644 --- a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 51691548d32..34cdb0d68b7 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -54,7 +54,7 @@ internal CmdletProviderContext(ExecutionContext executionContext) { if (executionContext == null) { - throw PSTraceSource.NewArgumentNullException("executionContext"); + throw PSTraceSource.NewArgumentNullException(nameof(executionContext)); } ExecutionContext = executionContext; @@ -84,7 +84,7 @@ internal CmdletProviderContext(ExecutionContext executionContext, CommandOrigin { if (executionContext == null) { - throw PSTraceSource.NewArgumentNullException("executionContext"); + throw PSTraceSource.NewArgumentNullException(nameof(executionContext)); } ExecutionContext = executionContext; @@ -118,7 +118,7 @@ internal CmdletProviderContext( // verify the command parameter if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } _command = command; @@ -172,7 +172,7 @@ internal CmdletProviderContext( // verify the command parameter if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } _command = command; @@ -220,7 +220,7 @@ internal CmdletProviderContext( // verify the command parameter if (command == null) { - throw PSTraceSource.NewArgumentNullException("command"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } _command = command; @@ -256,7 +256,7 @@ internal CmdletProviderContext( { if (contextToCopyFrom == null) { - throw PSTraceSource.NewArgumentNullException("contextToCopyFrom"); + throw PSTraceSource.NewArgumentNullException(nameof(contextToCopyFrom)); } ExecutionContext = contextToCopyFrom.ExecutionContext; @@ -985,7 +985,7 @@ internal void WriteErrorsToContext(CmdletProviderContext errorContext) { if (errorContext == null) { - throw PSTraceSource.NewArgumentNullException("errorContext"); + throw PSTraceSource.NewArgumentNullException(nameof(errorContext)); } if (HasErrors()) diff --git a/src/System.Management.Automation/namespaces/DriveProviderBase.cs b/src/System.Management.Automation/namespaces/DriveProviderBase.cs index 2a6e6ff03f7..d69f17e94ee 100644 --- a/src/System.Management.Automation/namespaces/DriveProviderBase.cs +++ b/src/System.Management.Automation/namespaces/DriveProviderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs index a5c21017569..4f1fd8eb0b0 100644 --- a/src/System.Management.Automation/namespaces/EnvironmentProvider.cs +++ b/src/System.Management.Automation/namespaces/EnvironmentProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index 4d7dae05950..5ee65158233 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -56,7 +56,9 @@ internal class FileSystemContentReaderWriter : IContentReader, IContentWriter private StreamReader _reader; private StreamWriter _writer; private bool _usingByteEncoding; + private const char DefaultDelimiter = '\n'; + private string _delimiter = $"{DefaultDelimiter}"; private int[] _offsetDictionary; private bool _usingDelimiter; @@ -156,7 +158,7 @@ public FileSystemContentReaderWriter( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (s_tracer.IsEnabled) @@ -435,7 +437,7 @@ internal void SeekItemsBackward(int backCount) if (backCount < 0) { // The caller needs to guarantee that 'backCount' is greater or equals to 0 - throw PSTraceSource.NewArgumentException("backCount"); + throw PSTraceSource.NewArgumentException(nameof(backCount)); } if (_isRawStream && _waitForChanges) @@ -1088,7 +1090,7 @@ private void WriteObject(object content) } catch (InvalidCastException) { - throw PSTraceSource.NewArgumentException("content", FileSystemProviderStrings.ByteEncodingError); + throw PSTraceSource.NewArgumentException(nameof(content), FileSystemProviderStrings.ByteEncodingError); } } else @@ -1156,6 +1158,7 @@ internal FileStreamBackReader(FileStream fileStream, Encoding encoding) private readonly Encoding _defaultAnsiEncoding; private const int BuffSize = 4096; + private readonly byte[] _byteBuff = new byte[BuffSize]; private readonly char[] _charBuff = new char[BuffSize]; private int _byteCount = 0; @@ -1434,7 +1437,7 @@ private int RefillByteBuff() int toRead = lengthLeft > BuffSize ? BuffSize : (int)lengthLeft; _stream.Seek(-toRead, SeekOrigin.Current); - if (_currentEncoding.Equals(Encoding.UTF8)) + if (_currentEncoding is UTF8Encoding) { // It's UTF-8, we need to detect the starting byte of a character do @@ -1460,14 +1463,12 @@ private int RefillByteBuff() _byteCount += _stream.Read(_byteBuff, _byteCount, (int)(lengthLeft - _stream.Position)); _stream.Position = _currentPosition; } - else if (_currentEncoding.Equals(Encoding.Unicode) || - _currentEncoding.Equals(Encoding.BigEndianUnicode) || - _currentEncoding.Equals(Encoding.UTF32) || - _currentEncoding.Equals(Encoding.ASCII) || + else if (_currentEncoding is UnicodeEncoding || + _currentEncoding is UTF32Encoding || + _currentEncoding is ASCIIEncoding || IsSingleByteCharacterSet()) { // Unicode -- two bytes per character - // BigEndianUnicode -- two types per character // UTF-32 -- four bytes per character // ASCII -- one byte per character // The BufferSize will be a multiple of 4, so we can just read toRead number of bytes diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index bda80eecb24..1ad37502614 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -83,6 +83,7 @@ public FileSystemProvider() } private Collection _excludeMatcher = null; + private static System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions { MatchType = MatchType.Win32, @@ -507,7 +508,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) // verify parameters if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } if (string.IsNullOrEmpty(drive.Root)) @@ -1260,7 +1261,7 @@ protected override void GetItem(string path) if (string.IsNullOrEmpty(path)) { // The parameter was null, throw an exception - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } try @@ -1446,7 +1447,7 @@ protected override void InvokeDefaultAction(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -1628,7 +1629,7 @@ private void GetPathItems( // Verify parameters if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -2114,14 +2115,14 @@ protected override void RenameItem( // Check the parameters if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); if (string.IsNullOrEmpty(newName)) { - throw PSTraceSource.NewArgumentException("newName"); + throw PSTraceSource.NewArgumentException(nameof(newName)); } // Clean up "newname" to fix some common usability problems: @@ -2141,7 +2142,7 @@ protected override void RenameItem( // If a path is specified for the newName then we flag that as an error. if (string.Compare(Path.GetFileName(newName), newName, StringComparison.OrdinalIgnoreCase) != 0) { - throw PSTraceSource.NewArgumentException("newName", FileSystemProviderStrings.RenameError); + throw PSTraceSource.NewArgumentException(nameof(newName), FileSystemProviderStrings.RenameError); } // Verify that the target doesn't represent a device name @@ -2255,7 +2256,7 @@ protected override void NewItem( // Verify parameters if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(type)) @@ -2351,7 +2352,7 @@ protected override void NewItem( if (string.IsNullOrEmpty(strTargetPath)) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } bool exists = false; @@ -2361,12 +2362,24 @@ protected override void NewItem( // non-existing targets on either Windows or Linux. try { - exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; - - // Pretend the target exists if we're making a symbolic link. if (itemType == ItemType.SymbolicLink) { exists = true; + + var normalizedTargetPath = strTargetPath; + if (strTargetPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || + strTargetPath.StartsWith("./", StringComparison.OrdinalIgnoreCase)) + { + normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan().Slice(2)); + } + + GetFileSystemInfo(normalizedTargetPath, out isDirectory); + + strTargetPath = strTargetPath.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); + } + else + { + exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; } } catch (Exception e) @@ -2385,7 +2398,7 @@ protected override void NewItem( if (itemType == ItemType.HardLink) { // Hard links can only be to files, not directories. - if (isDirectory == true) + if (isDirectory) { string message = StringUtil.Format(FileSystemProviderStrings.ItemNotFile, strTargetPath); WriteError(new ErrorRecord(new InvalidOperationException(message), "ItemNotFile", ErrorCategory.InvalidOperation, strTargetPath)); @@ -2663,7 +2676,7 @@ protected override void NewItem( } else { - throw PSTraceSource.NewArgumentException("type", FileSystemProviderStrings.UnknownType); + throw PSTraceSource.NewArgumentException(nameof(type), FileSystemProviderStrings.UnknownType); } } @@ -2822,7 +2835,7 @@ private bool CreateIntermediateDirectories(string path) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } try @@ -2912,7 +2925,7 @@ protected override void RemoveItem(string path, bool recurse) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } try @@ -3385,7 +3398,7 @@ private bool ItemExists(string path, out ErrorRecord error) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } bool result = false; @@ -3486,7 +3499,7 @@ protected override bool HasChildItems(string path) // verify parameters if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -3588,12 +3601,12 @@ protected override void CopyItem( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(destinationPath)) { - throw PSTraceSource.NewArgumentException("destinationPath"); + throw PSTraceSource.NewArgumentException(nameof(destinationPath)); } path = NormalizePath(path); @@ -4367,14 +4380,14 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf ps.AddParameter("copyFromNumBytes", fragmentSize); if (force) { - ps.AddParameter("force", true); + ps.AddParameter(nameof(force), true); } #if !UNIX if (isAlternateDataStream) { ps.AddParameter("isAlternateStream", true); - ps.AddParameter("streamName", streamName); + ps.AddParameter(nameof(streamName), streamName); } #endif @@ -4528,7 +4541,7 @@ private string MakeRemotePath(System.Management.Automation.PowerShell ps, string string path = null; ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName); - ps.AddParameter("remotePath", remotePath); + ps.AddParameter(nameof(remotePath), remotePath); Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); if (op != null) @@ -4689,7 +4702,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath ps.AddCommand(CopyFileRemoteUtils.PSCopyToSessionHelperName); ps.AddParameter("copyToFilePath", destinationPath); ps.AddParameter("b64Fragment", b64Fragment); - ps.AddParameter("streamName", streamName); + ps.AddParameter(nameof(streamName), streamName); } Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); @@ -4843,7 +4856,7 @@ private string CreateDirectoryOnRemoteSession(string destination, bool force, Sy ps.AddParameter("createDirectoryPath", destination); if (force) { - ps.AddParameter("force", true); + ps.AddParameter(nameof(force), true); } Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); @@ -5050,7 +5063,7 @@ protected override string NormalizeRelativePath( { if (string.IsNullOrEmpty(path) || !IsValidPath(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (basePath == null) @@ -5237,7 +5250,7 @@ private string NormalizeRelativePathHelper(string path, string basePath) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (path.Length == 0) @@ -5661,7 +5674,7 @@ protected override string GetChildName(string path) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Normalize the path @@ -5724,7 +5737,7 @@ protected override bool IsItemContainer(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -5758,12 +5771,12 @@ protected override void MoveItem( if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(destination)) { - throw PSTraceSource.NewArgumentException("destination"); + throw PSTraceSource.NewArgumentException(nameof(destination)); } path = NormalizePath(path); @@ -6122,7 +6135,7 @@ public void GetProperty(string path, Collection providerSpecificPickList { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -6255,12 +6268,12 @@ public void SetProperty(string path, PSObject propertyToSet) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (propertyToSet == null) { - throw PSTraceSource.NewArgumentNullException("propertyToSet"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyToSet)); } path = NormalizePath(path); @@ -6426,7 +6439,7 @@ public void ClearProperty( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -6434,14 +6447,14 @@ public void ClearProperty( if (propertiesToClear == null || propertiesToClear.Count == 0) { - throw PSTraceSource.NewArgumentNullException("propertiesToClear"); + throw PSTraceSource.NewArgumentNullException(nameof(propertiesToClear)); } // Only the attributes property can be cleared if (propertiesToClear.Count > 1 || Host.CurrentCulture.CompareInfo.Compare("Attributes", propertiesToClear[0], CompareOptions.IgnoreCase) != 0) { - throw PSTraceSource.NewArgumentException("propertiesToClear", FileSystemProviderStrings.CannotClearProperty); + throw PSTraceSource.NewArgumentException(nameof(propertiesToClear), FileSystemProviderStrings.CannotClearProperty); } try @@ -6544,7 +6557,7 @@ public IContentReader GetContentReader(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -6718,7 +6731,7 @@ public IContentWriter GetContentWriter(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -6847,7 +6860,7 @@ public void ClearContent(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); @@ -7307,12 +7320,16 @@ private struct NetResource public int Type; public int DisplayType; public int Usage; + [MarshalAs(UnmanagedType.LPWStr)] public string LocalName; + [MarshalAs(UnmanagedType.LPWStr)] public string RemoteName; + [MarshalAs(UnmanagedType.LPWStr)] public string Comment; + [MarshalAs(UnmanagedType.LPWStr)] public string Provider; } @@ -7855,6 +7872,7 @@ private struct REPARSE_DATA_BUFFER_SYMBOLICLINK public ushort PrintNameOffset; public ushort PrintNameLength; public uint Flags; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)] public byte[] PathBuffer; } @@ -7869,6 +7887,7 @@ private struct REPARSE_DATA_BUFFER_MOUNTPOINT public ushort SubstituteNameLength; public ushort PrintNameOffset; public ushort PrintNameLength; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)] public byte[] PathBuffer; } @@ -7880,6 +7899,7 @@ private struct REPARSE_DATA_BUFFER_APPEXECLINK public ushort ReparseDataLength; public ushort Reserved; public uint StringCount; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)] public byte[] StringList; } @@ -7905,6 +7925,7 @@ private struct GUID public uint Data1; public ushort Data2; public ushort Data3; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public char[] Data4; } @@ -7916,6 +7937,7 @@ private struct REPARSE_GUID_DATA_BUFFER public ushort ReparseDataLength; public ushort Reserved; public GUID ReparseGuid; + [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_REPARSE_SIZE)] public char[] DataBuffer; } @@ -8164,7 +8186,7 @@ internal static bool IsReparsePointWithTarget(FileSystemInfo fileInfo) var data = new WIN32_FIND_DATA(); using (var handle = FindFirstFileEx(fileInfo.FullName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0)) { - // The name surrogate bit 0x20000000 is defined in https://docs.microsoft.com/en-us/windows/win32/fileio/reparse-point-tags + // The name surrogate bit 0x20000000 is defined in https://docs.microsoft.com/windows/win32/fileio/reparse-point-tags // Name surrogates (0x20000000) are reparse points that point to other named entities local to the filesystem // (like symlinks and mount points). // In the case of OneDrive, they are not name surrogates and would be safe to recurse into. @@ -8455,12 +8477,12 @@ private static bool WinCreateJunction(string path, string target) } else { - throw new ArgumentNullException("target"); + throw new ArgumentNullException(nameof(target)); } } else { - throw new ArgumentNullException("path"); + throw new ArgumentNullException(nameof(path)); } } @@ -8535,7 +8557,7 @@ public static class AlternateDataStreamUtilities /// The list of streams (and their size) in the file. internal static List GetStreams(string path) { - if (path == null) throw new ArgumentNullException("path"); + if (path == null) throw new ArgumentNullException(nameof(path)); List alternateStreams = new List(); @@ -8648,8 +8670,8 @@ internal static bool TryCreateFileStream(string path, string streamName, FileMod /// The name of the alternate data stream to delete. internal static void DeleteFileStream(string path, string streamName) { - if (path == null) throw new ArgumentNullException("path"); - if (streamName == null) throw new ArgumentNullException("streamName"); + if (path == null) throw new ArgumentNullException(nameof(path)); + if (streamName == null) throw new ArgumentNullException(nameof(streamName)); string adjustedStreamName = streamName.Trim(); if (adjustedStreamName.IndexOf(':') != 0) @@ -8679,6 +8701,7 @@ internal static void SetZoneOfOrigin(string path, SecurityZone securityZone) internal static class NativeMethods { internal const int ERROR_HANDLE_EOF = 38; + internal enum StreamInfoLevels { FindStreamInfoStandard = 0 } [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] @@ -8750,9 +8773,11 @@ internal static class CopyFileRemoteUtils #region PSCopyToSessionHelper internal const string PSCopyToSessionHelperName = @"PSCopyToSessionHelper"; + private static string s_driveMaxSizeErrorFormatString = FileSystemProviderStrings.DriveMaxSizeError; private static string s_PSCopyToSessionHelperDefinition = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]", s_driveMaxSizeErrorFormatString); private static string s_PSCopyToSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyToSessionHelperDefinitionFormat, @"[ValidateUserDrive()]", s_driveMaxSizeErrorFormatString); + private const string PSCopyToSessionHelperDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSCopyFileToRemoteSession"")] @@ -9216,8 +9241,10 @@ function PSCreateDirectoryOnRemoteSession #region PSCopyFromSessionHelper internal const string PSCopyFromSessionHelperName = @"PSCopyFromSessionHelper"; + private static string s_PSCopyFromSessionHelperDefinition = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateNotNullOrEmpty()]"); private static string s_PSCopyFromSessionHelperDefinitionRestricted = StringUtil.Format(PSCopyFromSessionHelperDefinitionFormat, @"[ValidateUserDrive()]"); + private const string PSCopyFromSessionHelperDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSCopyFileFromRemoteSession"", Mandatory=$true)] @@ -9689,7 +9716,7 @@ PSGetPathDirAndFiles @params }} "; - internal static string PSCopyFromSessionHelper = functionToken + PSCopyFromSessionHelperName + @" + internal static readonly string PSCopyFromSessionHelper = functionToken + PSCopyFromSessionHelperName + @" { " + s_PSCopyFromSessionHelperDefinition + @" } @@ -9705,8 +9732,10 @@ PSGetPathDirAndFiles @params #region PSCopyRemoteUtils internal const string PSCopyRemoteUtilsName = @"PSCopyRemoteUtils"; - internal static string PSCopyRemoteUtilsDefinition = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateNotNullOrEmpty()]", PSValidatePathFunction); + + internal static readonly string PSCopyRemoteUtilsDefinition = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateNotNullOrEmpty()]", PSValidatePathFunction); private static string s_PSCopyRemoteUtilsDefinitionRestricted = StringUtil.Format(PSCopyRemoteUtilsDefinitionFormat, @"[ValidateUserDrive()]", PSValidatePathFunction); + private const string PSCopyRemoteUtilsDefinitionFormat = @" param ( [Parameter(ParameterSetName=""PSRemoteDirectoryExist"", Mandatory=$true)] @@ -9861,27 +9890,29 @@ function SafeGetDriveRoot return $result "; - internal static string PSCopyRemoteUtils = functionToken + PSCopyRemoteUtilsName + @" + internal static readonly string PSCopyRemoteUtils = functionToken + PSCopyRemoteUtilsName + @" { " + PSCopyRemoteUtilsDefinition + @" } "; - internal static Hashtable PSCopyRemoteUtilsFunction = new Hashtable() { + internal static readonly Hashtable PSCopyRemoteUtilsFunction = new Hashtable() { {nameToken, PSCopyRemoteUtilsName}, {definitionToken, s_PSCopyRemoteUtilsDefinitionRestricted} }; #endregion - internal static string AllCopyToRemoteScripts = s_PSCopyToSessionHelper + PSCopyRemoteUtils; + internal static readonly string AllCopyToRemoteScripts = s_PSCopyToSessionHelper + PSCopyRemoteUtils; + internal static IEnumerable GetAllCopyToRemoteScriptFunctions() { yield return s_PSCopyToSessionHelperFunction; yield return PSCopyRemoteUtilsFunction; } - internal static string AllCopyFromRemoteScripts = PSCopyFromSessionHelper + PSCopyRemoteUtils; + internal static readonly string AllCopyFromRemoteScripts = PSCopyFromSessionHelper + PSCopyRemoteUtils; + internal static IEnumerable GetAllCopyFromRemoteScriptFunctions() { yield return s_PSCopyFromSessionHelperFunction; diff --git a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs index c3b1cc1f5a6..8a95b16ee8b 100644 --- a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs +++ b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -46,12 +46,12 @@ public void GetSecurityDescriptor(string path, if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if ((sections & ~AccessControlSections.All) != 0) { - throw PSTraceSource.NewArgumentException("sections"); + throw PSTraceSource.NewArgumentException(nameof(sections)); } var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); @@ -103,14 +103,14 @@ public void SetSecurityDescriptor( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } path = NormalizePath(path); if (securityDescriptor == null) { - throw PSTraceSource.NewArgumentNullException("securityDescriptor"); + throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } if (!File.Exists(path) && !Directory.Exists(path)) @@ -123,7 +123,7 @@ public void SetSecurityDescriptor( if (sd == null) { - throw PSTraceSource.NewArgumentException("securityDescriptor"); + throw PSTraceSource.NewArgumentException(nameof(securityDescriptor)); } else { diff --git a/src/System.Management.Automation/namespaces/FunctionProvider.cs b/src/System.Management.Automation/namespaces/FunctionProvider.cs index c5d603f4158..1843d1edff8 100644 --- a/src/System.Management.Automation/namespaces/FunctionProvider.cs +++ b/src/System.Management.Automation/namespaces/FunctionProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -238,7 +238,7 @@ internal override void SetSessionStateItem(string name, object value, bool write break; } - throw PSTraceSource.NewArgumentException("value"); + throw PSTraceSource.NewArgumentException(nameof(value)); } while (false); if (writeItem && modifiedItem != null) @@ -309,7 +309,7 @@ internal override object GetValueOfItem(object item) /// internal override IDictionary GetSessionStateTable() { - return SessionState.Internal.GetFunctionTable(); + return (IDictionary)SessionState.Internal.GetFunctionTable(); } /// diff --git a/src/System.Management.Automation/namespaces/IContentProvider.cs b/src/System.Management.Automation/namespaces/IContentProvider.cs index 92c88d7a937..7c91019124d 100644 --- a/src/System.Management.Automation/namespaces/IContentProvider.cs +++ b/src/System.Management.Automation/namespaces/IContentProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Provider diff --git a/src/System.Management.Automation/namespaces/IContentReader.cs b/src/System.Management.Automation/namespaces/IContentReader.cs index 4ca0064f888..8835d948ddd 100644 --- a/src/System.Management.Automation/namespaces/IContentReader.cs +++ b/src/System.Management.Automation/namespaces/IContentReader.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/namespaces/IContentWriter.cs b/src/System.Management.Automation/namespaces/IContentWriter.cs index 437a08cfe19..e01ed0c9cb4 100644 --- a/src/System.Management.Automation/namespaces/IContentWriter.cs +++ b/src/System.Management.Automation/namespaces/IContentWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; diff --git a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs index d4ccdaa3b59..d7265e7380f 100644 --- a/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs +++ b/src/System.Management.Automation/namespaces/IDynamicPropertyProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Provider diff --git a/src/System.Management.Automation/namespaces/IPermissionProvider.cs b/src/System.Management.Automation/namespaces/IPermissionProvider.cs index b5adea6644c..13b41261a19 100644 --- a/src/System.Management.Automation/namespaces/IPermissionProvider.cs +++ b/src/System.Management.Automation/namespaces/IPermissionProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Security.AccessControl; diff --git a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs index f5e331846d9..2a347fafbce 100644 --- a/src/System.Management.Automation/namespaces/IPropertiesProvider.cs +++ b/src/System.Management.Automation/namespaces/IPropertiesProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; diff --git a/src/System.Management.Automation/namespaces/ItemProviderBase.cs b/src/System.Management.Automation/namespaces/ItemProviderBase.cs index 7562c1c58fe..c563f48aaec 100644 --- a/src/System.Management.Automation/namespaces/ItemProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ItemProviderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index 217d3787e18..ab43d492d8f 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -1869,9 +1869,7 @@ internal string GetDriveRootRelativePathFromPSPath( if (normalizedPath.StartsWith(normalizedRoot, StringComparison.OrdinalIgnoreCase)) { isPathForCurrentDrive = true; - path = path.Substring(normalizedRoot.Length); - path = path.TrimStart(StringLiterals.DefaultPathSeparator); - path = StringLiterals.DefaultPathSeparator + path; + path = string.Concat(StringLiterals.DefaultPathSeparatorString, path.AsSpan(normalizedRoot.Length).TrimStart(StringLiterals.DefaultPathSeparator)); workingDriveForPath = _sessionState.Drive.Current; } } @@ -2389,7 +2387,7 @@ private static string ParseProviderPath(string path, out string providerId) { ArgumentException e = PSTraceSource.NewArgumentException( - "path", + nameof(path), SessionStateStrings.NotProviderQualifiedPath); throw e; } @@ -3087,8 +3085,7 @@ internal static string GetDriveQualifiedPath(string path, PSDriveInfo drive) } else { - string possibleDriveName = path.Substring(0, index); - if (string.Equals(possibleDriveName, drive.Name, StringComparison.OrdinalIgnoreCase)) + if (path.AsSpan(0, index).Equals(drive.Name, StringComparison.OrdinalIgnoreCase)) { treatAsRelative = false; } @@ -4438,17 +4435,17 @@ private static string ConvertMshEscapeToRegexEscape(string path) const char mshEscapeChar = '`'; const char regexEscapeChar = '\\'; - char[] workerArray = path.ToCharArray(); + ReadOnlySpan workerArray = path; StringBuilder result = new StringBuilder(); - for (int index = 0; index < workerArray.GetLength(0); ++index) + for (int index = 0; index < workerArray.Length; ++index) { // look for an escape character if (workerArray[index] == mshEscapeChar) { - if (index + 1 < workerArray.GetLength(0)) + if (index + 1 < workerArray.Length) { if (workerArray[index + 1] == mshEscapeChar) { diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index 94f60deaacb..9bb1e3813b5 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -407,7 +407,7 @@ protected virtual string GetParentPath(string path, string root) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (root == null) @@ -508,7 +508,7 @@ internal string ContractRelativePath( if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (path.Length == 0) @@ -706,7 +706,7 @@ protected virtual string GetChildName(string path) if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Normalize the path @@ -873,12 +873,12 @@ private string NormalizePath(string path) // normalize it, then we will get a wrong path. // // Fast return if nothing to normalize. - if (path.IndexOf(StringLiterals.AlternatePathSeparator) == -1) + if (!path.Contains(StringLiterals.AlternatePathSeparator)) { return path; } - bool pathHasBackSlash = path.IndexOf(StringLiterals.DefaultPathSeparator) != -1; + bool pathHasBackSlash = path.Contains(StringLiterals.DefaultPathSeparator); string normalizedPath; // There is a mix of slashes & the path is rooted & the path exists without normalization. @@ -1039,7 +1039,7 @@ private static Stack NormalizeThePath( PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( - "path", + nameof(path), SessionStateStrings.NormalizeRelativePathOutsideBase, path, basePath); diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index 9440eb56e51..cd91845f84c 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Dbg = System.Management.Automation; diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 4b9e46ab596..326d4d51b04 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -78,7 +78,7 @@ public abstract partial class CmdletProvider : IResourceSupplier [TraceSourceAttribute( "CmdletProviderClasses", "The namespace provider base classes tracer")] - internal static PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( + internal static readonly PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( "CmdletProviderClasses", "The namespace provider base classes tracer"); @@ -98,7 +98,7 @@ internal void SetProviderInformation(ProviderInfo providerInfoToSet) { if (providerInfoToSet == null) { - throw PSTraceSource.NewArgumentNullException("providerInfoToSet"); + throw PSTraceSource.NewArgumentNullException(nameof(providerInfoToSet)); } _providerInformation = providerInfoToSet; @@ -1425,12 +1425,12 @@ public virtual string GetResourceString(string baseName, string resourceId) { if (string.IsNullOrEmpty(baseName)) { - throw PSTraceSource.NewArgumentException("baseName"); + throw PSTraceSource.NewArgumentException(nameof(baseName)); } if (string.IsNullOrEmpty(resourceId)) { - throw PSTraceSource.NewArgumentException("resourceId"); + throw PSTraceSource.NewArgumentException(nameof(resourceId)); } ResourceManager manager = @@ -1447,12 +1447,12 @@ public virtual string GetResourceString(string baseName, string resourceId) } catch (MissingManifestResourceException) { - throw PSTraceSource.NewArgumentException("baseName", GetErrorText.ResourceBaseNameFailure, baseName); + throw PSTraceSource.NewArgumentException(nameof(baseName), GetErrorText.ResourceBaseNameFailure, baseName); } if (retValue == null) { - throw PSTraceSource.NewArgumentException("resourceId", GetErrorText.ResourceIdFailure, resourceId); + throw PSTraceSource.NewArgumentException(nameof(resourceId), GetErrorText.ResourceIdFailure, resourceId); } return retValue; @@ -1468,7 +1468,7 @@ public void ThrowTerminatingError(ErrorRecord errorRecord) { if (errorRecord == null) { - throw PSTraceSource.NewArgumentNullException("errorRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } if (errorRecord.ErrorDetails != null @@ -1677,7 +1677,7 @@ public void WriteProgress(ProgressRecord progressRecord) if (progressRecord == null) { - throw PSTraceSource.NewArgumentNullException("progressRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(progressRecord)); } Context.WriteProgress(progressRecord); @@ -1801,7 +1801,7 @@ private PSObject WrapOutputInPSObject( { if (item == null) { - throw PSTraceSource.NewArgumentNullException("item"); + throw PSTraceSource.NewArgumentNullException(nameof(item)); } PSObject result = new PSObject(item); @@ -2000,7 +2000,7 @@ public void WriteError(ErrorRecord errorRecord) if (errorRecord == null) { - throw PSTraceSource.NewArgumentNullException("errorRecord"); + throw PSTraceSource.NewArgumentNullException(nameof(errorRecord)); } if (errorRecord.ErrorDetails != null diff --git a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs index 16fd633c9e1..c232b769fb3 100644 --- a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs +++ b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Security.AccessControl; diff --git a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs index e490db90a18..dbc03a69181 100644 --- a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs +++ b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Provider @@ -37,13 +37,13 @@ public CmdletProviderAttribute( if (string.IsNullOrEmpty(providerName)) { - throw PSTraceSource.NewArgumentNullException("providerName"); + throw PSTraceSource.NewArgumentNullException(nameof(providerName)); } if (providerName.IndexOfAny(_illegalCharacters) != -1) { throw PSTraceSource.NewArgumentException( - "providerName", + nameof(providerName), SessionStateStrings.ProviderNameNotValid, providerName); } diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 7aa18ebee6c..5aa8fbc954d 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -112,7 +112,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) { if (drive == null) { - throw PSTraceSource.NewArgumentNullException("drive"); + throw PSTraceSource.NewArgumentNullException(nameof(drive)); } if (!ItemExists(drive.Root)) @@ -249,7 +249,7 @@ protected override void SetItem(string path, object value) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Confirm the set item with the user @@ -413,7 +413,7 @@ protected override void ClearItem(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Confirm the clear item with the user @@ -533,7 +533,7 @@ protected override void GetChildItems( if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (IsHiveContainer(path)) @@ -680,7 +680,7 @@ protected override void GetChildNames( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (path.Length == 0) @@ -871,12 +871,12 @@ protected override void RenameItem( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(newName)) { - throw PSTraceSource.NewArgumentException("newName"); + throw PSTraceSource.NewArgumentException(nameof(newName)); } s_tracer.WriteLine("newName = {0}", newName); @@ -941,7 +941,7 @@ protected override void NewItem( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Confirm the new item with the user @@ -1100,7 +1100,7 @@ protected override void RemoveItem( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } s_tracer.WriteLine("recurse = {0}", recurse); @@ -1186,7 +1186,7 @@ protected override bool ItemExists(string path) if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } try @@ -1240,7 +1240,7 @@ protected override bool HasChildItems(string path) if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } try @@ -1298,12 +1298,12 @@ protected override void CopyItem( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(destination)) { - throw PSTraceSource.NewArgumentException("destination"); + throw PSTraceSource.NewArgumentException(nameof(destination)); } s_tracer.WriteLine("destination = {0}", destination); @@ -1586,7 +1586,7 @@ protected override bool IsItemContainer(string path) { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } bool result = false; @@ -1642,12 +1642,12 @@ protected override void MoveItem( { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (string.IsNullOrEmpty(destination)) { - throw PSTraceSource.NewArgumentException("destination"); + throw PSTraceSource.NewArgumentException(nameof(destination)); } s_tracer.WriteLine("destination = {0}", destination); @@ -1785,7 +1785,7 @@ public void GetProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) @@ -1853,7 +1853,7 @@ public void SetProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) @@ -1863,7 +1863,7 @@ public void SetProperty( if (propertyValue == null) { - throw PSTraceSource.NewArgumentNullException("propertyValue"); + throw PSTraceSource.NewArgumentNullException(nameof(propertyValue)); } IRegistryWrapper key = GetRegkeyForPathWriteIfError(path, true); @@ -1978,7 +1978,7 @@ public void ClearProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) @@ -2122,7 +2122,7 @@ public void NewProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) @@ -2234,7 +2234,7 @@ public void RemoveProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) @@ -2337,7 +2337,7 @@ public void RenameProperty( { if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (!CheckOperationNotAllowedOnHiveContainer(path)) @@ -2426,12 +2426,12 @@ public void CopyProperty( { if (sourcePath == null) { - throw PSTraceSource.NewArgumentNullException("sourcePath"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePath)); } if (destinationPath == null) { - throw PSTraceSource.NewArgumentNullException("destinationPath"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (!CheckOperationNotAllowedOnHiveContainer(sourcePath, destinationPath)) @@ -2526,12 +2526,12 @@ public void MoveProperty( { if (sourcePath == null) { - throw PSTraceSource.NewArgumentNullException("sourcePath"); + throw PSTraceSource.NewArgumentNullException(nameof(sourcePath)); } if (destinationPath == null) { - throw PSTraceSource.NewArgumentNullException("destinationPath"); + throw PSTraceSource.NewArgumentNullException(nameof(destinationPath)); } if (!CheckOperationNotAllowedOnHiveContainer(sourcePath, destinationPath)) @@ -2979,7 +2979,7 @@ private void GetFilteredRegistryKeyProperties(string path, if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } filteredCollection = new Collection(); @@ -3062,7 +3062,7 @@ private void GetFilteredRegistryKeyProperties(string path, if ( expandAll || ((Context.SuppressWildcardExpansion == false) && (valueNameMatcher.IsMatch(valueNameToMatch))) || - ((Context.SuppressWildcardExpansion == true) && (string.Equals(valueNameToMatch, requestedValueName, StringComparison.OrdinalIgnoreCase)))) + ((Context.SuppressWildcardExpansion) && (string.Equals(valueNameToMatch, requestedValueName, StringComparison.OrdinalIgnoreCase)))) { if (string.IsNullOrEmpty(valueNameToMatch)) { @@ -3199,7 +3199,7 @@ private bool IsHiveContainer(string path) bool result = false; if (path == null) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if (string.IsNullOrEmpty(path) || @@ -3273,7 +3273,7 @@ private IRegistryWrapper GetHiveRoot(string path) { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (TransactionAvailable()) @@ -3321,7 +3321,7 @@ private bool CreateIntermediateKeys(string path) // Check input. if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } try @@ -3359,7 +3359,7 @@ private bool CreateIntermediateKeys(string path) if (remainingPath.Length == 0 || rootKey == null) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } // Create new subkey..and close @@ -3373,7 +3373,7 @@ private bool CreateIntermediateKeys(string path) { // SubKey is null // Unable to create intermediate keys - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } result = true; @@ -3833,7 +3833,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) { value = 0; } - }; break; + } break; case RegistryValueKind.ExpandString: value = (value != null) @@ -3870,7 +3870,7 @@ private static object ConvertValueToKind(object value, RegistryValueKind kind) { value = 0; } - }; break; + } break; case RegistryValueKind.String: value = (value != null) @@ -3896,7 +3896,7 @@ private static RegistryValueKind GetValueKindFromObject(object value) { if (value == null) { - throw PSTraceSource.NewArgumentNullException("value"); + throw PSTraceSource.NewArgumentNullException(nameof(value)); } RegistryValueKind result = RegistryValueKind.Unknown; diff --git a/src/System.Management.Automation/namespaces/RegistrySecurity.cs b/src/System.Management.Automation/namespaces/RegistrySecurity.cs index c528c3b5131..04f25d7f06f 100644 --- a/src/System.Management.Automation/namespaces/RegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/RegistrySecurity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -48,12 +48,12 @@ public void GetSecurityDescriptor(string path, // Validate input first. if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentNullException("path"); + throw PSTraceSource.NewArgumentNullException(nameof(path)); } if ((sections & ~AccessControlSections.All) != 0) { - throw PSTraceSource.NewArgumentException("sections"); + throw PSTraceSource.NewArgumentException(nameof(sections)); } path = NormalizePath(path); @@ -93,12 +93,12 @@ public void SetSecurityDescriptor( if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (securityDescriptor == null) { - throw PSTraceSource.NewArgumentNullException("securityDescriptor"); + throw PSTraceSource.NewArgumentNullException(nameof(securityDescriptor)); } path = NormalizePath(path); @@ -110,7 +110,7 @@ public void SetSecurityDescriptor( if (sd == null) { - throw PSTraceSource.NewArgumentException("securityDescriptor"); + throw PSTraceSource.NewArgumentException(nameof(securityDescriptor)); } } else @@ -119,7 +119,7 @@ public void SetSecurityDescriptor( if (sd == null) { - throw PSTraceSource.NewArgumentException("securityDescriptor"); + throw PSTraceSource.NewArgumentException(nameof(securityDescriptor)); } } diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index 049c65fbd34..6f0c3e3d66f 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* @@ -30,11 +30,13 @@ internal interface IRegistryWrapper object GetValue(string name); object GetValue(string name, object defaultValue, RegistryValueOptions options); RegistryValueKind GetValueKind(string name); + object RegistryKey { get; } void SetAccessControl(ObjectSecurity securityDescriptor); ObjectSecurity GetAccessControl(AccessControlSections includeSections); void Close(); + string Name { get; } int SubKeyCount { get; } diff --git a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs index 2bfa089d455..3d9e299d028 100644 --- a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs +++ b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs index d26d3ce3642..01cef7dce46 100644 --- a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs +++ b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index d96010ed163..33b043ce919 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -190,7 +190,7 @@ protected override void SetItem( if (string.IsNullOrEmpty(name)) { WriteError(new ErrorRecord( - PSTraceSource.NewArgumentNullException("name"), + PSTraceSource.NewArgumentNullException(nameof(name)), "SetItemNullName", ErrorCategory.InvalidArgument, name)); @@ -241,7 +241,7 @@ protected override void ClearItem(string path) if (string.IsNullOrEmpty(path)) { WriteError(new ErrorRecord( - PSTraceSource.NewArgumentNullException("path"), + PSTraceSource.NewArgumentNullException(nameof(path)), "ClearItemNullPath", ErrorCategory.InvalidArgument, path)); @@ -608,7 +608,7 @@ protected override void RemoveItem(string path, bool recurse) if (string.IsNullOrEmpty(path)) { Exception e = - PSTraceSource.NewArgumentException("path"); + PSTraceSource.NewArgumentException(nameof(path)); WriteError(new ErrorRecord( e, "RemoveItemNullPath", @@ -682,7 +682,7 @@ protected override void NewItem(string path, string type, object newItem) if (string.IsNullOrEmpty(path)) { Exception e = - PSTraceSource.NewArgumentException("path"); + PSTraceSource.NewArgumentException(nameof(path)); WriteError(new ErrorRecord( e, "NewItemNullPath", @@ -710,7 +710,7 @@ protected override void NewItem(string path, string type, object newItem) PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( - "path", + nameof(path), SessionStateStrings.NewItemAlreadyExists, path); @@ -760,7 +760,7 @@ protected override void CopyItem(string path, string copyPath, bool recurse) if (string.IsNullOrEmpty(path)) { Exception e = - PSTraceSource.NewArgumentException("path"); + PSTraceSource.NewArgumentException(nameof(path)); WriteError(new ErrorRecord( e, "CopyItemNullPath", @@ -840,7 +840,7 @@ protected override void CopyItem(string path, string copyPath, bool recurse) PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( - "path", + nameof(path), SessionStateStrings.CopyItemDoesntExist, path); @@ -866,7 +866,7 @@ protected override void RenameItem(string name, string newName) if (string.IsNullOrEmpty(name)) { Exception e = - PSTraceSource.NewArgumentException("name"); + PSTraceSource.NewArgumentException(nameof(name)); WriteError(new ErrorRecord( e, "RenameItemNullPath", @@ -899,7 +899,7 @@ protected override void RenameItem(string name, string newName) PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( - "newName", + nameof(newName), SessionStateStrings.NewItemAlreadyExists, newName); @@ -986,7 +986,7 @@ protected override void RenameItem(string name, string newName) PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( - "name", + nameof(name), SessionStateStrings.RenameItemDoesntExist, name); @@ -1104,12 +1104,12 @@ internal SessionStateProviderBaseContentReaderWriter(string path, SessionStatePr { if (string.IsNullOrEmpty(path)) { - throw PSTraceSource.NewArgumentException("path"); + throw PSTraceSource.NewArgumentException(nameof(path)); } if (provider == null) { - throw PSTraceSource.NewArgumentNullException("provider"); + throw PSTraceSource.NewArgumentNullException(nameof(provider)); } _path = path; @@ -1175,7 +1175,7 @@ public IList Write(IList content) { if (content == null) { - throw PSTraceSource.NewArgumentNullException("content"); + throw PSTraceSource.NewArgumentNullException(nameof(content)); } // Unravel the IList if there is only one value diff --git a/src/System.Management.Automation/namespaces/StackInfo.cs b/src/System.Management.Automation/namespaces/StackInfo.cs index c8f068f4bd2..887285c37fe 100644 --- a/src/System.Management.Automation/namespaces/StackInfo.cs +++ b/src/System.Management.Automation/namespaces/StackInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -29,12 +29,12 @@ internal PathInfoStack(string stackName, Stack locationStack) : base() { if (locationStack == null) { - throw PSTraceSource.NewArgumentNullException("locationStack"); + throw PSTraceSource.NewArgumentNullException(nameof(locationStack)); } if (string.IsNullOrEmpty(stackName)) { - throw PSTraceSource.NewArgumentException("stackName"); + throw PSTraceSource.NewArgumentException(nameof(stackName)); } Name = stackName; diff --git a/src/System.Management.Automation/namespaces/TransactedRegistry.cs b/src/System.Management.Automation/namespaces/TransactedRegistry.cs index ea293cc857d..56062e6de6c 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistry.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs index 145d72f0618..dac6f6c0897 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // @@ -1723,7 +1723,7 @@ internal static void Win32ErrorStatic(int errorCode, string str) internal static string FixupName(string name) { BCLDebug.Assert(name != null, "[FixupName]name!=null"); - if (name.IndexOf('\\') == -1) + if (name.Contains('\\')) return name; StringBuilder sb = new StringBuilder(name); diff --git a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs index a6f69c981d9..e0cd273fe2b 100644 --- a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs +++ b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // diff --git a/src/System.Management.Automation/namespaces/VariableProvider.cs b/src/System.Management.Automation/namespaces/VariableProvider.cs index 994476117e7..5da5351ebad 100644 --- a/src/System.Management.Automation/namespaces/VariableProvider.cs +++ b/src/System.Management.Automation/namespaces/VariableProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/src/System.Management.Automation/namespaces/Win32Native.cs b/src/System.Management.Automation/namespaces/Win32Native.cs index 5ce1810440a..41638e9b969 100644 --- a/src/System.Management.Automation/namespaces/Win32Native.cs +++ b/src/System.Management.Automation/namespaces/Win32Native.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // NOTE: A vast majority of this code was copied from BCL in diff --git a/src/System.Management.Automation/resources/Modules.resx b/src/System.Management.Automation/resources/Modules.resx index a74152b9717..345811502b6 100644 --- a/src/System.Management.Automation/resources/Modules.resx +++ b/src/System.Management.Automation/resources/Modules.resx @@ -511,7 +511,7 @@ Some commands from module {0} cannot be imported over a CimSession. To get all the commands, verify that the remote server has PowerShell remote management enabled, and then try adding the PSSession parameter to an Import-Module cmdlet. - Module {0} is loaded in Windows PowerShell using {1} remoting session; please note that all input and output of commands from this module will be deserialized objects. If you want to load this module into PowerShell Core please use 'Import-Module -SkipEditionCheck' syntax. + Module {0} is loaded in Windows PowerShell using {1} remoting session; please note that all input and output of commands from this module will be deserialized objects. If you want to load this module into PowerShell please use 'Import-Module -SkipEditionCheck' syntax. Detected Windows PowerShell version {0}. Windows PowerShell 5.1 is required to load modules using Windows PowerShell compatibility feature. Install Windows Management Framework (WMF) 5.1 from https://aka.ms/WMF5Download to enable this feature. diff --git a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx index 3f9e9ad1183..b4f9dc40a89 100644 --- a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx +++ b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx @@ -1339,9 +1339,6 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. - - You are currently in a PowerShell PSSession and cannot use the Enter-PSSession cmdlet to enter another PSSession. - Cannot start job. The language mode for this session is incompatible with the system-wide language mode. @@ -1696,4 +1693,7 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro Remote debugger exception: {0}, error message: {1} + + Unable to create Windows PowerShell process because Windows PowerShell could not be found on this machine. + diff --git a/src/System.Management.Automation/resources/SecuritySupportStrings.resx b/src/System.Management.Automation/resources/SecuritySupportStrings.resx index d263c3895b7..cd8a65a5c90 100644 --- a/src/System.Management.Automation/resources/SecuritySupportStrings.resx +++ b/src/System.Management.Automation/resources/SecuritySupportStrings.resx @@ -141,4 +141,16 @@ Session key not available to encrypt secure string. + + Invalid buffer offset. + + + Invalid public key data. + + + Cannot import public key. + + + Invalid session key data. + diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index 1b809231cae..cf5e559f830 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -112,7 +112,7 @@ internal static Signature SignFile(SigningOption option, (timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0)) { throw PSTraceSource.NewArgumentException( - "certificate", + nameof(certificate), Authenticode.TimeStampUrlRequired); } } @@ -131,7 +131,7 @@ internal static Signature SignFile(SigningOption option, if (oidPtr == IntPtr.Zero) { throw PSTraceSource.NewArgumentException( - "certificate", + nameof(certificate), Authenticode.InvalidHashAlgorithm); } else @@ -146,7 +146,7 @@ internal static Signature SignFile(SigningOption option, if (!SecuritySupport.CertIsGoodForSigning(certificate)) { throw PSTraceSource.NewArgumentException( - "certificate", + nameof(certificate), Authenticode.CertNotGoodForSigning); } @@ -226,7 +226,7 @@ internal static Signature SignFile(SigningOption option, if (error == Win32Errors.NTE_BAD_ALGID) { throw PSTraceSource.NewArgumentException( - "certificate", + nameof(certificate), Authenticode.InvalidHashAlgorithm); } diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 1ed0a8ef148..050c373af74 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -218,7 +218,7 @@ internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileTo if (dirInfo != null) { // Relative path of the file is the path inside the containing folder excluding folder Name - relativePath = fileToHash.FullName.Substring(dirInfo.FullName.Length).TrimStart('\\'); + relativePath = fileToHash.FullName.AsSpan(dirInfo.FullName.Length).TrimStart('\\').ToString(); } else { @@ -613,7 +613,7 @@ internal static void ProcessPathFile(FileInfo fileToHash, DirectoryInfo dirInfo, if (dirInfo != null) { // Relative path of the file is the path inside the containing folder excluding folder Name - relativePath = fileToHash.FullName.Substring(dirInfo.FullName.Length).TrimStart('\\'); + relativePath = fileToHash.FullName.AsSpan(dirInfo.FullName.Length).TrimStart('\\').ToString(); exclude = fileToHash.Name; } else @@ -631,9 +631,8 @@ internal static void ProcessPathFile(FileInfo fileToHash, DirectoryInfo dirInfo, fileHash = CalculateFileHash(fileToHash.FullName, hashAlgorithm); } - if (!fileHashes.ContainsKey(relativePath)) + if (fileHashes.TryAdd(relativePath, fileHash)) { - fileHashes.Add(relativePath, fileHash); _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.FoundFileInPath, relativePath, fileHash)); } else @@ -750,7 +749,7 @@ internal static CatalogInformation ValidateCatalog(PSCmdlet cmdlet, Collection /// Create a new SecureString based on the specified binary data. @@ -131,7 +131,7 @@ internal static byte[] ByteArrayFromString(string s) { for (int i = 0; i < dataLen; i++) { - data[i] = byte.Parse(s.Substring(2 * i, 2), + data[i] = byte.Parse(s.AsSpan(2 * i, 2), NumberStyles.AllowHexSpecifier, System.Globalization.CultureInfo.InvariantCulture); } @@ -185,7 +185,7 @@ internal static SecureString Unprotect(string input) Utils.CheckArgForNullOrEmpty(input, "input"); if ((input.Length % 2) != 0) { - throw PSTraceSource.NewArgumentException("input", Serialization.InvalidEncryptedString, input); + throw PSTraceSource.NewArgumentException(nameof(input), Serialization.InvalidEncryptedString, input); } byte[] data = null; @@ -432,7 +432,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec { if (userData == null) { - throw new ArgumentNullException("userData"); + throw new ArgumentNullException(nameof(userData)); } GCHandle pbDataIn = new GCHandle(); @@ -520,7 +520,7 @@ public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, Dat { if (encryptedData == null) { - throw new ArgumentNullException("encryptedData"); + throw new ArgumentNullException(nameof(encryptedData)); } GCHandle pbDataIn = new GCHandle(); diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 940241b260f..f6ae0fdf1f3 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -83,7 +83,7 @@ public PSAuthorizationManager(string shellId) { if (string.IsNullOrEmpty(shellId)) { - throw PSTraceSource.NewArgumentNullException("shellId"); + throw PSTraceSource.NewArgumentNullException(nameof(shellId)); } _shellId = shellId; @@ -383,7 +383,7 @@ private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Excep { TrustPublisher(signature); policyCheckPassed = true; - }; break; + } break; case RunPromptDecision.DoNotRun: policyCheckPassed = false; reasonMessage = StringUtil.Format(Authenticode.Reason_DoNotRun, path); @@ -395,7 +395,7 @@ private bool SetPolicyFromAuthenticodePrompt(string path, PSHost host, ref Excep reasonMessage = StringUtil.Format(Authenticode.Reason_NeverRun, path); reason = new UnauthorizedAccessException(reasonMessage); policyCheckPassed = false; - }; break; + } break; } return policyCheckPassed; diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index ee1058be350..90d4a71d73b 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -1,25 +1,26 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 #pragma warning disable 56523 +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; -using Microsoft.PowerShell; -using Microsoft.PowerShell.Commands; -using System.Management.Automation.Security; +using System.Globalization; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; +using System.Management.Automation.Security; +using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; -using System.Globalization; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Runtime.InteropServices; +using Microsoft.PowerShell; +using Microsoft.PowerShell.Commands; + using DWORD = System.UInt32; namespace Microsoft.PowerShell @@ -142,15 +143,20 @@ internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPol switch (policy) { case ExecutionPolicy.Restricted: - executionPolicy = "Restricted"; break; + executionPolicy = "Restricted"; + break; case ExecutionPolicy.AllSigned: - executionPolicy = "AllSigned"; break; + executionPolicy = "AllSigned"; + break; case ExecutionPolicy.RemoteSigned: - executionPolicy = "RemoteSigned"; break; + executionPolicy = "RemoteSigned"; + break; case ExecutionPolicy.Unrestricted: - executionPolicy = "Unrestricted"; break; + executionPolicy = "Unrestricted"; + break; case ExecutionPolicy.Bypass: - executionPolicy = "Bypass"; break; + executionPolicy = "Bypass"; + break; } // Set the execution policy @@ -359,12 +365,18 @@ internal static string GetExecutionPolicy(ExecutionPolicy policy) { switch (policy) { - case ExecutionPolicy.Bypass: return "Bypass"; - case ExecutionPolicy.Unrestricted: return "Unrestricted"; - case ExecutionPolicy.RemoteSigned: return "RemoteSigned"; - case ExecutionPolicy.AllSigned: return "AllSigned"; - case ExecutionPolicy.Restricted: return "Restricted"; - default: return "Restricted"; + case ExecutionPolicy.Bypass: + return "Bypass"; + case ExecutionPolicy.Unrestricted: + return "Unrestricted"; + case ExecutionPolicy.RemoteSigned: + return "RemoteSigned"; + case ExecutionPolicy.AllSigned: + return "AllSigned"; + case ExecutionPolicy.Restricted: + return "Restricted"; + default: + return "Restricted"; } } @@ -595,7 +607,7 @@ internal static void CheckIfFileExists(string filePath) /// True on success, false otherwise. internal static bool CertIsGoodForSigning(X509Certificate2 c) { - if (!CertHasPrivatekey(c)) + if (!c.HasPrivateKey) { return false; } @@ -618,18 +630,33 @@ internal static bool CertIsGoodForEncryption(X509Certificate2 c) CertHasKeyUsage(c, X509KeyUsageFlags.KeyEncipherment))); } - private static bool CertHasOid(X509Certificate2 c, string oid) + /// + /// Check to see if the specified cert is expiring by the time. + /// + /// Certificate object. + /// Certificate expire time. + /// True on success, false otherwise. + internal static bool CertExpiresByTime(X509Certificate2 c, DateTime expiring) { - Collection ekus = GetCertEKU(c); + return c.NotAfter < expiring; + } - foreach (string testOid in ekus) + private static bool CertHasOid(X509Certificate2 c, string oid) + { + foreach (var extension in c.Extensions) { - if (testOid == oid) + if (extension is X509EnhancedKeyUsageExtension ext) { - return true; + foreach (Oid ekuOid in ext.EnhancedKeyUsages) + { + if (ekuOid.Value == oid) + { + return true; + } + } + break; } } - return false; } @@ -644,24 +671,12 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa { return true; } - break; } } - return false; } - /// - /// Check if the specified cert has a private key in it. - /// - /// Certificate object. - /// True on success, false otherwise. - internal static bool CertHasPrivatekey(X509Certificate2 cert) - { - return cert.HasPrivateKey; - } - /// /// Get the EKUs of a cert. /// @@ -753,174 +768,53 @@ internal CertificateFilterInfo() } /// - /// Purpose of a certificate. + /// Gets or sets purpose of a certificate. /// internal CertificatePurpose Purpose { - get { return _purpose; } - - set { _purpose = value; } - } + get; + set; + } = CertificatePurpose.NotSpecified; /// - /// SSL Server Authentication. + /// Gets or sets SSL Server Authentication. /// internal bool SSLServerAuthentication { - get { return _sslServerAuthentication; } - - set { _sslServerAuthentication = value; } - } + get; - /// - /// DNS name of a certificate. - /// - internal string DnsName - { - set { _dnsName = value; } + set; } /// - /// EKU OID list of a certificate. + /// Gets or sets DNS name of a certificate. /// - internal string[] Eku + internal WildcardPattern DnsName { - set { _eku = value; } + get; + set; } /// - /// Remaining validity period in days for a certificate. + /// Gets or sets EKU OID list of a certificate. /// - internal int ExpiringInDays + internal List Eku { - set { _expiringInDays = value; } + get; + set; } /// - /// Combine properties into a filter string. + /// Gets or sets validity time for a certificate. /// - internal string FilterString + internal DateTime Expiring { - get - { - string filterString = string.Empty; - - if (_dnsName != null) - { - filterString = AppendFilter(filterString, "dns", _dnsName); - } - - string ekuT = string.Empty; - if (_eku != null) - { - for (int i = 0; i < _eku.Length; i++) - { - if (ekuT.Length != 0) - { - ekuT = ekuT + ","; - } - - ekuT = ekuT + _eku[i]; - } - } - - if (_purpose == CertificatePurpose.CodeSigning) - { - if (ekuT.Length != 0) - { - ekuT = ekuT + ","; - } - - ekuT = ekuT + CodeSigningOid; - } - - if (_purpose == CertificatePurpose.DocumentEncryption) - { - if (ekuT.Length != 0) - { - ekuT = ekuT + ","; - } - - ekuT = ekuT + DocumentEncryptionOid; - } - - if (_sslServerAuthentication) - { - if (ekuT.Length != 0) - { - ekuT = ekuT + ","; - } - - ekuT = ekuT + szOID_PKIX_KP_SERVER_AUTH; - } - - if (ekuT.Length != 0) - { - filterString = AppendFilter(filterString, "eku", ekuT); - if (_purpose == CertificatePurpose.CodeSigning || - _sslServerAuthentication) - { - filterString = AppendFilter(filterString, "key", "*"); - } - } - - if (_expiringInDays >= 0) - { - filterString = AppendFilter( - filterString, - "ExpiringInDays", - _expiringInDays.ToString(System.Globalization.CultureInfo.InvariantCulture)); - } - - if (filterString.Length == 0) - { - filterString = null; - } - - return filterString; - } - } - - private string AppendFilter( - string filterString, - string name, - string value) - { - string newfilter = value; - - // append a "name=value" filter to the existing filter string. - // insert a separating "&" if existing filter string is not empty. - - // if the value is empty, do nothing. - - if (newfilter.Length != 0) - { - // if the value contains an equal sign or an ampersand, throw - // an exception to avoid compromising the native code parser. - - if (newfilter.Contains("=") || newfilter.Contains("&")) - { - Marshal.ThrowExceptionForHR(Security.NativeMethods.E_INVALID_DATA); - } - - newfilter = name + "=" + newfilter; - if (filterString.Length != 0) - { - newfilter = "&" + newfilter; - } - } - - return filterString + newfilter; - } - - private CertificatePurpose _purpose = 0; - private bool _sslServerAuthentication = false; - private string _dnsName = null; - private string[] _eku = null; - private int _expiringInDays = -1; + get; + set; + } = DateTime.MinValue; internal const string CodeSigningOid = "1.3.6.1.5.5.7.3.3"; - internal const string szOID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"; + internal const string OID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"; // The OID arc 1.3.6.1.4.1.311.80 is assigned to PowerShell. If we need // new OIDs, we can assign them under this branch. @@ -1016,11 +910,11 @@ internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipi return encodedContent; } - internal static string BEGIN_CMS_SIGIL = "-----BEGIN CMS-----"; - internal static string END_CMS_SIGIL = "-----END CMS-----"; + internal static readonly string BEGIN_CMS_SIGIL = "-----BEGIN CMS-----"; + internal static readonly string END_CMS_SIGIL = "-----END CMS-----"; - internal static string BEGIN_CERTIFICATE_SIGIL = "-----BEGIN CERTIFICATE-----"; - internal static string END_CERTIFICATE_SIGIL = "-----END CERTIFICATE-----"; + internal static readonly string BEGIN_CERTIFICATE_SIGIL = "-----BEGIN CERTIFICATE-----"; + internal static readonly string END_CERTIFICATE_SIGIL = "-----END CERTIFICATE-----"; /// /// Adds Ascii armour to a byte stream in Base64 format. @@ -1138,8 +1032,10 @@ public void Resolve(SessionState sessionState, ResolutionPurpose purpose, out Er // Process the certificate if that was supplied exactly if (_pendingCertificate != null) { - ProcessResolvedCertificates(purpose, - new List { _pendingCertificate }, out error); + ProcessResolvedCertificates( + purpose, + new X509Certificate2Collection(_pendingCertificate), + out error); if ((error != null) || (Certificates.Count != 0)) { return; @@ -1162,15 +1058,8 @@ public void Resolve(SessionState sessionState, ResolutionPurpose purpose, out Er return; } - // Then by thumbprint - ResolveFromThumbprint(sessionState, purpose, out error); - if ((error != null) || (Certificates.Count != 0)) - { - return; - } - - // Then by Subject Name - ResolveFromSubjectName(sessionState, purpose, out error); + // Then by cert store + ResolveFromStoreById(purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; @@ -1215,7 +1104,7 @@ private void ResolveFromBase64Encoding(ResolutionPurpose purpose, out ErrorRecor return; } - List certificatesToProcess = new List(); + var certificatesToProcess = new X509Certificate2Collection(); try { X509Certificate2 newCertificate = new X509Certificate2(messageBytes); @@ -1289,7 +1178,7 @@ private void ResolveFromPath(SessionState sessionState, ResolutionPurpose purpos resolvedPaths.Remove(path); } - List certificatesToProcess = new List(); + var certificatesToProcess = new X509Certificate2Collection(); foreach (string path in resolvedPaths) { X509Certificate2 certificate = null; @@ -1311,99 +1200,51 @@ private void ResolveFromPath(SessionState sessionState, ResolutionPurpose purpos } } - private void ResolveFromThumbprint(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) + private void ResolveFromStoreById(ResolutionPurpose purpose, out ErrorRecord error) { - // Quickly check that this is a thumbprint-like pattern (just hex) - if (!System.Text.RegularExpressions.Regex.IsMatch(_identifier, "^[a-f0-9]+$", Text.RegularExpressions.RegexOptions.IgnoreCase)) - { - error = null; - return; - } - - Collection certificates = new Collection(); + error = null; + WildcardPattern subjectNamePattern = WildcardPattern.Get(_identifier, WildcardOptions.IgnoreCase); try { - // Get first from 'My' store - string certificatePath = sessionState.Path.Combine("Microsoft.PowerShell.Security\\Certificate::CurrentUser\\My", _identifier); - if (sessionState.InvokeProvider.Item.Exists(certificatePath)) - { - foreach (PSObject certificateObject in sessionState.InvokeProvider.Item.Get(certificatePath)) - { - certificates.Add(certificateObject); - } - } + var certificatesToProcess = new X509Certificate2Collection(); - // Second from 'LocalMachine' store - certificatePath = sessionState.Path.Combine("Microsoft.PowerShell.Security\\Certificate::LocalMachine\\My", _identifier); - if (sessionState.InvokeProvider.Item.Exists(certificatePath)) + using (var storeCU = new X509Store("my", StoreLocation.CurrentUser)) { - foreach (PSObject certificateObject in sessionState.InvokeProvider.Item.Get(certificatePath)) + storeCU.Open(OpenFlags.ReadOnly); + X509Certificate2Collection storeCerts = storeCU.Certificates; + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - certificates.Add(certificateObject); + using (var storeLM = new X509Store("my", StoreLocation.LocalMachine)) + { + storeLM.Open(OpenFlags.ReadOnly); + storeCerts.AddRange(storeLM.Certificates); + } } - } - } - catch (SessionStateException) - { - // If we got an ItemNotFound / etc., then this didn't represent a valid path. - } - List certificatesToProcess = new List(); - foreach (PSObject certificateObject in certificates) - { - X509Certificate2 certificate = certificateObject.BaseObject as X509Certificate2; - if (certificate != null) - { - certificatesToProcess.Add(certificate); - } - } + certificatesToProcess.AddRange(storeCerts.Find(X509FindType.FindByThumbprint, _identifier, validOnly: false)); - ProcessResolvedCertificates(purpose, certificatesToProcess, out error); - } - - private void ResolveFromSubjectName(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) - { - Collection certificates = new Collection(); - WildcardPattern subjectNamePattern = WildcardPattern.Get(_identifier, WildcardOptions.IgnoreCase); - - try - { - // Get first from 'My' store, then 'LocalMachine' - string[] certificatePaths = new string[] { - "Microsoft.PowerShell.Security\\Certificate::CurrentUser\\My", - "Microsoft.PowerShell.Security\\Certificate::LocalMachine\\My" }; - - foreach (string certificatePath in certificatePaths) - { - foreach (PSObject certificateObject in sessionState.InvokeProvider.ChildItem.Get(certificatePath, false)) + if (certificatesToProcess.Count == 0) { - if (subjectNamePattern.IsMatch(certificateObject.Properties["Subject"].Value.ToString())) + foreach (var cert in storeCerts) { - certificates.Add(certificateObject); + if (subjectNamePattern.IsMatch(cert.Subject) || subjectNamePattern.IsMatch(cert.GetNameInfo(X509NameType.SimpleName, forIssuer: false))) + { + certificatesToProcess.Add(cert); + } } } + + ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } } catch (SessionStateException) { - // If we got an ItemNotFound / etc., then this didn't represent a valid path. - } - - List certificatesToProcess = new List(); - foreach (PSObject certificateObject in certificates) - { - X509Certificate2 certificate = certificateObject.BaseObject as X509Certificate2; - if (certificate != null) - { - certificatesToProcess.Add(certificate); - } } - - ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } - private void ProcessResolvedCertificates(ResolutionPurpose purpose, List certificatesToProcess, out ErrorRecord error) + private void ProcessResolvedCertificates(ResolutionPurpose purpose, X509Certificate2Collection certificatesToProcess, out ErrorRecord error) { error = null; HashSet processedThumbprints = new HashSet(); @@ -1418,9 +1259,14 @@ private void ProcessResolvedCertificates(ResolutionPurpose purpose, ListLONG->int ///appName: LPCWSTR->WCHAR* ///amsiContext: HAMSICONTEXT* + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiInitialize", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiInitialize( [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string appName, ref System.IntPtr amsiContext); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiUninitialize", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiUninitialize(System.IntPtr amsiContext); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION* + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiOpenSession", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiOpenSession(System.IntPtr amsiContext, ref System.IntPtr amsiSession); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION->HAMSISESSION__* + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiCloseSession", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiCloseSession(System.IntPtr amsiContext, System.IntPtr amsiSession); @@ -1778,6 +1634,7 @@ internal static extern int AmsiInitialize( ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanBuffer", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanBuffer( System.IntPtr amsiContext, System.IntPtr buffer, uint length, @@ -1789,6 +1646,7 @@ internal static extern int AmsiScanBuffer( ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanString", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanString( System.IntPtr amsiContext, [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string @string, diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index 6b027579f03..7cda5b88260 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -524,6 +524,7 @@ int NCryptOpenKey(IntPtr hProv, string strKeyName, uint dwLegacySpec, uint dwFlags); + [DllImport("ncrypt.dll", CharSet = CharSet.Unicode)] internal static extern unsafe int NCryptSetProperty(IntPtr hProv, string pszProperty, void* pbInput, int cbInput, int dwFlags); @@ -565,12 +566,16 @@ internal struct CRYPTUI_WIZ_DIGITAL_SIGN_INFO { internal DWORD dwSize; internal DWORD dwSubjectChoice; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszFileName; + internal DWORD dwSigningCertChoice; internal IntPtr pSigningCertContext; // PCCERT_CONTEXT + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszTimestampURL; + internal DWORD dwAdditionalCertChoice; internal IntPtr pSignExtInfo; // PCCRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO }; @@ -602,10 +607,13 @@ internal struct CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO { internal DWORD dwSize; internal DWORD dwAttrFlagsNotUsed; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszDescription; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszMoreInfoLocation; + [MarshalAs(UnmanagedType.LPStr)] internal string pszHashAlg; @@ -794,8 +802,10 @@ IntPtr pWinTrustData // WINTRUST_DATA* internal struct WINTRUST_FILE_INFO { internal DWORD cbStruct; // = sizeof(WINTRUST_FILE_INFO) + [MarshalAs(UnmanagedType.LPWStr)] internal string pcwszFilePath; // LPCWSTR + internal IntPtr hFileNotUsed; // optional, HANDLE to pcwszFilePath internal IntPtr pgKnownSubjectNotUsed; // optional: GUID* : fill if the // subject type is known @@ -808,7 +818,7 @@ internal struct WINTRUST_BLOB_INFO internal uint cbStruct; /// GUID->_GUID - internal GUID gSubject; + internal Guid gSubject; /// LPCWSTR->WCHAR* [MarshalAsAttribute(UnmanagedType.LPWStr)] @@ -827,23 +837,6 @@ internal struct WINTRUST_BLOB_INFO internal System.IntPtr pbMemSignedMsg; } - [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] - internal struct GUID - { - /// unsigned int - internal uint Data1; - - /// unsigned short - internal ushort Data2; - - /// unsigned short - internal ushort Data3; - - /// unsigned char[8] - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - internal byte[] Data4; - } - [ArchitectureSensitive] internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName) { @@ -864,11 +857,7 @@ internal static WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, s byte[] contentBytes = System.Text.Encoding.Unicode.GetBytes(content); // The GUID of the PowerShell SIP - bi.gSubject.Data1 = 0x603bcc1f; - bi.gSubject.Data2 = 0x4b59; - bi.gSubject.Data3 = 0x4e08; - bi.gSubject.Data4 = new byte[] { 0xb7, 0x24, 0xd2, 0xc6, 0x29, 0x7e, 0xf3, 0x51 }; - + bi.gSubject = new Guid(0x603bcc1f, 0x4b59, 0x4e08, new byte[] { 0xb7, 0x24, 0xd2, 0xc6, 0x29, 0x7e, 0xf3, 0x51 }); bi.cbStruct = (DWORD)Marshal.SizeOf(bi); bi.pcwszDisplayName = fileName; bi.cbMemObject = (uint)contentBytes.Length; @@ -1956,6 +1945,7 @@ internal struct CRYPT_ATTRIBUTE_TYPE_VALUE { [MarshalAs(UnmanagedType.LPStr)] internal string pszObjId; + internal CRYPT_ATTR_BLOB Value; } @@ -1975,8 +1965,10 @@ internal struct CRYPTCATCDF private DWORD _dwCurFilePos; private DWORD _dwLastMemberOffset; private BOOL _fEOF; + [MarshalAs(UnmanagedType.LPWStr)] private string _pwszResultDir; + private IntPtr _hCATStore; }; @@ -1984,11 +1976,14 @@ internal struct CRYPTCATCDF internal struct CRYPTCATMEMBER { internal DWORD cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszReferenceTag; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszFileName; - internal GUID gSubjectType; + + internal Guid gSubjectType; internal DWORD fdwMemberFlags; internal IntPtr pIndirectData; internal DWORD dwCertVersion; @@ -2002,8 +1997,10 @@ internal struct CRYPTCATMEMBER internal struct CRYPTCATATTRIBUTE { private DWORD _cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszReferenceTag; + private DWORD _dwAttrTypeAndAction; internal DWORD cbValue; internal System.IntPtr pbValue; @@ -2015,8 +2012,10 @@ internal struct CRYPTCATSTORE { private DWORD _cbStruct; internal DWORD dwPublicVersion; + [MarshalAs(UnmanagedType.LPWStr)] internal string pwszP7File; + private IntPtr _hProv; private DWORD _dwEncodingType; private DWORD _fdwStoreFlags; diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 901135907d3..608503b932f 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // @@ -176,6 +176,7 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl private const string AppLockerTestFileName = "__PSScriptPolicyTest_"; private const string AppLockerTestFileContents = "# PowerShell test file to determine AppLocker lockdown mode "; + private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle handle) { SaferPolicy result = SaferPolicy.Disallowed; @@ -564,6 +565,7 @@ internal class WldpNativeMethods /// pHostInformation: PWLDP_HOST_INFORMATION->_WLDP_HOST_INFORMATION* /// pdwLockdownState: PDWORD->DWORD* /// dwFlags: DWORD->unsigned int + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("wldp.dll", EntryPoint = "WldpGetLockdownPolicy")] internal static extern int WldpGetLockdownPolicy(ref WLDP_HOST_INFORMATION pHostInformation, ref uint pdwLockdownState, uint dwFlags); @@ -572,6 +574,7 @@ internal class WldpNativeMethods /// pHostInformation: PWLDP_HOST_INFORMATION->_WLDP_HOST_INFORMATION* /// ptIsApproved: PBOOL->BOOL* /// dwFlags: DWORD->unsigned int + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("wldp.dll", EntryPoint = "WldpIsClassInApprovedList")] internal static extern int WldpIsClassInApprovedList(ref Guid rclsid, ref WLDP_HOST_INFORMATION pHostInformation, ref int ptIsApproved, uint dwFlags); diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs index 27656b111c2..9e8c2585215 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -87,6 +87,7 @@ private void CreateErrorRecord() } private Collection _PSSnapInExceptions = new Collection(); + internal Collection PSSnapInExceptions { get diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index f6f8f0b6df2..7c0bf58a5cf 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -90,27 +90,27 @@ string vendorFallback { if (string.IsNullOrEmpty(name)) { - throw PSTraceSource.NewArgumentNullException("name"); + throw PSTraceSource.NewArgumentNullException(nameof(name)); } if (string.IsNullOrEmpty(applicationBase)) { - throw PSTraceSource.NewArgumentNullException("applicationBase"); + throw PSTraceSource.NewArgumentNullException(nameof(applicationBase)); } if (string.IsNullOrEmpty(assemblyName)) { - throw PSTraceSource.NewArgumentNullException("assemblyName"); + throw PSTraceSource.NewArgumentNullException(nameof(assemblyName)); } if (string.IsNullOrEmpty(moduleName)) { - throw PSTraceSource.NewArgumentNullException("moduleName"); + throw PSTraceSource.NewArgumentNullException(nameof(moduleName)); } if (psVersion == null) { - throw PSTraceSource.NewArgumentNullException("psVersion"); + throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } if (version == null) @@ -578,7 +578,7 @@ internal static Collection ReadAll(string psVersion) { if (string.IsNullOrEmpty(psVersion)) { - throw PSTraceSource.NewArgumentNullException("psVersion"); + throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } RegistryKey monadRootKey = GetMonadRootKey(); @@ -655,12 +655,12 @@ internal static PSSnapInInfo Read(string psVersion, string mshsnapinId) { if (string.IsNullOrEmpty(psVersion)) { - throw PSTraceSource.NewArgumentNullException("psVersion"); + throw PSTraceSource.NewArgumentNullException(nameof(psVersion)); } if (string.IsNullOrEmpty(mshsnapinId)) { - throw PSTraceSource.NewArgumentNullException("mshsnapinId"); + throw PSTraceSource.NewArgumentNullException(nameof(mshsnapinId)); } // PSSnapIn Reader wont service invalid mshsnapins // Monad has specific restrictions on the mshsnapinid like @@ -698,7 +698,7 @@ private static PSSnapInInfo ReadOne(RegistryKey mshSnapInRoot, string mshsnapinI if (mshsnapinKey == null) { s_mshsnapinTracer.TraceError("Error opening registry key {0}\\{1}.", mshSnapInRoot.Name, mshsnapinId); - throw PSTraceSource.NewArgumentException("mshsnapinId", MshSnapinInfo.MshSnapinDoesNotExist, mshsnapinId); + throw PSTraceSource.NewArgumentException(nameof(mshsnapinId), MshSnapinInfo.MshSnapinDoesNotExist, mshsnapinId); } string applicationBase = ReadStringValue(mshsnapinKey, RegistryStrings.MshSnapin_ApplicationBase, true); @@ -759,7 +759,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, { s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); } else { @@ -787,7 +787,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, { s_mshsnapinTracer.TraceError("Cannot get string/multi-string value for mandatory property {0} in registry key {1}", name, mshsnapinKey.Name); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotInCorrectFormatMultiString, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotInCorrectFormatMultiString, name, mshsnapinKey.Name); } else { @@ -816,19 +816,19 @@ internal static string ReadStringValue(RegistryKey mshsnapinKey, string name, bo Dbg.Assert(mshsnapinKey != null, "Caller should validate the parameter"); object value = mshsnapinKey.GetValue(name); - if (value == null && mandatory == true) + if (value == null && mandatory) { s_mshsnapinTracer.TraceError("Mandatory property {0} not specified for registry key {1}", name, mshsnapinKey.Name); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotPresent, name, mshsnapinKey.Name); } string s = value as string; - if (string.IsNullOrEmpty(s) && mandatory == true) + if (string.IsNullOrEmpty(s) && mandatory) { s_mshsnapinTracer.TraceError("Value is null or empty for mandatory property {0} in {1}", name, mshsnapinKey.Name); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.MandatoryValueNotInCorrectFormat, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.MandatoryValueNotInCorrectFormat, name, mshsnapinKey.Name); } s_mshsnapinTracer.WriteLine("Successfully read value {0} for property {1} from {2}", @@ -855,22 +855,22 @@ internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, catch (ArgumentOutOfRangeException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (ArgumentException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (OverflowException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } catch (FormatException) { s_mshsnapinTracer.TraceError("Cannot convert value {0} to version format", temp); - throw PSTraceSource.NewArgumentException("name", MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); + throw PSTraceSource.NewArgumentException(nameof(name), MshSnapinInfo.VersionValueInCorrect, name, mshsnapinKey.Name); } s_mshsnapinTracer.WriteLine("Successfully converted string {0} to version format.", v); @@ -1192,7 +1192,7 @@ internal static RegistryKey versionRoot = rootKey.OpenSubKey(versionKey); if (versionRoot == null) { - throw PSTraceSource.NewArgumentException("psVersion", MshSnapinInfo.SpecifiedVersionNotFound, versionKey); + throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.SpecifiedVersionNotFound, versionKey); } return versionRoot; @@ -1219,7 +1219,7 @@ private static RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); if (mshsnapinRoot == null) { - throw PSTraceSource.NewArgumentException("psVersion", MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); + throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } return mshsnapinRoot; @@ -1246,7 +1246,7 @@ internal static RegistryKey mshsnapinRoot = versionRootKey.OpenSubKey(RegistryStrings.MshSnapinKey); if (mshsnapinRoot == null) { - throw PSTraceSource.NewArgumentException("psVersion", MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); + throw PSTraceSource.NewArgumentException(nameof(psVersion), MshSnapinInfo.NoMshSnapinPresentForVersion, psVersion); } RegistryKey mshsnapinKey = mshsnapinRoot.OpenSubKey(mshSnapInName); diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index b75c50bcbb9..9ee9588be65 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Reflection; @@ -192,7 +192,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw PSTraceSource.NewArgumentNullException("info"); + throw PSTraceSource.NewArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs b/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs index 1e10b2e4eb7..eecde27926c 100644 --- a/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs +++ b/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Internal diff --git a/src/System.Management.Automation/utils/BackgroundDispatcher.cs b/src/System.Management.Automation/utils/BackgroundDispatcher.cs index 6b28170ffad..583eecfa836 100644 --- a/src/System.Management.Automation/utils/BackgroundDispatcher.cs +++ b/src/System.Management.Automation/utils/BackgroundDispatcher.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index db0f8f9f1b2..587ce283578 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -58,9 +58,36 @@ internal static IEnumerable GetAssemblies(TypeResolutionState typeReso /// internal static IEnumerable GetAssemblies(string namespaceQualifiedTypeName = null) { - return PSAssemblyLoadContext.GetAssembly(namespaceQualifiedTypeName) ?? - AssemblyLoadContext.Default.Assemblies.Where(a => - !a.FullName.StartsWith(TypeDefiner.DynamicClassAssemblyFullNamePrefix, StringComparison.Ordinal)); + return PSAssemblyLoadContext.GetAssembly(namespaceQualifiedTypeName) ?? GetPSVisibleAssemblies(); + } + + /// + /// Return assemblies from the default load context and the 'individual' load contexts. + /// The 'individual' load contexts are the ones holding assemblies loaded via 'Assembly.Load(byte[])' and 'Assembly.LoadFile'. + /// Assemblies loaded in any custom load contexts are not consider visible to PowerShell to avoid type identity issues. + /// + private static IEnumerable GetPSVisibleAssemblies() + { + const string IndividualAssemblyLoadContext = "System.Runtime.Loader.IndividualAssemblyLoadContext"; + + foreach (Assembly assembly in AssemblyLoadContext.Default.Assemblies) + { + if (!assembly.FullName.StartsWith(TypeDefiner.DynamicClassAssemblyFullNamePrefix, StringComparison.Ordinal)) + { + yield return assembly; + } + } + + foreach (AssemblyLoadContext context in AssemblyLoadContext.All) + { + if (IndividualAssemblyLoadContext.Equals(context.GetType().FullName, StringComparison.Ordinal)) + { + foreach (Assembly assembly in context.Assemblies) + { + yield return assembly; + } + } + } } /// @@ -204,7 +231,7 @@ private static SecurityZone MapSecurityZone(string filePath) // has 'dot' in it, the file will be treated as in Internet security zone. Otherwise, it's // in Intranet security zone. string hostName = uri.Host; - return hostName.IndexOf('.') == -1 ? SecurityZone.Intranet : SecurityZone.Internet; + return hostName.Contains('.') ? SecurityZone.Intranet : SecurityZone.Internet; } string root = Path.GetPathRoot(filePath); diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index 39e22c79ab1..c7dc2cb2587 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -50,7 +50,7 @@ internal CommandNotFoundException( /// /// Constructs a CommandNotFoundException. /// - public CommandNotFoundException() : base() {; } + public CommandNotFoundException() : base() { } /// /// Constructs a CommandNotFoundException. @@ -58,7 +58,7 @@ internal CommandNotFoundException( /// /// The message used in the exception. /// - public CommandNotFoundException(string message) : base(message) {; } + public CommandNotFoundException(string message) : base(message) { } /// /// Constructs a CommandNotFoundException. @@ -69,7 +69,7 @@ internal CommandNotFoundException( /// /// An exception that led to this exception. /// - public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) {; } + public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) { } #region Serialization /// @@ -87,7 +87,7 @@ protected CommandNotFoundException(SerializationInfo info, { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } _commandName = info.GetString("CommandName"); @@ -107,7 +107,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -339,7 +339,7 @@ internal ScriptRequiresException( /// /// Constructs an PSVersionNotCompatibleException. /// - public ScriptRequiresException() : base() {; } + public ScriptRequiresException() : base() { } /// /// Constructs an PSVersionNotCompatibleException. @@ -347,7 +347,7 @@ internal ScriptRequiresException( /// /// The message used in the exception. /// - public ScriptRequiresException(string message) : base(message) {; } + public ScriptRequiresException(string message) : base(message) { } /// /// Constructs an PSVersionNotCompatibleException. @@ -358,7 +358,7 @@ internal ScriptRequiresException( /// /// The exception that led to this exception. /// - public ScriptRequiresException(string message, Exception innerException) : base(message, innerException) {; } + public ScriptRequiresException(string message, Exception innerException) : base(message, innerException) { } #region Serialization /// @@ -394,7 +394,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -470,7 +470,7 @@ private static string BuildMessage( StringBuilder sb = new StringBuilder(); if (missingItems == null) { - throw PSTraceSource.NewArgumentNullException("missingItems"); + throw PSTraceSource.NewArgumentNullException(nameof(missingItems)); } foreach (string missingItem in missingItems) diff --git a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs index d0ee48167f6..4aebe05af59 100644 --- a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs +++ b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; diff --git a/src/System.Management.Automation/utils/CoreProviderCmdlets.cs b/src/System.Management.Automation/utils/CoreProviderCmdlets.cs index 9a544dc5871..c91c3ce69fb 100644 --- a/src/System.Management.Automation/utils/CoreProviderCmdlets.cs +++ b/src/System.Management.Automation/utils/CoreProviderCmdlets.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index 55706f0d178..f860bdd4b15 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -1,441 +1,267 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; using System.Management.Automation.Remoting; -using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; +using System.Security.Cryptography; using System.Text; using System.Threading; -using Microsoft.Win32.SafeHandles; - using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Internal { /// - /// Class that encapsulates native crypto provider handles and provides a - /// mechanism for resources released by them. + /// This class provides the converters for all Native CAPI key blob formats. /// - // [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)] - // [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] - internal class PSSafeCryptProvHandle : SafeHandleZeroOrMinusOneIsInvalid + internal static class PSCryptoNativeConverter { + #region Constants + /// - /// This safehandle instance "owns" the handle, hence base(true) - /// is being called. When safehandle is no longer in use it will - /// call this class's ReleaseHandle method which will release - /// the resources. + /// The blob version is fixed. /// - internal PSSafeCryptProvHandle() : base(true) { } + public const uint CUR_BLOB_VERSION = 0x00000002; /// - /// Release the crypto handle held by this instance. + /// RSA Key. /// - /// True on success, false otherwise. - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - protected override bool ReleaseHandle() - { - return PSCryptoNativeUtils.CryptReleaseContext(handle, 0); - } - } + public const uint CALG_RSA_KEYX = 0x000000a4; - /// - /// Class the encapsulates native crypto key handles and provides a - /// mechanism to release resources used by it. - /// - // [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)] - // [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)] - internal class PSSafeCryptKey : SafeHandleZeroOrMinusOneIsInvalid - { /// - /// This safehandle instance "owns" the handle, hence base(true) - /// is being called. When safehandle is no longer in use it will - /// call this class's ReleaseHandle method which will release the - /// resources. + /// AES 256 symmetric key. /// - internal PSSafeCryptKey() : base(true) { } + public const uint CALG_AES_256 = 0x00000010; /// - /// Release the crypto handle held by this instance. + /// Option for exporting public key blob. /// - /// True on success, false otherwise. - [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] - protected override bool ReleaseHandle() - { - return PSCryptoNativeUtils.CryptDestroyKey(handle); - } + public const uint PUBLICKEYBLOB = 0x00000006; + + /// + /// PUBLICKEYBLOB header length. + /// + public const int PUBLICKEYBLOB_HEADER_LEN = 20; /// - /// Equivalent of IntPtr.Zero for the safe crypt key. + /// Option for exporting a session key. /// - internal static PSSafeCryptKey Zero { get; } = new PSSafeCryptKey(); - } + public const uint SIMPLEBLOB = 0x00000001; + + /// + /// SIMPLEBLOB header length. + /// + public const int SIMPLEBLOB_HEADER_LEN = 12; + + #endregion Constants - /// - /// This class provides the wrapper for all Native CAPI functions. - /// - internal class PSCryptoNativeUtils - { #region Functions -#if UNIX - /// Return Type: BOOL->int - ///hProv: HCRYPTPROV->ULONG_PTR->unsigned int - ///Algid: ALG_ID->unsigned int - ///dwFlags: DWORD->unsigned int - ///phKey: HCRYPTKEY* - public static bool CryptGenKey( - PSSafeCryptProvHandle hProv, - uint Algid, - uint dwFlags, - ref PSSafeCryptKey phKey) + private static int ToInt32LE(byte[] bytes, int offset) { - throw new PSCryptoException(); + return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1 ] << 8) | bytes[offset]; } - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - public static bool CryptDestroyKey(IntPtr hKey) + private static uint ToUInt32LE(byte[] bytes, int offset) { - throw new PSCryptoException(); + return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]); } - /// Return Type: BOOL->int - ///phProv: HCRYPTPROV* - ///szContainer: LPCWSTR->WCHAR* - ///szProvider: LPCWSTR->WCHAR* - ///dwProvType: DWORD->unsigned int - ///dwFlags: DWORD->unsigned int - public static bool CryptAcquireContext(ref PSSafeCryptProvHandle phProv, - [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szContainer, - [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szProvider, - uint dwProvType, - uint dwFlags) + private static byte[] GetBytesLE(int val) { - throw new PSCryptoException(); + return new [] { + (byte)(val & 0xff), + (byte)((val >> 8) & 0xff), + (byte)((val >> 16) & 0xff), + (byte)((val >> 24) & 0xff) + }; } - /// Return Type: BOOL->int - ///hProv: HCRYPTPROV->ULONG_PTR->unsigned int - ///dwFlags: DWORD->unsigned int - public static bool CryptReleaseContext(IntPtr hProv, uint dwFlags) + private static byte[] CreateReverseByteArray(byte[] data) { - throw new PSCryptoException(); + byte[] reverseData = new byte[data.Length]; + Array.Copy(data, reverseData, data.Length); + Array.Reverse(reverseData); + return reverseData; } - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///hHash: HCRYPTHASH->ULONG_PTR->unsigned int - ///Final: BOOL->int - ///dwFlags: DWORD->unsigned int - ///pbData: BYTE* - ///pdwDataLen: DWORD* - ///dwBufLen: DWORD->unsigned int - public static bool CryptEncrypt(PSSafeCryptKey hKey, - IntPtr hHash, - [MarshalAsAttribute(UnmanagedType.Bool)] bool Final, - uint dwFlags, - byte[] pbData, - ref int pdwDataLen, - int dwBufLen) + internal static RSA FromCapiPublicKeyBlob(byte[] blob) { - throw new PSCryptoException(); + return FromCapiPublicKeyBlob(blob, 0); } - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///hHash: HCRYPTHASH->ULONG_PTR->unsigned int - ///Final: BOOL->int - ///dwFlags: DWORD->unsigned int - ///pbData: BYTE* - ///pdwDataLen: DWORD* - public static bool CryptDecrypt(PSSafeCryptKey hKey, - IntPtr hHash, - [MarshalAsAttribute(UnmanagedType.Bool)] bool Final, - uint dwFlags, - byte[] pbData, - ref int pdwDataLen) + private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { - throw new PSCryptoException(); - } + if (blob == null) + { + throw new ArgumentNullException(nameof(blob)); + } - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///hExpKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///dwBlobType: DWORD->unsigned int - ///dwFlags: DWORD->unsigned int - ///pbData: BYTE* - ///pdwDataLen: DWORD* - public static bool CryptExportKey(PSSafeCryptKey hKey, - PSSafeCryptKey hExpKey, - uint dwBlobType, - uint dwFlags, - byte[] pbData, - ref uint pdwDataLen) - { - throw new PSCryptoException(); - } + if (offset > blob.Length) + { + throw new ArgumentException(SecuritySupportStrings.InvalidOffset); + } - /// Return Type: BOOL->int - ///hProv: HCRYPTPROV->ULONG_PTR->unsigned int - ///pbData: BYTE* - ///dwDataLen: DWORD->unsigned int - ///hPubKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///dwFlags: DWORD->unsigned int - ///phKey: HCRYPTKEY* - public static bool CryptImportKey(PSSafeCryptProvHandle hProv, - byte[] pbData, - int dwDataLen, - PSSafeCryptKey hPubKey, - uint dwFlags, - ref PSSafeCryptKey phKey) - { - throw new PSCryptoException(); - } + var rsap = GetParametersFromCapiPublicKeyBlob(blob, offset); - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///pdwReserved: DWORD* - ///dwFlags: DWORD->unsigned int - ///phKey: HCRYPTKEY* - public static bool CryptDuplicateKey(PSSafeCryptKey hKey, - ref uint pdwReserved, - uint dwFlags, - ref PSSafeCryptKey phKey) - { - throw new PSCryptoException(); + try + { + RSA rsa = RSA.Create(); + rsa.ImportParameters(rsap); + return rsa; + } + catch (Exception ex) + { + throw new CryptographicException(SecuritySupportStrings.CannotImportPublicKey, ex); + } } - /// Return Type: DWORD->unsigned int - public static uint GetLastError() + private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int offset) { - throw new PSCryptoException(); - } -#else - - /// Return Type: BOOL->int - ///hProv: HCRYPTPROV->ULONG_PTR->unsigned int - ///Algid: ALG_ID->unsigned int - ///dwFlags: DWORD->unsigned int - ///phKey: HCRYPTKEY* - [DllImportAttribute(PinvokeDllNames.CryptGenKeyDllName, EntryPoint = "CryptGenKey")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptGenKey(PSSafeCryptProvHandle hProv, - uint Algid, - uint dwFlags, - ref PSSafeCryptKey phKey); - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - [DllImportAttribute(PinvokeDllNames.CryptDestroyKeyDllName, EntryPoint = "CryptDestroyKey")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptDestroyKey(IntPtr hKey); - - /// Return Type: BOOL->int - ///phProv: HCRYPTPROV* - ///szContainer: LPCWSTR->WCHAR* - ///szProvider: LPCWSTR->WCHAR* - ///dwProvType: DWORD->unsigned int - ///dwFlags: DWORD->unsigned int - [DllImportAttribute(PinvokeDllNames.CryptAcquireContextDllName, EntryPoint = "CryptAcquireContext")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptAcquireContext(ref PSSafeCryptProvHandle phProv, - [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szContainer, - [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szProvider, - uint dwProvType, - uint dwFlags); - - /// Return Type: BOOL->int - ///hProv: HCRYPTPROV->ULONG_PTR->unsigned int - ///dwFlags: DWORD->unsigned int - [DllImportAttribute(PinvokeDllNames.CryptReleaseContextDllName, EntryPoint = "CryptReleaseContext")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptReleaseContext(IntPtr hProv, uint dwFlags); - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///hHash: HCRYPTHASH->ULONG_PTR->unsigned int - ///Final: BOOL->int - ///dwFlags: DWORD->unsigned int - ///pbData: BYTE* - ///pdwDataLen: DWORD* - ///dwBufLen: DWORD->unsigned int - [DllImportAttribute(PinvokeDllNames.CryptEncryptDllName, EntryPoint = "CryptEncrypt")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptEncrypt(PSSafeCryptKey hKey, - IntPtr hHash, - [MarshalAsAttribute(UnmanagedType.Bool)] bool Final, - uint dwFlags, - byte[] pbData, - ref int pdwDataLen, - int dwBufLen); - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///hHash: HCRYPTHASH->ULONG_PTR->unsigned int - ///Final: BOOL->int - ///dwFlags: DWORD->unsigned int - ///pbData: BYTE* - ///pdwDataLen: DWORD* - [DllImportAttribute(PinvokeDllNames.CryptDecryptDllName, EntryPoint = "CryptDecrypt")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptDecrypt(PSSafeCryptKey hKey, - IntPtr hHash, - [MarshalAsAttribute(UnmanagedType.Bool)] bool Final, - uint dwFlags, - byte[] pbData, - ref int pdwDataLen); - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///hExpKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///dwBlobType: DWORD->unsigned int - ///dwFlags: DWORD->unsigned int - ///pbData: BYTE* - ///pdwDataLen: DWORD* - [DllImportAttribute(PinvokeDllNames.CryptExportKeyDllName, EntryPoint = "CryptExportKey")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptExportKey(PSSafeCryptKey hKey, - PSSafeCryptKey hExpKey, - uint dwBlobType, - uint dwFlags, - byte[] pbData, - ref uint pdwDataLen); - - /// Return Type: BOOL->int - ///hProv: HCRYPTPROV->ULONG_PTR->unsigned int - ///pbData: BYTE* - ///dwDataLen: DWORD->unsigned int - ///hPubKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///dwFlags: DWORD->unsigned int - ///phKey: HCRYPTKEY* - [DllImportAttribute(PinvokeDllNames.CryptImportKeyDllName, EntryPoint = "CryptImportKey")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptImportKey(PSSafeCryptProvHandle hProv, - byte[] pbData, - int dwDataLen, - PSSafeCryptKey hPubKey, - uint dwFlags, - ref PSSafeCryptKey phKey); - - /// Return Type: BOOL->int - ///hKey: HCRYPTKEY->ULONG_PTR->unsigned int - ///pdwReserved: DWORD* - ///dwFlags: DWORD->unsigned int - ///phKey: HCRYPTKEY* - [DllImportAttribute(PinvokeDllNames.CryptDuplicateKeyDllName, EntryPoint = "CryptDuplicateKey")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - public static extern bool CryptDuplicateKey(PSSafeCryptKey hKey, - ref uint pdwReserved, - uint dwFlags, - ref PSSafeCryptKey phKey); - - /// Return Type: DWORD->unsigned int - [DllImportAttribute(PinvokeDllNames.GetLastErrorDllName, EntryPoint = "GetLastError")] - public static extern uint GetLastError(); -#endif + if (blob == null) + { + throw new ArgumentNullException(nameof(blob)); + } - #endregion Functions + if (offset > blob.Length) + { + throw new ArgumentException(SecuritySupportStrings.InvalidOffset); + } - #region Constants + if (blob.Length < PUBLICKEYBLOB_HEADER_LEN) + { + throw new ArgumentException(SecuritySupportStrings.InvalidPublicKey); + } - /// - /// Do not use persisted private key. - /// - public const uint CRYPT_VERIFYCONTEXT = 0xF0000000; + try + { + if ((blob[offset] != PUBLICKEYBLOB) || // PUBLICKEYBLOB (0x06) + (blob[offset + 1] != CUR_BLOB_VERSION) || // Version (0x02) + (blob[offset + 2] != 0x00) || // Reserved (word) + (blob[offset + 3] != 0x00) || + (ToUInt32LE(blob, offset + 8) != 0x31415352)) // DWORD magic = RSA1 + { + throw new CryptographicException(SecuritySupportStrings.InvalidPublicKey); + } - /// - /// Mark the key for export. - /// - public const uint CRYPT_EXPORTABLE = 0x00000001; + // DWORD bitlen + int bitLen = ToInt32LE(blob, offset + 12); - /// - /// Automatically assign a salt value when creating a - /// session key. - /// - public const int CRYPT_CREATE_SALT = 4; + // DWORD public exponent + RSAParameters rsap = new RSAParameters(); + rsap.Exponent = new byte[3]; + rsap.Exponent[0] = blob[offset + 18]; + rsap.Exponent[1] = blob[offset + 17]; + rsap.Exponent[2] = blob[offset + 16]; - /// - /// RSA Provider. - /// - public const int PROV_RSA_FULL = 1; + int pos = offset + 20; + int byteLen = (bitLen >> 3); + rsap.Modulus = new byte[byteLen]; + Buffer.BlockCopy(blob, pos, rsap.Modulus, 0, byteLen); + Array.Reverse(rsap.Modulus); - /// - /// RSA Provider that supports AES - /// encryption. - /// - public const int PROV_RSA_AES = 24; + return rsap; + } + catch (Exception ex) + { + throw new CryptographicException(SecuritySupportStrings.InvalidPublicKey, ex); + } + } - /// - /// Public key to be used for encryption. - /// - public const int AT_KEYEXCHANGE = 1; + internal static byte[] ToCapiPublicKeyBlob(RSA rsa) + { + if (rsa == null) + { + throw new ArgumentNullException(nameof(rsa)); + } - /// - /// RSA Key. - /// - public const int CALG_RSA_KEYX = - (PSCryptoNativeUtils.ALG_CLASS_KEY_EXCHANGE | - (PSCryptoNativeUtils.ALG_TYPE_RSA | PSCryptoNativeUtils.ALG_SID_RSA_ANY)); + RSAParameters p = rsa.ExportParameters(false); + int keyLength = p.Modulus.Length; // in bytes + byte[] blob = new byte[PUBLICKEYBLOB_HEADER_LEN + keyLength]; - /// - /// Create a key for encryption. - /// - public const int ALG_CLASS_KEY_EXCHANGE = (5) << (13); + blob[0] = (byte)PUBLICKEYBLOB; // Type - PUBLICKEYBLOB (0x06) + blob[1] = (byte)CUR_BLOB_VERSION; // Version - Always CUR_BLOB_VERSION (0x02) + // [2], [3] // RESERVED - Always 0 + blob[5] = (byte)CALG_RSA_KEYX; // ALGID - Always 00 a4 00 00 (for CALG_RSA_KEYX) + blob[8] = 0x52; // Magic - RSA1 (ASCII in hex) + blob[9] = 0x53; + blob[10] = 0x41; + blob[11] = 0x31; - /// - /// Create a RSA key pair. - /// - public const int ALG_TYPE_RSA = (2) << (9); + byte[] bitlen = GetBytesLE(keyLength << 3); + blob[12] = bitlen[0]; // bitlen + blob[13] = bitlen[1]; + blob[14] = bitlen[2]; + blob[15] = bitlen[3]; - /// - /// - public const int ALG_SID_RSA_ANY = 0; + // public exponent (DWORD) + int pos = 16; + int n = p.Exponent.Length; - /// - /// Option for exporting public key blob. - /// - public const int PUBLICKEYBLOB = 6; + Dbg.Assert(n <= 4, "RSA exponent byte length cannot exceed allocated segment"); - /// - /// Option for exporting a session key. - /// - public const int SIMPLEBLOB = 1; + while (n > 0) + { + blob[pos++] = p.Exponent[--n]; + } - /// - /// AES 256 symmetric key. - /// - public const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_256); + // modulus + pos = 20; + byte[] key = p.Modulus; + Array.Reverse(key); + Buffer.BlockCopy(key, 0, blob, pos, keyLength); - /// - /// ALG_CLASS_DATA_ENCRYPT. - /// - public const int ALG_CLASS_DATA_ENCRYPT = (3) << (13); + return blob; + } - /// - /// ALG_TYPE_BLOCK. - /// - public const int ALG_TYPE_BLOCK = (3) << (9); + internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) + { + if (blob == null) + { + throw new ArgumentNullException(nameof(blob)); + } - /// - /// ALG_SID_AES_256 -> 16. - /// - public const int ALG_SID_AES_256 = 16; + if (blob.Length < SIMPLEBLOB_HEADER_LEN) + { + throw new ArgumentException(SecuritySupportStrings.InvalidSessionKey); + } - /// CALG_AES_128 -> (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_128) - public const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT - | (ALG_TYPE_BLOCK | ALG_SID_AES_128)); + // just ignore the header of the capi blob and go straight for the key + return CreateReverseByteArray(blob.Skip(SIMPLEBLOB_HEADER_LEN).ToArray()); + } - /// ALG_SID_AES_128 -> 14 - public const int ALG_SID_AES_128 = 14; + internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) + { + if (encryptedKey == null) + { + throw new ArgumentNullException(nameof(encryptedKey)); + } - #endregion Constants + // formulate the PUBLICKEYSTRUCT + byte[] blob = new byte[SIMPLEBLOB_HEADER_LEN + encryptedKey.Length]; + + blob[0] = (byte)SIMPLEBLOB; // Type - SIMPLEBLOB (0x01) + blob[1] = (byte)CUR_BLOB_VERSION; // Version - Always CUR_BLOB_VERSION (0x02) + // [2], [3] // RESERVED - Always 0 + blob[4] = (byte)CALG_AES_256; // AES-256 algo id (0x10) + blob[5] = 0x66; // ?? + // [6], [7], [8] // 0x00 + blob[9] = (byte)CALG_RSA_KEYX; // 0xa4 + // [10], [11] // 0x00 + + // create a reversed copy and add the encrypted key + byte[] reversedKey = CreateReverseByteArray(encryptedKey); + Buffer.BlockCopy(reversedKey, 0, blob, SIMPLEBLOB_HEADER_LEN, reversedKey.Length); + + return blob; + } + + #endregion Functions } /// @@ -540,32 +366,26 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont } /// - /// One of the issues with RSACryptoServiceProvider is that it never uses CRYPT_VERIFYCONTEXT - /// to create ephemeral keys. This class is a facade written on top of native CAPI APIs - /// to create ephemeral keys. + /// A reverse compatible implementation of session key exchange. This supports the CAPI + /// keyblob formats but uses dotnet std abstract AES and RSA classes for all crypto operations. /// internal class PSRSACryptoServiceProvider : IDisposable { #region Private Members - private PSSafeCryptProvHandle _hProv; - // handle to the provider - private bool _canEncrypt = false; // this flag indicates that this class has a key - // imported from the remote end and so can be - // used for encryption - private PSSafeCryptKey _hRSAKey; - // handle to the RSA key with which the session - // key is exchange. This can either be generated - // or imported - private PSSafeCryptKey _hSessionKey; - // handle to the session key. This can either - // be generated or imported - private bool _sessionKeyGenerated = false; + // handle session key encryption/decryption + private RSA _rsa; + + // handle to the AES provider object (houses session key and iv) + private readonly Aes _aes; + + // this flag indicates that this class has a key imported from the + // remote end and so can be used for encryption + private bool _canEncrypt; + // bool indicating if session key was generated before + private bool _sessionKeyGenerated = false; - private static PSSafeCryptProvHandle s_hStaticProv; - private static PSSafeCryptKey s_hStaticRSAKey; - private static bool s_keyPairGenerated = false; private static object s_syncObject = new object(); #endregion Private Members @@ -581,22 +401,11 @@ private PSRSACryptoServiceProvider(bool serverMode) { if (serverMode) { - _hProv = new PSSafeCryptProvHandle(); - - // We need PROV_RSA_AES to support AES-256 symmetric key - // encryption. PROV_RSA_FULL supports only RC2 and RC4 - bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref _hProv, - null, - null, - PSCryptoNativeUtils.PROV_RSA_AES, - PSCryptoNativeUtils.CRYPT_VERIFYCONTEXT); - - CheckStatus(ret); - - _hRSAKey = new PSSafeCryptKey(); + GenerateKeyPair(); } - _hSessionKey = new PSSafeCryptKey(); + _aes = Aes.Create(); + _aes.IV = new byte[16]; // iv should be 0 } #endregion Constructors @@ -604,37 +413,16 @@ private PSRSACryptoServiceProvider(bool serverMode) #region Internal Methods /// - /// Get the public key as a base64 encoded string. + /// Get the public key, in CAPI-compatible form, as a base64 encoded string. /// /// Public key as base64 encoded string. internal string GetPublicKeyAsBase64EncodedString() { - uint publicKeyLength = 0; - - // Get key length first - bool ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey, - PSSafeCryptKey.Zero, - PSCryptoNativeUtils.PUBLICKEYBLOB, - 0, - null, - ref publicKeyLength); - CheckStatus(ret); - - // Create enough buffer and get the actual data - byte[] publicKey = new byte[publicKeyLength]; - ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey, - PSSafeCryptKey.Zero, - PSCryptoNativeUtils.PUBLICKEYBLOB, - 0, - publicKey, - ref publicKeyLength); - CheckStatus(ret); - - // Convert the public key into base64 encoding so that it can be exported to - // the other end. - string result = Convert.ToBase64String(publicKey); - - return result; + Dbg.Assert(_rsa != null, "No public key available."); + + byte[] capiPublicKeyBlob = PSCryptoNativeConverter.ToCapiPublicKeyBlob(_rsa); + + return Convert.ToBase64String(capiPublicKeyBlob); } /// @@ -649,13 +437,9 @@ internal void GenerateSessionKey() { if (!_sessionKeyGenerated) { - bool ret = PSCryptoNativeUtils.CryptGenKey(_hProv, - PSCryptoNativeUtils.CALG_AES_256, - 0x01000000 | // key length = 256 bits - PSCryptoNativeUtils.CRYPT_EXPORTABLE | - PSCryptoNativeUtils.CRYPT_CREATE_SALT, - ref _hSessionKey); - CheckStatus(ret); + // Aes object gens key automatically on construction, so this is somewhat redundant, + // but at least the actionable key will not be in-memory until it's requested fwiw. + _aes.GenerateKey(); _sessionKeyGenerated = true; _canEncrypt = true; // we can encrypt and decrypt once session key is available } @@ -672,35 +456,17 @@ internal void GenerateSessionKey() /// and encoded as a base 64 string. internal string SafeExportSessionKey() { + Dbg.Assert(_rsa != null, "No public key available."); + // generate one if not already done. GenerateSessionKey(); - uint length = 0; - - // get key length first - bool ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey, - _hRSAKey, - PSCryptoNativeUtils.SIMPLEBLOB, - 0, - null, - ref length); - CheckStatus(ret); - - // allocate buffer and export the key - byte[] sessionkey = new byte[length]; - ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey, - _hRSAKey, - PSCryptoNativeUtils.SIMPLEBLOB, - 0, - sessionkey, - ref length); - CheckStatus(ret); - - // now we can encrypt as we have the session key - _canEncrypt = true; + // encrypt it + byte[] encryptedKey = _rsa.Encrypt(_aes.Key, RSAEncryptionPadding.Pkcs1); - // convert the key to base64 before exporting - return Convert.ToBase64String(sessionkey); + // convert the key to capi simpleblob format before exporting + byte[] simpleKeyBlob = PSCryptoNativeConverter.ToCapiSimpleKeyBlob(encryptedKey); + return Convert.ToBase64String(simpleKeyBlob); } /// @@ -712,16 +478,8 @@ internal void ImportPublicKeyFromBase64EncodedString(string publicKey) { Dbg.Assert(!string.IsNullOrEmpty(publicKey), "key cannot be null or empty"); - byte[] convertedBase64 = Convert.FromBase64String(publicKey); - - bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv, - convertedBase64, - convertedBase64.Length, - PSSafeCryptKey.Zero, - 0, - ref _hRSAKey); - - CheckStatus(ret); + byte[] publicKeyBlob = Convert.FromBase64String(publicKey); + _rsa = PSCryptoNativeConverter.FromCapiPublicKeyBlob(publicKeyBlob); } /// @@ -734,15 +492,10 @@ internal void ImportSessionKeyFromBase64EncodedString(string sessionKey) { Dbg.Assert(!string.IsNullOrEmpty(sessionKey), "key cannot be null or empty"); - byte[] convertedBase64 = Convert.FromBase64String(sessionKey); + byte[] sessionKeyBlob = Convert.FromBase64String(sessionKey); + byte[] rsaEncryptedKey = PSCryptoNativeConverter.FromCapiSimpleKeyBlob(sessionKeyBlob); - bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv, - convertedBase64, - convertedBase64.Length, - _hRSAKey, - 0, - ref _hSessionKey); - CheckStatus(ret); + _aes.Key = _rsa.Decrypt(rsaEncryptedKey, RSAEncryptionPadding.Pkcs1); // now we have imported the key and will be able to // encrypt using the session key @@ -756,58 +509,19 @@ internal void ImportSessionKeyFromBase64EncodedString(string sessionKey) /// Encrypted byte array. internal byte[] EncryptWithSessionKey(byte[] data) { - // first make a copy of the original data.This is needed - // as CryptEncrypt uses the same buffer to write the encrypted data - // into. Dbg.Assert(_canEncrypt, "Remote key has not been imported to encrypt"); - byte[] encryptedData = new byte[data.Length]; - Array.Copy(data, 0, encryptedData, 0, data.Length); - - int dataLength = encryptedData.Length; - - // encryption always happens using the session key - bool ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey, - IntPtr.Zero, - true, - 0, - encryptedData, - ref dataLength, - data.Length); - - // if encryption failed, then dataLength will contain the length - // of buffer needed to store the encrypted contents. Recreate - // the buffer - if (false == ret) + using (ICryptoTransform encryptor = _aes.CreateEncryptor()) + using (MemoryStream targetStream = new MemoryStream()) + using (MemoryStream sourceStream = new MemoryStream(data)) { - // before reallocating the encryptedData buffer, - // zero out its contents - for (int i = 0; i < encryptedData.Length; i++) + using (CryptoStream cryptoStream = new CryptoStream(targetStream, encryptor, CryptoStreamMode.Write)) { - encryptedData[i] = 0; + sourceStream.CopyTo(cryptoStream); } - encryptedData = new byte[dataLength]; - - Array.Copy(data, 0, encryptedData, 0, data.Length); - dataLength = data.Length; - ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey, - IntPtr.Zero, - true, - 0, - encryptedData, - ref dataLength, - encryptedData.Length); - - CheckStatus(ret); + return targetStream.ToArray(); } - - // make sure we copy only appropriate data - // dataLength will contain the length of the encrypted - // data buffer - byte[] result = new byte[dataLength]; - Array.Copy(encryptedData, 0, result, 0, dataLength); - return result; } /// @@ -817,53 +531,17 @@ internal byte[] EncryptWithSessionKey(byte[] data) /// Decrypted buffer. internal byte[] DecryptWithSessionKey(byte[] data) { - // first make a copy of the original data.This is needed - // as CryptDecrypt uses the same buffer to write the decrypted data - // into. - byte[] decryptedData = new byte[data.Length]; - - Array.Copy(data, 0, decryptedData, 0, data.Length); - - int dataLength = decryptedData.Length; - - bool ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey, - IntPtr.Zero, - true, - 0, - decryptedData, - ref dataLength); - - // if decryption failed, then dataLength will contain the length - // of buffer needed to store the decrypted contents. Recreate - // the buffer - if (false == ret) + using (ICryptoTransform decryptor = _aes.CreateDecryptor()) + using (MemoryStream sourceStream = new MemoryStream(data)) + using (MemoryStream targetStream = new MemoryStream()) { - decryptedData = new byte[dataLength]; - - Array.Copy(data, 0, decryptedData, 0, data.Length); - ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey, - IntPtr.Zero, - true, - 0, - decryptedData, - ref dataLength); - CheckStatus(ret); - } - - // make sure we copy only appropriate data - // dataLength will contain the length of the encrypted - // data buffer - byte[] result = new byte[dataLength]; - - Array.Copy(decryptedData, 0, result, 0, dataLength); + using (CryptoStream csDecrypt = new CryptoStream(sourceStream, decryptor, CryptoStreamMode.Read)) + { + csDecrypt.CopyTo(targetStream); + } - // zero out the decryptedData buffer - for (int i = 0; i < decryptedData.Length; i++) - { - decryptedData[i] = 0; + return targetStream.ToArray(); } - - return result; } /// @@ -872,39 +550,8 @@ internal byte[] DecryptWithSessionKey(byte[] data) /// internal void GenerateKeyPair() { - if (!s_keyPairGenerated) - { - lock (s_syncObject) - { - if (!s_keyPairGenerated) - { - s_hStaticProv = new PSSafeCryptProvHandle(); - // We need PROV_RSA_AES to support AES-256 symmetric key - // encryption. PROV_RSA_FULL supports only RC2 and RC4 - bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref s_hStaticProv, - null, - null, - PSCryptoNativeUtils.PROV_RSA_AES, - PSCryptoNativeUtils.CRYPT_VERIFYCONTEXT); - - CheckStatus(ret); - - s_hStaticRSAKey = new PSSafeCryptKey(); - ret = PSCryptoNativeUtils.CryptGenKey(s_hStaticProv, - PSCryptoNativeUtils.AT_KEYEXCHANGE, - 0x08000000 | PSCryptoNativeUtils.CRYPT_EXPORTABLE, // key length -> 2048 - ref s_hStaticRSAKey); - - CheckStatus(ret); - - // key needs to be generated once - s_keyPairGenerated = true; - } - } - } - - _hProv = s_hStaticProv; - _hRSAKey = s_hStaticRSAKey; + _rsa = RSA.Create(); + _rsa.KeySize = 2048; } /// @@ -937,13 +584,7 @@ internal bool CanEncrypt /// the client side. internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForClient() { - PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(false); - - // set the handles for provider and rsa key - cryptoProvider._hProv = s_hStaticProv; - cryptoProvider._hRSAKey = s_hStaticRSAKey; - - return cryptoProvider; + return new PSRSACryptoServiceProvider(false); } /// @@ -954,36 +595,11 @@ internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForClient( /// the server side. internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForServer() { - PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(true); - - return cryptoProvider; + return new PSRSACryptoServiceProvider(true); } #endregion Internal Static Methods - #region Private Methods - - /// - /// Checks the status of a call, if it had resulted in an error - /// then obtains the last error, wraps it in an exception and - /// throws the same. - /// - /// Value to examine. - private void CheckStatus(bool value) - { - if (value) - { - return; - } - - uint errorCode = PSCryptoNativeUtils.GetLastError(); - StringBuilder errorMessage = new StringBuilder(new ComponentModel.Win32Exception(unchecked((int)errorCode)).Message); - - throw new PSCryptoException(errorCode, errorMessage); - } - - #endregion Private Methods - #region IDisposable /// @@ -1000,45 +616,14 @@ protected void Dispose(bool disposing) { if (disposing) { - if (_hSessionKey != null) + if (_rsa != null) { - if (!_hSessionKey.IsInvalid) - { - _hSessionKey.Dispose(); - } - - _hSessionKey = null; + _rsa.Dispose(); } - // we need to dismiss the provider and key - // only if the static members are not allocated - // since otherwise, these are just references - // to the static members - - if (s_hStaticRSAKey == null) + if (_aes != null) { - if (_hRSAKey != null) - { - if (!_hRSAKey.IsInvalid) - { - _hRSAKey.Dispose(); - } - - _hRSAKey = null; - } - } - - if (s_hStaticProv == null) - { - if (_hProv != null) - { - if (!_hProv.IsInvalid) - { - _hProv.Dispose(); - } - - _hProv = null; - } + _aes.Dispose(); } } } @@ -1324,11 +909,7 @@ internal class PSRemotingCryptoHelperServer : PSRemotingCryptoHelper /// internal PSRemotingCryptoHelperServer() { -#if UNIX - _rsaCryptoProvider = null; -#else _rsaCryptoProvider = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForServer(); -#endif } #endregion Constructors @@ -1455,8 +1036,6 @@ internal class PSRemotingCryptoHelperClient : PSRemotingCryptoHelper internal PSRemotingCryptoHelperClient() { _rsaCryptoProvider = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForClient(); - - // _session = new RemoteSession(); } #endregion Constructors diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index 26a1b6a60ac..8206b5cf8a3 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -16,6 +16,7 @@ internal static class EncodingConversion internal const string String = "string"; internal const string Unicode = "unicode"; internal const string BigEndianUnicode = "bigendianunicode"; + internal const string BigEndianUtf32 = "bigendianutf32"; internal const string Ascii = "ascii"; internal const string Utf8 = "utf8"; internal const string Utf8NoBom = "utf8NoBOM"; @@ -24,14 +25,16 @@ internal static class EncodingConversion internal const string Utf32 = "utf32"; internal const string Default = "default"; internal const string OEM = "oem"; + internal static readonly string[] TabCompletionResults = { - Ascii, BigEndianUnicode, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 + Ascii, BigEndianUnicode, BigEndianUtf32, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 }; - internal static Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { { Ascii, System.Text.Encoding.ASCII }, { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, + { BigEndianUtf32, new UTF32Encoding(bigEndian: true, byteOrderMark: true) }, { Default, ClrFacade.GetDefaultEncoding() }, { OEM, ClrFacade.GetOEMEncoding() }, { Unicode, System.Text.Encoding.Unicode }, @@ -116,6 +119,7 @@ internal sealed class ArgumentEncodingCompletionsAttribute : ArgumentCompletions public ArgumentEncodingCompletionsAttribute() : base( EncodingConversion.Ascii, EncodingConversion.BigEndianUnicode, + EncodingConversion.BigEndianUtf32, EncodingConversion.OEM, EncodingConversion.Unicode, EncodingConversion.Utf7, diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 297105a1c17..2b7fcd7cff4 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 @@ -33,7 +33,7 @@ internal CmdletInvocationException(ErrorRecord errorRecord) { if (errorRecord == null) { - throw new ArgumentNullException("errorRecord"); + throw new ArgumentNullException(nameof(errorRecord)); } _errorRecord = errorRecord; @@ -58,7 +58,7 @@ internal CmdletInvocationException(Exception innerException, { if (innerException == null) { - throw new ArgumentNullException("innerException"); + throw new ArgumentNullException(nameof(innerException)); } // invocationInfo may be null @@ -142,7 +142,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -208,7 +208,7 @@ internal CmdletProviderInvocationException( { if (innerException == null) { - throw new ArgumentNullException("innerException"); + throw new ArgumentNullException(nameof(innerException)); } _providerInvocationException = innerException; @@ -473,7 +473,7 @@ internal ActionPreferenceStopException(ErrorRecord error) { if (error == null) { - throw new ArgumentNullException("error"); + throw new ArgumentNullException(nameof(error)); } _errorRecord = error; @@ -501,7 +501,7 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, { if (errorRecord == null) { - throw new ArgumentNullException("errorRecord"); + throw new ArgumentNullException(nameof(errorRecord)); } _errorRecord = errorRecord; @@ -725,7 +725,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/ExtensionMethods.cs b/src/System.Management.Automation/utils/ExtensionMethods.cs index a7abaf71055..127c9a226cf 100644 --- a/src/System.Management.Automation/utils/ExtensionMethods.cs +++ b/src/System.Management.Automation/utils/ExtensionMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -68,7 +68,7 @@ internal static int SequenceGetHashCode(this IEnumerable xs) /// * If you want to add an extension method that will be used only by CoreCLR powershell, please add it to the partial /// 'PSTypeExtensions' class in 'CorePsExtensions.cs'. /// - internal static partial class PSTypeExtensions + internal static class PSTypeExtensions { /// /// Check does the type have an instance default constructor with visibility that allows calling it from subclass. diff --git a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs index a46fdb056ec..db68073deb4 100644 --- a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs +++ b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; diff --git a/src/System.Management.Automation/utils/FuzzyMatch.cs b/src/System.Management.Automation/utils/FuzzyMatch.cs index a99f9a5bf5c..3052cf6e3f2 100644 --- a/src/System.Management.Automation/utils/FuzzyMatch.cs +++ b/src/System.Management.Automation/utils/FuzzyMatch.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -21,7 +21,6 @@ public static bool IsFuzzyMatch(string string1, string string2) return GetDamerauLevenshteinDistance(string1, string2) <= MinimumDistance; } - /// /// Compute the case-insensitive distance between two strings. /// Based off https://www.csharpstar.com/csharp-string-distance-algorithm/. @@ -38,8 +37,8 @@ public static int GetDamerauLevenshteinDistance(string string1, string string2) int[,] matrix = new int[bounds.Height, bounds.Width]; - for (int height = 0; height < bounds.Height; height++) { matrix[height, 0] = height; }; - for (int width = 0; width < bounds.Width; width++) { matrix[0, width] = width; }; + for (int height = 0; height < bounds.Height; height++) { matrix[height, 0] = height; } + for (int width = 0; width < bounds.Width; width++) { matrix[0, width] = width; } for (int height = 1; height < bounds.Height; height++) { diff --git a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs index 3a1ffb11ba5..7579245980b 100644 --- a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs +++ b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Internal diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs index f0b80dcf057..c67fcd7e1b7 100644 --- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs +++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; diff --git a/src/System.Management.Automation/utils/IObjectReader.cs b/src/System.Management.Automation/utils/IObjectReader.cs index 5d865f197b8..a4fb4a53f37 100644 --- a/src/System.Management.Automation/utils/IObjectReader.cs +++ b/src/System.Management.Automation/utils/IObjectReader.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/utils/IObjectWriter.cs b/src/System.Management.Automation/utils/IObjectWriter.cs index c3367ee77f3..5a6afad9514 100644 --- a/src/System.Management.Automation/utils/IObjectWriter.cs +++ b/src/System.Management.Automation/utils/IObjectWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -125,18 +125,21 @@ public abstract int MaxCapacity internal class DiscardingPipelineWriter : PipelineWriter { private ManualResetEvent _waitHandle = new ManualResetEvent(true); + public override WaitHandle WaitHandle { get { return _waitHandle; } } private bool _isOpen = true; + public override bool IsOpen { get { return _isOpen; } } private int _count = 0; + public override int Count { get { return _count; } diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index c7a9e061b10..21f9a9b842c 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index f7adfb599f5..26980059c00 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -88,7 +88,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index 9789acb2dd9..03ab45654a3 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -99,7 +99,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index 6806b836248..a6bb0dfd3ff 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -86,7 +86,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index 18a100c686b..0889fee33df 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -57,7 +57,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -132,6 +132,7 @@ public ErrorRecord ErrorRecord private ErrorRecord _errorRecord; private string _errorId = "InvalidOperation"; + internal void SetErrorId(string errorId) { _errorId = errorId; diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index bc63b870ddc..e6a1128a38d 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -57,7 +57,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index c35af88a065..e6847ba6d16 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -57,7 +57,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index d1eacfc9068..93cf76100bb 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Runtime.Serialization; @@ -85,7 +85,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index b632b206dc1..9bb0cfbcc3d 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #define TRACE @@ -103,7 +103,7 @@ internal static PSTraceSource GetTracer( // 2005/04/13-JonN In theory this should be ArgumentException, // but I don't want to deal with loading the string in this // low-level code. - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } lock (PSTraceSource.s_getTracerLock) @@ -230,7 +230,7 @@ internal static PSArgumentNullException NewArgumentNullException(string paramNam { if (string.IsNullOrEmpty(paramName)) { - throw new ArgumentNullException("paramName"); + throw new ArgumentNullException(nameof(paramName)); } string message = StringUtil.Format(AutomationExceptions.ArgumentNull, paramName); @@ -259,12 +259,12 @@ internal static PSArgumentNullException NewArgumentNullException( { if (string.IsNullOrEmpty(paramName)) { - throw NewArgumentNullException("paramName"); + throw NewArgumentNullException(nameof(paramName)); } if (string.IsNullOrEmpty(resourceString)) { - throw NewArgumentNullException("resourceString"); + throw NewArgumentNullException(nameof(resourceString)); } string message = StringUtil.Format(resourceString, args); @@ -289,7 +289,7 @@ internal static PSArgumentException NewArgumentException(string paramName) { if (string.IsNullOrEmpty(paramName)) { - throw new ArgumentNullException("paramName"); + throw new ArgumentNullException(nameof(paramName)); } string message = StringUtil.Format(AutomationExceptions.Argument, paramName); @@ -319,12 +319,12 @@ internal static PSArgumentException NewArgumentException( { if (string.IsNullOrEmpty(paramName)) { - throw NewArgumentNullException("paramName"); + throw NewArgumentNullException(nameof(paramName)); } if (string.IsNullOrEmpty(resourceString)) { - throw NewArgumentNullException("resourceString"); + throw NewArgumentNullException(nameof(resourceString)); } string message = StringUtil.Format(resourceString, args); @@ -366,7 +366,7 @@ internal static PSInvalidOperationException NewInvalidOperationException( { if (string.IsNullOrEmpty(resourceString)) { - throw NewArgumentNullException("resourceString"); + throw NewArgumentNullException(nameof(resourceString)); } string message = StringUtil.Format(resourceString, args); @@ -396,7 +396,7 @@ internal static PSInvalidOperationException NewInvalidOperationException( { if (string.IsNullOrEmpty(resourceString)) { - throw NewArgumentNullException("resourceString"); + throw NewArgumentNullException(nameof(resourceString)); } string message = StringUtil.Format(resourceString, args); @@ -438,7 +438,7 @@ internal static PSNotSupportedException NewNotSupportedException( { if (string.IsNullOrEmpty(resourceString)) { - throw NewArgumentNullException("resourceString"); + throw NewArgumentNullException(nameof(resourceString)); } string message = StringUtil.Format(resourceString, args); @@ -479,7 +479,7 @@ internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException(str { if (string.IsNullOrEmpty(paramName)) { - throw new ArgumentNullException("paramName"); + throw new ArgumentNullException(nameof(paramName)); } string message = StringUtil.Format(AutomationExceptions.ArgumentOutOfRange, paramName); @@ -511,12 +511,12 @@ internal static PSArgumentOutOfRangeException NewArgumentOutOfRangeException( { if (string.IsNullOrEmpty(paramName)) { - throw NewArgumentNullException("paramName"); + throw NewArgumentNullException(nameof(paramName)); } if (string.IsNullOrEmpty(resourceString)) { - throw NewArgumentNullException("resourceString"); + throw NewArgumentNullException(nameof(resourceString)); } string message = StringUtil.Format(resourceString, args); @@ -542,7 +542,7 @@ internal static PSObjectDisposedException NewObjectDisposedException(string obje { if (string.IsNullOrEmpty(objectName)) { - throw NewArgumentNullException("objectName"); + throw NewArgumentNullException(nameof(objectName)); } string message = StringUtil.Format(AutomationExceptions.ObjectDisposed, objectName); diff --git a/src/System.Management.Automation/utils/ObjectReader.cs b/src/System.Management.Automation/utils/ObjectReader.cs index cb41bd79067..deb056a180e 100644 --- a/src/System.Management.Automation/utils/ObjectReader.cs +++ b/src/System.Management.Automation/utils/ObjectReader.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -27,7 +27,7 @@ public ObjectReaderBase([In, Out] ObjectStreamBase stream) { if (stream == null) { - throw new ArgumentNullException("stream", "stream may not be null"); + throw new ArgumentNullException(nameof(stream), "stream may not be null"); } _stream = stream; @@ -48,7 +48,7 @@ public override event EventHandler DataReady InternalDataReady += value; if (firstRegistrant) { - _stream.DataReady += new EventHandler(this.OnDataReady); + _stream.DataReady += this.OnDataReady; } } } @@ -60,7 +60,7 @@ public override event EventHandler DataReady InternalDataReady -= value; if (InternalDataReady == null) { - _stream.DataReady -= new EventHandler(this.OnDataReady); + _stream.DataReady -= this.OnDataReady; } } } @@ -573,7 +573,7 @@ public override Collection NonBlockingRead(int maxRequested) { if (maxRequested < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested); } if (maxRequested == 0) @@ -755,7 +755,7 @@ public override Collection NonBlockingRead(int maxRequested) { if (maxRequested < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested); } if (maxRequested == 0) diff --git a/src/System.Management.Automation/utils/ObjectStream.cs b/src/System.Management.Automation/utils/ObjectStream.cs index 989bd54a8da..eccfdfad901 100644 --- a/src/System.Management.Automation/utils/ObjectStream.cs +++ b/src/System.Management.Automation/utils/ObjectStream.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Internal @@ -541,7 +541,7 @@ internal ObjectStream(int capacity) { if (capacity <= 0 || capacity > Int32.MaxValue) { - throw PSTraceSource.NewArgumentOutOfRangeException("capacity", capacity); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(capacity), capacity); } // the maximum number of objects to allow in the stream at a given time. @@ -1124,7 +1124,7 @@ internal override Collection Read(int count) { if (count < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("count", count); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(count), count); } if (count == 0) @@ -1232,7 +1232,7 @@ internal override Collection NonBlockingRead(int maxRequested) if (maxRequested < 0) { - throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(maxRequested), maxRequested); } try @@ -1583,7 +1583,7 @@ internal PSDataCollectionStream(Guid psInstanceId, PSDataCollection storeToUs { if (storeToUse == null) { - throw PSTraceSource.NewArgumentNullException("storeToUse"); + throw PSTraceSource.NewArgumentNullException(nameof(storeToUse)); } _objects = storeToUse; diff --git a/src/System.Management.Automation/utils/ObjectWriter.cs b/src/System.Management.Automation/utils/ObjectWriter.cs index 73aa30cfefa..d4fe3493b78 100644 --- a/src/System.Management.Automation/utils/ObjectWriter.cs +++ b/src/System.Management.Automation/utils/ObjectWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Internal @@ -25,7 +25,7 @@ public ObjectWriter([In, Out] ObjectStreamBase stream) { if (stream == null) { - throw new ArgumentNullException("stream"); + throw new ArgumentNullException(nameof(stream)); } _stream = stream; diff --git a/src/System.Management.Automation/utils/PInvokeDllNames.cs b/src/System.Management.Automation/utils/PInvokeDllNames.cs index d0ce5ea844a..7dd28be8cdd 100644 --- a/src/System.Management.Automation/utils/PInvokeDllNames.cs +++ b/src/System.Management.Automation/utils/PInvokeDllNames.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation diff --git a/src/System.Management.Automation/utils/PSTelemetryMethods.cs b/src/System.Management.Automation/utils/PSTelemetryMethods.cs index a131a7bfef4..b440b649c79 100644 --- a/src/System.Management.Automation/utils/PSTelemetryMethods.cs +++ b/src/System.Management.Automation/utils/PSTelemetryMethods.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if LEGACYTELEMETRY diff --git a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs index 5a15dbb9435..8e9da553f24 100644 --- a/src/System.Management.Automation/utils/PSTelemetryWrapper.cs +++ b/src/System.Management.Automation/utils/PSTelemetryWrapper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if LEGACYTELEMETRY diff --git a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs index 78b92409f37..903bdc4076c 100644 --- a/src/System.Management.Automation/utils/ParameterBinderExceptions.cs +++ b/src/System.Management.Automation/utils/ParameterBinderExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Internal; @@ -86,12 +86,12 @@ internal ParameterBindingException( { if (string.IsNullOrEmpty(resourceString)) { - throw PSTraceSource.NewArgumentException("resourceString"); + throw PSTraceSource.NewArgumentException(nameof(resourceString)); } if (string.IsNullOrEmpty(errorId)) { - throw PSTraceSource.NewArgumentException("errorId"); + throw PSTraceSource.NewArgumentException(nameof(errorId)); } _invocationInfo = invocationInfo; @@ -194,17 +194,17 @@ internal ParameterBindingException( { if (invocationInfo == null) { - throw PSTraceSource.NewArgumentNullException("invocationInfo"); + throw PSTraceSource.NewArgumentNullException(nameof(invocationInfo)); } if (string.IsNullOrEmpty(resourceString)) { - throw PSTraceSource.NewArgumentException("resourceString"); + throw PSTraceSource.NewArgumentException(nameof(resourceString)); } if (string.IsNullOrEmpty(errorId)) { - throw PSTraceSource.NewArgumentException("errorId"); + throw PSTraceSource.NewArgumentException(nameof(errorId)); } _invocationInfo = invocationInfo; @@ -248,12 +248,12 @@ internal ParameterBindingException( { if (pbex == null) { - throw PSTraceSource.NewArgumentNullException("pbex"); + throw PSTraceSource.NewArgumentNullException(nameof(pbex)); } if (string.IsNullOrEmpty(resourceString)) { - throw PSTraceSource.NewArgumentException("resourceString"); + throw PSTraceSource.NewArgumentException(nameof(resourceString)); } _invocationInfo = pbex.CommandInvocation; @@ -327,7 +327,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -346,7 +346,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont /// /// DO NOT USE!!! /// - public ParameterBindingException() : base() {; } + public ParameterBindingException() : base() { } /// /// Constructors a ParameterBindingException. diff --git a/src/System.Management.Automation/utils/ParserException.cs b/src/System.Management.Automation/utils/ParserException.cs index 4feb9822d8c..22010873d9f 100644 --- a/src/System.Management.Automation/utils/ParserException.cs +++ b/src/System.Management.Automation/utils/ParserException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -15,6 +15,7 @@ namespace System.Management.Automation public class ParseException : RuntimeException { private const string errorIdString = "Parse"; + private ParseError[] _errors; /// @@ -47,7 +48,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -132,7 +133,7 @@ public ParseException(Language.ParseError[] errors) { if ((errors == null) || (errors.Length == 0)) { - throw new ArgumentNullException("errors"); + throw new ArgumentNullException(nameof(errors)); } _errors = errors; diff --git a/src/System.Management.Automation/utils/PathUtils.cs b/src/System.Management.Automation/utils/PathUtils.cs index da3d094bd01..ad92bc37fff 100644 --- a/src/System.Management.Automation/utils/PathUtils.cs +++ b/src/System.Management.Automation/utils/PathUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/utils/PlatformInvokes.cs b/src/System.Management.Automation/utils/PlatformInvokes.cs index a25aca6c73c..8e99cdff4b0 100644 --- a/src/System.Management.Automation/utils/PlatformInvokes.cs +++ b/src/System.Management.Automation/utils/PlatformInvokes.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; @@ -99,6 +99,7 @@ internal class SecurityAttributes internal int nLength; internal SafeLocalMemHandle lpSecurityDescriptor; internal bool bInheritHandle; + internal SecurityAttributes() { this.nLength = 12; @@ -124,6 +125,7 @@ internal SafeLocalMemHandle(IntPtr existingHandle, bool ownsHandle) [DllImport(PinvokeDllNames.LocalFreeDllName), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] private static extern IntPtr LocalFree(IntPtr hMem); + protected override bool ReleaseHandle() { return (LocalFree(base.handle) == IntPtr.Zero); @@ -527,14 +529,14 @@ internal struct PRIVILEGE_SET // Fields internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); - internal static UInt32 GENERIC_READ = 0x80000000; - internal static UInt32 GENERIC_WRITE = 0x40000000; - internal static UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; - internal static UInt32 CREATE_ALWAYS = 2; - internal static UInt32 FILE_SHARE_WRITE = 0x00000002; - internal static UInt32 FILE_SHARE_READ = 0x00000001; - internal static UInt32 OF_READWRITE = 0x00000002; - internal static UInt32 OPEN_EXISTING = 3; + internal static readonly UInt32 GENERIC_READ = 0x80000000; + internal static readonly UInt32 GENERIC_WRITE = 0x40000000; + internal static readonly UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; + internal static readonly UInt32 CREATE_ALWAYS = 2; + internal static readonly UInt32 FILE_SHARE_WRITE = 0x00000002; + internal static readonly UInt32 FILE_SHARE_READ = 0x00000001; + internal static readonly UInt32 OF_READWRITE = 0x00000002; + internal static readonly UInt32 OPEN_EXISTING = 3; [StructLayout(LayoutKind.Sequential)] internal class PROCESS_INFORMATION @@ -602,6 +604,7 @@ internal class STARTUPINFO public SafeFileHandle hStdInput; public SafeFileHandle hStdOutput; public SafeFileHandle hStdError; + public STARTUPINFO() { this.lpReserved = IntPtr.Zero; @@ -650,6 +653,7 @@ internal class SECURITY_ATTRIBUTES public int nLength; public SafeLocalMemHandle lpSecurityDescriptor; public bool bInheritHandle; + public SECURITY_ATTRIBUTES() { this.nLength = 12; @@ -674,7 +678,8 @@ internal static extern bool CreateProcess( [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint ResumeThread(IntPtr threadHandle); - internal static uint RESUME_THREAD_FAILED = System.UInt32.MaxValue; // (DWORD)-1 + + internal static readonly uint RESUME_THREAD_FAILED = System.UInt32.MaxValue; // (DWORD)-1 [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern System.IntPtr CreateFileW( diff --git a/src/System.Management.Automation/utils/PowerShellETWTracer.cs b/src/System.Management.Automation/utils/PowerShellETWTracer.cs index d9945d4cc0f..0dc4b2f08f8 100644 --- a/src/System.Management.Automation/utils/PowerShellETWTracer.cs +++ b/src/System.Management.Automation/utils/PowerShellETWTracer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs index 35e6af08a51..d6d845c7281 100644 --- a/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs +++ b/src/System.Management.Automation/utils/PowerShellExecutionHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -18,7 +18,7 @@ internal PowerShellExecutionHelper(PowerShell powershell) { if (powershell == null) { - throw PSTraceSource.NewArgumentNullException("powershell"); + throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } CurrentPowerShell = powershell; diff --git a/src/System.Management.Automation/utils/PsUtils.cs b/src/System.Management.Automation/utils/PsUtils.cs index 447564d013e..5866e3d52f9 100644 --- a/src/System.Management.Automation/utils/PsUtils.cs +++ b/src/System.Management.Automation/utils/PsUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; @@ -298,11 +298,11 @@ internal static Hashtable EvaluatePowerShellDataFile( bool allowEnvironmentVariables, bool skipPathValidation) { - if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } + if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException(nameof(parameterName)); } - if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } + if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException(nameof(psDataFilePath)); } - if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } + if (context == null) { throw PSTraceSource.NewArgumentNullException(nameof(context)); } string resolvedPath; if (skipPathValidation) @@ -404,6 +404,7 @@ internal static Hashtable EvaluatePowerShellDataFile( internal static readonly string[] ManifestModuleVersionPropertyName = new[] { "ModuleVersion" }; internal static readonly string[] ManifestGuidPropertyName = new[] { "GUID" }; internal static readonly string[] ManifestPrivateDataPropertyName = new[] { "PrivateData" }; + internal static readonly string[] FastModuleManifestAnalysisPropertyNames = new[] { "AliasesToExport", @@ -486,7 +487,7 @@ internal static string StringToBase64String(string input) // shell crashes if you pass an empty script block to a native command if (input == null) { - throw PSTraceSource.NewArgumentNullException("input"); + throw PSTraceSource.NewArgumentNullException(nameof(input)); } string base64 = Convert.ToBase64String @@ -505,7 +506,7 @@ internal static string Base64ToString(string base64) { if (string.IsNullOrEmpty(base64)) { - throw PSTraceSource.NewArgumentNullException("base64"); + throw PSTraceSource.NewArgumentNullException(nameof(base64)); } string output = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); @@ -521,7 +522,7 @@ internal static object[] Base64ToArgsConverter(string base64) { if (string.IsNullOrEmpty(base64)) { - throw PSTraceSource.NewArgumentNullException("base64"); + throw PSTraceSource.NewArgumentNullException(nameof(base64)); } string decoded = new string(Encoding.Unicode.GetChars(Convert.FromBase64String(base64))); @@ -566,6 +567,7 @@ internal class CRC32Hash { // CRC-32C polynomial representations private const uint polynomial = 0x1EDC6F41; + private static uint[] table; static CRC32Hash() diff --git a/src/System.Management.Automation/utils/ResourceManagerCache.cs b/src/System.Management.Automation/utils/ResourceManagerCache.cs index e4f5c3dc594..302fd0c48cf 100644 --- a/src/System.Management.Automation/utils/ResourceManagerCache.cs +++ b/src/System.Management.Automation/utils/ResourceManagerCache.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -43,12 +43,12 @@ internal static ResourceManager GetResourceManager( { if (assembly == null) { - throw PSTraceSource.NewArgumentNullException("assembly"); + throw PSTraceSource.NewArgumentNullException(nameof(assembly)); } if (string.IsNullOrEmpty(baseName)) { - throw PSTraceSource.NewArgumentException("baseName"); + throw PSTraceSource.NewArgumentException(nameof(baseName)); } // Check to see if the manager is already in the cache @@ -113,6 +113,7 @@ internal static ResourceManager GetResourceManager( /// Design For Testability -- assert on failed resource lookup. /// private static bool s_DFT_monitorFailingResourceLookup = true; + internal static bool DFT_DoMonitorFailingResourceLookup { get { return ResourceManagerCache.s_DFT_monitorFailingResourceLookup; } @@ -153,17 +154,17 @@ internal static string GetResourceString( { if (assembly == null) { - throw PSTraceSource.NewArgumentNullException("assembly"); + throw PSTraceSource.NewArgumentNullException(nameof(assembly)); } if (string.IsNullOrEmpty(baseName)) { - throw PSTraceSource.NewArgumentException("baseName"); + throw PSTraceSource.NewArgumentException(nameof(baseName)); } if (string.IsNullOrEmpty(resourceId)) { - throw PSTraceSource.NewArgumentException("resourceId"); + throw PSTraceSource.NewArgumentException(nameof(resourceId)); } ResourceManager resourceManager = null; @@ -234,7 +235,7 @@ private static ResourceManager InitRMWithAssembly(string baseName, Assembly asse { // 2004/10/11-JonN Do we need a better error message? I don't think so, // since this is private. - throw PSTraceSource.NewArgumentException("assemblyToUse"); + throw PSTraceSource.NewArgumentException(nameof(assemblyToUse)); } return rm; diff --git a/src/System.Management.Automation/utils/RuntimeException.cs b/src/System.Management.Automation/utils/RuntimeException.cs index d3fc5e95201..fe5a6c3b4be 100644 --- a/src/System.Management.Automation/utils/RuntimeException.cs +++ b/src/System.Management.Automation/utils/RuntimeException.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Language; @@ -60,7 +60,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); @@ -305,6 +305,7 @@ internal bool SuppressPromptInInterpreter #endregion Internal private Token _errorToken; + internal Token ErrorToken { get diff --git a/src/System.Management.Automation/utils/SessionStateExceptions.cs b/src/System.Management.Automation/utils/SessionStateExceptions.cs index 7f516c413a9..acf3d9b8306 100644 --- a/src/System.Management.Automation/utils/SessionStateExceptions.cs +++ b/src/System.Management.Automation/utils/SessionStateExceptions.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; @@ -98,7 +98,7 @@ internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRec { if (errorRecord == null) { - throw new ArgumentNullException("errorRecord"); + throw new ArgumentNullException(nameof(errorRecord)); } _message = base.Message; @@ -482,7 +482,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont { if (info == null) { - throw new PSArgumentNullException("info"); + throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); diff --git a/src/System.Management.Automation/utils/StringUtil.cs b/src/System.Management.Automation/utils/StringUtil.cs index 99eb63d90e4..9b3cf3447cb 100644 --- a/src/System.Management.Automation/utils/StringUtil.cs +++ b/src/System.Management.Automation/utils/StringUtil.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Management.Automation.Host; @@ -66,7 +66,9 @@ internal static // 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) @@ -84,7 +86,9 @@ internal static string Padding(int countOfSpaces) } private const int DashCacheMax = 120; + private static readonly string[] DashCache = new string[DashCacheMax]; + internal static string DashPadding(int count) { if (count >= DashCacheMax) diff --git a/src/System.Management.Automation/utils/StructuredTraceSource.cs b/src/System.Management.Automation/utils/StructuredTraceSource.cs index c3d7b566205..c464a27cbaa 100644 --- a/src/System.Management.Automation/utils/StructuredTraceSource.cs +++ b/src/System.Management.Automation/utils/StructuredTraceSource.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #define TRACE @@ -274,7 +274,7 @@ internal PSTraceSource(string fullName, string name, string description, bool tr // 2005/04/13-JonN In theory this should be ArgumentException, // but I don't want to deal with loading the string in this // low-level code. - throw new ArgumentNullException("fullName"); + throw new ArgumentNullException(nameof(fullName)); } try diff --git a/src/System.Management.Automation/utils/Telemetry.cs b/src/System.Management.Automation/utils/Telemetry.cs index bf4f0be1f55..6041c35ca06 100644 --- a/src/System.Management.Automation/utils/Telemetry.cs +++ b/src/System.Management.Automation/utils/Telemetry.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -87,6 +87,9 @@ public static class ApplicationInsightsTelemetry // the session identifier private static string s_sessionId { get; set; } + // private semaphore to determine whether we sent the startup telemetry event + private static int s_startupEventSent = 0; + /// Use a hashset for quick lookups. /// We send telemetry only a known set of modules. /// If it's not in the list (initialized in the static constructor), then we report anonymous. @@ -583,6 +586,8 @@ internal static void SendTelemetryMetric(TelemetryType metricId, string data) return; } + SendPSCoreStartupTelemetry("hosted"); + string metricName = metricId.ToString(); try { @@ -645,6 +650,12 @@ private static string GetModuleName(string moduleNameToValidate) /// The "mode" of the startup. internal static void SendPSCoreStartupTelemetry(string mode) { + // Check if we already sent startup telemetry + if (Interlocked.CompareExchange(ref s_startupEventSent, 1, 0) == 1) + { + return; + } + if (!CanSendTelemetry) { return; diff --git a/src/System.Management.Automation/utils/VTUtils.cs b/src/System.Management.Automation/utils/VTUtils.cs index 2ff110dd423..c91ce24e19d 100644 --- a/src/System.Management.Automation/utils/VTUtils.cs +++ b/src/System.Management.Automation/utils/VTUtils.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; @@ -22,24 +22,24 @@ public enum VT Inverse } - private static readonly Dictionary ConsoleColors = new Dictionary + private static readonly Dictionary ForegroundColorMap = new Dictionary { - { ConsoleColor.Black, "\x1b[2;30m" }, - { ConsoleColor.Gray, "\x1b[2;37m" }, - { ConsoleColor.Red, "\x1b[1;31m" }, - { ConsoleColor.Green, "\x1b[1;32m" }, - { ConsoleColor.Yellow, "\x1b[1;33m" }, - { ConsoleColor.Blue, "\x1b[1;34m" }, - { ConsoleColor.Magenta, "\x1b[1;35m" }, - { ConsoleColor.Cyan, "\x1b[1;36m" }, - { ConsoleColor.White, "\x1b[1;37m" }, - { ConsoleColor.DarkRed, "\x1b[2;31m" }, - { ConsoleColor.DarkGreen, "\x1b[2;32m" }, - { ConsoleColor.DarkYellow, "\x1b[2;33m" }, - { ConsoleColor.DarkBlue, "\x1b[2;34m" }, - { ConsoleColor.DarkMagenta, "\x1b[2;35m" }, - { ConsoleColor.DarkCyan, "\x1b[2;36m" }, - { ConsoleColor.DarkGray, "\x1b[1;30m" }, + { ConsoleColor.Black, "\x1b[30m" }, + { ConsoleColor.Gray, "\x1b[37m" }, + { ConsoleColor.Red, "\x1b[91m" }, + { ConsoleColor.Green, "\x1b[92m" }, + { ConsoleColor.Yellow, "\x1b[93m" }, + { ConsoleColor.Blue, "\x1b[94m" }, + { ConsoleColor.Magenta, "\x1b[95m" }, + { ConsoleColor.Cyan, "\x1b[96m" }, + { ConsoleColor.White, "\x1b[97m" }, + { ConsoleColor.DarkRed, "\x1b[31m" }, + { ConsoleColor.DarkGreen, "\x1b[32m" }, + { ConsoleColor.DarkYellow, "\x1b[33m" }, + { ConsoleColor.DarkBlue, "\x1b[34m" }, + { ConsoleColor.DarkMagenta, "\x1b[35m" }, + { ConsoleColor.DarkCyan, "\x1b[36m" }, + { ConsoleColor.DarkGray, "\x1b[90m" }, }; private static readonly Dictionary VTCodes = new Dictionary @@ -60,7 +60,7 @@ public enum VT public static string GetEscapeSequence(ConsoleColor color) { string value = string.Empty; - ConsoleColors.TryGetValue(color, out value); + ForegroundColorMap.TryGetValue(color, out value); return value; } diff --git a/src/System.Management.Automation/utils/Verbs.cs b/src/System.Management.Automation/utils/Verbs.cs index 1bd2efba32b..aeb6a3ee530 100644 --- a/src/System.Management.Automation/utils/Verbs.cs +++ b/src/System.Management.Automation/utils/Verbs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/utils/assert.cs b/src/System.Management.Automation/utils/assert.cs index 2909c858178..921ed42c0f3 100644 --- a/src/System.Management.Automation/utils/assert.cs +++ b/src/System.Management.Automation/utils/assert.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // The define below is only valid for this file. It allows the methods @@ -11,6 +11,7 @@ #define DEBUG using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Text; namespace System.Management.Automation @@ -126,6 +127,7 @@ internal static void Assert( #if RESHARPER_ATTRIBUTES [JetBrains.Annotations.AssertionCondition(JetBrains.Annotations.AssertionConditionType.IS_TRUE)] #endif + [DoesNotReturnIf(false)] bool condition, string whyThisShouldNeverHappen) { @@ -159,6 +161,7 @@ internal static void #if RESHARPER_ATTRIBUTES [JetBrains.Annotations.AssertionCondition(JetBrains.Annotations.AssertionConditionType.IS_TRUE)] #endif + [DoesNotReturnIf(false)] bool condition, string whyThisShouldNeverHappen, string detailMessage) { diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs index 68d770d8a90..89b2a69e7b4 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetInstanceBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; diff --git a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs index 58fc193bd9c..155a3db99c9 100644 --- a/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs +++ b/src/System.Management.Automation/utils/perfCounters/CounterSetRegistrarBase.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; diff --git a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs index 8ecaf3600a5..22df79a0589 100644 --- a/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs +++ b/src/System.Management.Automation/utils/perfCounters/PSPerfCountersMgr.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Concurrent; diff --git a/src/System.Management.Automation/utils/tracing/EtwActivity.cs b/src/System.Management.Automation/utils/tracing/EtwActivity.cs index 6f076f148ac..2bd8a57fbeb 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivity.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivity.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -122,12 +122,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackNoParameter callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } if (tracer == null) { - throw new ArgumentNullException("tracer"); + throw new ArgumentNullException(nameof(tracer)); } this.tracer = tracer; @@ -144,12 +144,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithState callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } if (tracer == null) { - throw new ArgumentNullException("tracer"); + throw new ArgumentNullException(nameof(tracer)); } this.tracer = tracer; @@ -166,12 +166,12 @@ public CorrelatedCallback(EtwActivity tracer, AsyncCallback callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } if (tracer == null) { - throw new ArgumentNullException("tracer"); + throw new ArgumentNullException(nameof(tracer)); } this.tracer = tracer; @@ -193,12 +193,12 @@ public CorrelatedCallback(EtwActivity tracer, CallbackWithStateAndArgs callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } if (tracer == null) { - throw new ArgumentNullException("tracer"); + throw new ArgumentNullException(nameof(tracer)); } this.tracer = tracer; @@ -380,7 +380,7 @@ public CallbackNoParameter Correlate(CallbackNoParameter callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } return new CorrelatedCallback(this, callback).Callback; @@ -395,7 +395,7 @@ public CallbackWithState Correlate(CallbackWithState callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } return new CorrelatedCallback(this, callback).Callback; @@ -410,7 +410,7 @@ public AsyncCallback Correlate(AsyncCallback callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } return new CorrelatedCallback(this, callback).Callback; @@ -426,7 +426,7 @@ public CallbackWithStateAndArgs Correlate(CallbackWithStateAndArgs callback) { if (callback == null) { - throw new ArgumentNullException("callback"); + throw new ArgumentNullException(nameof(callback)); } return new CorrelatedCallback(this, callback).Callback; diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs index 22badeaa20b..fdff216e1c8 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs index 3a753e59182..db63b2727d3 100644 --- a/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/EtwActivityReverterMethodInvoker.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -22,7 +22,7 @@ public EtwActivityReverterMethodInvoker(IEtwEventCorrelator eventCorrelator) { if (eventCorrelator == null) { - throw new ArgumentNullException("eventCorrelator"); + throw new ArgumentNullException(nameof(eventCorrelator)); } _eventCorrelator = eventCorrelator; diff --git a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs index d22830c5e6c..7e4e81abe06 100644 --- a/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs +++ b/src/System.Management.Automation/utils/tracing/EtwEventCorrelator.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -63,7 +63,7 @@ public EtwEventCorrelator(EventProvider transferProvider, EventDescriptor transf { if (transferProvider == null) { - throw new ArgumentNullException("transferProvider"); + throw new ArgumentNullException(nameof(transferProvider)); } _transferProvider = transferProvider; diff --git a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs index 20f60433cc1..78561134fb9 100644 --- a/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs +++ b/src/System.Management.Automation/utils/tracing/IMethodInvoker.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs index 5cf505bdbea..ec772fe549c 100644 --- a/src/System.Management.Automation/utils/tracing/PSEtwLog.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLog.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; diff --git a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs index d3158afa763..173c5b8379a 100755 --- a/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSEtwLogProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs index 27799bdc16b..5f698f1b912 100755 --- a/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/PSSysLogProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if UNIX @@ -42,19 +42,19 @@ static PSSysLogProvider() /// property to ensure correct thread initialization; otherwise, a null reference can occur. /// [ThreadStatic] - private static StringBuilder _payloadBuilder; + private static StringBuilder t_payloadBuilder; private static StringBuilder PayloadBuilder { get { - if (_payloadBuilder == null) + if (t_payloadBuilder == null) { // NOTE: Thread static fields must be explicitly initialized for each thread. - _payloadBuilder = new StringBuilder(200); + t_payloadBuilder = new StringBuilder(200); } - return _payloadBuilder; + return t_payloadBuilder; } } diff --git a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs index 59b2c0055cf..f3a899acb7d 100755 --- a/src/System.Management.Automation/utils/tracing/SysLogProvider.cs +++ b/src/System.Management.Automation/utils/tracing/SysLogProvider.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if UNIX @@ -123,19 +123,19 @@ public SysLogProvider(string applicationId, PSLevel level, PSKeyword keywords, P /// property to ensure correct thread initialization; otherwise, a null reference can occur. /// [ThreadStatic] - private static StringBuilder _messageBuilder; + private static StringBuilder t_messageBuilder; private static StringBuilder MessageBuilder { get { - if (_messageBuilder == null) + if (t_messageBuilder == null) { // NOTE: Thread static fields must be explicitly initialized for each thread. - _messageBuilder = new StringBuilder(200); + t_messageBuilder = new StringBuilder(200); } - return _messageBuilder; + return t_messageBuilder; } } @@ -147,24 +147,24 @@ private static StringBuilder MessageBuilder /// to ensure correct thread initialization. /// [ThreadStatic] - static Guid? _activity; + static Guid? t_activity; private static Guid Activity { get { - if (_activity.HasValue == false) + if (t_activity.HasValue == false) { // NOTE: Thread static fields must be explicitly initialized for each thread. - _activity = Guid.NewGuid(); + t_activity = Guid.NewGuid(); } - return _activity.Value; + return t_activity.Value; } set { - _activity = value; + t_activity = value; } } diff --git a/src/System.Management.Automation/utils/tracing/Tracing.cs b/src/System.Management.Automation/utils/tracing/Tracing.cs index ab6c0f6831d..70338b28c7a 100644 --- a/src/System.Management.Automation/utils/tracing/Tracing.cs +++ b/src/System.Management.Automation/utils/tracing/Tracing.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX diff --git a/src/System.Management.Automation/utils/tracing/TracingGen.cs b/src/System.Management.Automation/utils/tracing/TracingGen.cs index 30fd715cb66..ea369e4513a 100644 --- a/src/System.Management.Automation/utils/tracing/TracingGen.cs +++ b/src/System.Management.Automation/utils/tracing/TracingGen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #if !UNIX @@ -36,6 +36,7 @@ public sealed partial class Tracer : System.Management.Automation.Tracing.EtwAct /// Keyword all. /// public const long KeywordAll = 0xFFFFFFFF; + private static Guid providerId = Guid.Parse("a0c1853b-5c40-4b15-8766-3cf1c58f985a"); private static EventDescriptor WriteTransferEventEvent; private static EventDescriptor DebugMessageEvent; diff --git a/src/TypeCatalogGen/TypeCatalogGen.cs b/src/TypeCatalogGen/TypeCatalogGen.cs index 2427f90fa72..8bac4cdbc21 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.cs +++ b/src/TypeCatalogGen/TypeCatalogGen.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /* * This is the source code for the tool 'TypeCatalogGen.exe', which has been checked in %SDXROOT%\tools\managed\v4.0\TypeCatalogGen. @@ -384,7 +384,7 @@ private static List ResolveReferenceAssemblies(string path) } string allText = File.ReadAllText(referenceListPath); - string[] references = allText.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + string[] references = allText.Split(';', StringSplitOptions.RemoveEmptyEntries); List refAssemblyFiles = new List(120); for (int i = 0; i < references.Length; i++) diff --git a/src/TypeCatalogGen/TypeCatalogGen.csproj b/src/TypeCatalogGen/TypeCatalogGen.csproj index 0b703967717..1ba3029ff18 100644 --- a/src/TypeCatalogGen/TypeCatalogGen.csproj +++ b/src/TypeCatalogGen/TypeCatalogGen.csproj @@ -2,7 +2,7 @@ Generates CorePsTypeCatalog.cs given powershell.inc - netcoreapp3.1 + net5.0 TypeCatalogGen Exe true diff --git a/src/libpsl-native/README.md b/src/libpsl-native/README.md index 70998594406..940fe41150c 100644 --- a/src/libpsl-native/README.md +++ b/src/libpsl-native/README.md @@ -1,5 +1,5 @@ # libpsl-native -The code under `libpsl-native` is being migrated to [PowerShell-native](https://github.com/PowerShell/PowerShell-native) repository. +The code under `libpsl-native` is being migrated to the [PowerShell-native](https://github.com/PowerShell/PowerShell-native) repository. Please make PRs to the new repository. Code under here will be removed once the move is complete. diff --git a/src/powershell-native/Install-PowerShellRemoting.ps1 b/src/powershell-native/Install-PowerShellRemoting.ps1 index 5162d1dccb2..f42fcde2da6 100644 --- a/src/powershell-native/Install-PowerShellRemoting.ps1 +++ b/src/powershell-native/Install-PowerShellRemoting.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. ##################################################################################################### @@ -215,7 +215,7 @@ function Install-PluginEndpoint { try { - Write-Host "`nGet-PSSessionConfiguration $pluginEndpointName" -foregroundcolor "green" + Write-Host "`nGet-PSSessionConfiguration $pluginEndpointName" -ForegroundColor "green" Get-PSSessionConfiguration $pluginEndpointName -ErrorAction Stop } catch [Microsoft.PowerShell.Commands.WriteErrorException] @@ -227,6 +227,6 @@ function Install-PluginEndpoint { Install-PluginEndpoint -Force $Force Install-PluginEndpoint -Force $Force -VersionIndependent -Write-Host "Restarting WinRM to ensure that the plugin configuration change takes effect.`nThis is required for WinRM running on Windows SKUs prior to Windows 10." -foregroundcolor Magenta +Write-Host "Restarting WinRM to ensure that the plugin configuration change takes effect.`nThis is required for WinRM running on Windows SKUs prior to Windows 10." -ForegroundColor Magenta Restart-Service winrm diff --git a/src/powershell/Program.cs b/src/powershell/Program.cs index 99834e6a95f..e4d3b51c5d6 100644 --- a/src/powershell/Program.cs +++ b/src/powershell/Program.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; diff --git a/stylecop.json b/stylecop.json index de9133da257..77517f2095b 100644 --- a/stylecop.json +++ b/stylecop.json @@ -38,7 +38,7 @@ "allowConsecutiveUsings" : false }, "documentationRules" : { - "copyrightText" : "Copyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the MIT License.", + "copyrightText" : "Copyright (c) Microsoft Corporation.\nLicensed under the MIT License.", "xmlHeader" : false, "documentInterfaces" : true, "documentExposedElements" : true, diff --git a/test/SSHRemoting/SSHRemoting.Basic.Tests.ps1 b/test/SSHRemoting/SSHRemoting.Basic.Tests.ps1 new file mode 100644 index 00000000000..40fa0ec1027 --- /dev/null +++ b/test/SSHRemoting/SSHRemoting.Basic.Tests.ps1 @@ -0,0 +1,187 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "SSHRemoting Basic Tests" -tags CI { + + # SSH remoting is set up to automatically authenticate current user via SSH keys + # All tests connect back to localhost machine + + function VerifySession { + param ( + [System.Management.Automation.Runspaces.PSSession] $session + ) + + $session.State | Should -BeExactly 'Opened' + $session.ComputerName | Should -BeExactly 'localhost' + $session.Transport | Should -BeExactly 'SSH' + Invoke-Command -Session $session -ScriptBlock { whoami } | Should -BeExactly $(whoami) + $psRemoteVersion = Invoke-Command -Session $session -ScriptBlock { $PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion } + $psRemoteVersion.Major | Should -BeExactly $PSVersionTable.PSVersion.Major + $psRemoteVersion.Minor | Should -BeExactly $PSVersionTable.PSVersion.Minor + } + + Context "New-PSSession Tests" { + + AfterEach { + if ($script:session -ne $null) { Remove-PSSession -Session $script:session } + if ($script:sessions -ne $null) { Remove-PSSession -Session $script:sessions } + } + + It "Verifies new connection with implicit current User" { + $script:session = New-PSSession -HostName localhost -ErrorVariable err + $err | Should -HaveCount 0 + VerifySession $script:session + } + + It "Verifies new connection with explicit User parameter" { + $script:session = New-PSSession -HostName localhost -UserName (whoami) -ErrorVariable err + $err | Should -HaveCount 0 + VerifySession $script:session + } + + It "Verifies explicit Name parameter" { + $sessionName = 'TestSessionNameA' + $script:session = New-PSSession -HostName localhost -Name $sessionName -ErrorVariable err + $err | Should -HaveCount 0 + VerifySession $script:session + $script:session.Name | Should -BeExactly $sessionName + } + + It "Verifies explicit Port parameter" { + $portNum = 22 + $script:session = New-PSSession -HostName localhost -Port $portNum -ErrorVariable err + $err | Should -HaveCount 0 + VerifySession $script:session + } + + It "Verifies explicit Subsystem parameter" { + $portNum = 22 + $subSystem = 'powershell' + $script:session = New-PSSession -HostName localhost -Port $portNum -SubSystem $subSystem -ErrorVariable err + $err | Should -HaveCount 0 + VerifySession $script:session + } + + It "Verifies explicit KeyFilePath parameter" { + $keyFilePath = "$HOME/.ssh/id_rsa" + $portNum = 22 + $subSystem = 'powershell' + $script:session = New-PSSession -HostName localhost -Port $portNum -SubSystem $subSystem -KeyFilePath $keyFilePath -ErrorVariable err + $err | Should -HaveCount 0 + VerifySession $script:session + } + + It "Verifies SSHConnection hash table parameters" { + $sshConnection = @( + @{ + HostName = 'localhost' + UserName = whoami + Port = 22 + KeyFilePath = "$HOME/.ssh/id_rsa" + Subsystem = 'powershell' + }, + @{ + HostName = 'localhost' + KeyFilePath = "$HOME/.ssh/id_rsa" + Subsystem = 'powershell' + }) + $script:sessions = New-PSSession -SSHConnection $sshConnection -Name 'Connection1','Connection2' -ErrorVariable err + $err | Should -HaveCount 0 + $script:sessions | Should -HaveCount 2 + $script:sessions[0].Name | Should -BeLike 'Connection*' + $script:sessions[1].Name | Should -BeLike 'Connection*' + VerifySession $script:sessions[0] + VerifySession $script:sessions[1] + } + } + + function VerifyRunspace { + param ( + [runspace] $rs + ) + + $rs.RunspaceStateInfo.State | Should -BeExactly 'Opened' + $rs.RunspaceAvailability | Should -BeExactly 'Available' + $rs.RunspaceIsRemote | Should -BeTrue + $ps = [powershell]::Create() + try + { + $ps.Runspace = $rs + $psRemoteVersion = $ps.AddScript('$PSSenderInfo.ApplicationArguments.PSVersionTable.PSVersion').Invoke() + $psRemoteVersion.Major | Should -BeExactly $PSVersionTable.PSVersion.Major + $psRemoteVersion.Minor | Should -BeExactly $PSVersionTable.PSVersion.Minor + + $ps.Commands.Clear() + $ps.AddScript('whoami').Invoke() | Should -BeExactly $(whoami) + } + finally + { + $ps.Dispose() + } + } + + Context "SSH Remoting API Tests" { + + AfterEach { + if ($script:rs -ne $null) { $script:rs.Dispose() } + } + + $testCases = @( + @{ + testName = 'Verifies connection with implicit user' + UserName = $null + ComputerName = 'localhost' + KeyFilePath = $null + Port = 0 + Subsystem = $null + }, + @{ + testName = 'Verifies connection with UserName' + UserName = whoami + ComputerName = 'localhost' + KeyFilePath = $null + Port = 0 + Subsystem = $null + }, + @{ + testName = 'Verifies connection with KeyFilePath' + UserName = whoami + ComputerName = 'localhost' + KeyFilePath = "$HOME/.ssh/id_rsa" + Port = 0 + Subsystem = $null + }, + @{ + testName = 'Verifies connection with Port specified' + UserName = whoami + ComputerName = 'localhost' + KeyFilePath = "$HOME/.ssh/id_rsa" + Port = 22 + Subsystem = $null + }, + @{ + testName = 'Verifies connection with Subsystem specified' + UserName = whoami + ComputerName = 'localhost' + KeyFilePath = "$HOME/.ssh/id_rsa" + Port = 22 + Subsystem = 'powershell' + } + ) + + It "" -TestCases $testCases { + param ( + $UserName, + $ComputerName, + $KeyFilePath, + $Port, + $SubSystem + ) + + $ci = [System.Management.Automation.Runspaces.SSHConnectionInfo]::new($UserName, $ComputerName, $KeyFilePath, $Port, $Subsystem) + $script:rs = [runspacefactory]::CreateRunspace($host, $ci) + $script:rs.Open() + VerifyRunspace $script:rs + } + } +} diff --git a/test/Test.Common.props b/test/Test.Common.props index 57afccc7772..777680552a4 100644 --- a/test/Test.Common.props +++ b/test/Test.Common.props @@ -2,9 +2,9 @@ PowerShell Test Microsoft Corporation - (c) Microsoft Corporation. All rights reserved. + (c) Microsoft Corporation. - netcoreapp3.1 + netcoreapp5.0 8.0 true diff --git a/test/common/markdown/gulpfile.js b/test/common/markdown/gulpfile.js new file mode 100644 index 00000000000..90014969b7d --- /dev/null +++ b/test/common/markdown/gulpfile.js @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +function runTest() { + "use strict"; + var gulp = require("gulp"); + var concat = require("gulp-concat"); + var through2 = require("through2"); + var markdownlint = require("markdownlint"); + + gulp.task("test-mdsyntax", function task() { + var paths = []; + var rootpath; + + // assign --repoRoot into rootpath + var j = process.argv.indexOf("--rootpath"); + if (j > -1) { + rootpath = process.argv[j + 1]; + } + + if (rootpath === null) { + throw "--rootpath must be specified before all other parameters"; + } + + // parse --filter into paths. --rootpath must be specified first. + j = process.argv.indexOf("--filter"); + if (j > -1) { + var filters = process.argv[j + 1].split(","); + filters.forEach(function(filter) { + paths.push(rootpath + "/" + filter); + }, this); + } + + if (paths.length === 0) { + throw "--filter must be specified"; + } + + var rootJsonFile = rootpath + "/.markdownlint.json"; + var fs = require("fs"); + fs.appendFileSync("markdownissues.txt", "--EMPTY--\r\n"); + return gulp.src(paths, { "read": false }) + .pipe(through2.obj(function obj(file, enc, next) { + markdownlint({ + "files": [file.path], + "config": require(rootJsonFile) + }, + function callback(err, result) { + var resultString = (result || "").toString(); + if (resultString) { + file.contents = Buffer.from(resultString); + } + next(err, file); + }); + })) + .pipe(concat("markdownissues.txt", { newLine: "\r\n" })) + .pipe(gulp.dest(".")); + }); +} + +runTest(); diff --git a/test/common/markdown/markdown-link.tests.ps1 b/test/common/markdown/markdown-link.tests.ps1 index 79f72906f12..21c3632b530 100644 --- a/test/common/markdown/markdown-link.tests.ps1 +++ b/test/common/markdown/markdown-link.tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Verify Markdown Links" { @@ -17,12 +17,12 @@ Describe "Verify Markdown Links" { } # Cleanup jobs for reliability - get-job | remove-job -force + Get-Job | Remove-Job -Force } AfterAll { # Cleanup jobs to leave the process the same - get-job | remove-job -force + Get-Job | Remove-Job -Force } $groups = Get-ChildItem -Path "$PSScriptRoot\..\..\..\*.md" -Recurse | Where-Object {$_.DirectoryName -notlike '*node_modules*'} | Group-Object -Property directory @@ -31,7 +31,7 @@ Describe "Verify Markdown Links" { # start all link verification in parallel Foreach($group in $groups) { - Write-Verbose -verbose "starting jobs for $($group.Name) ..." + Write-Verbose -Verbose "starting jobs for $($group.Name) ..." $job = Start-ThreadJob { param([object] $group) foreach($file in $group.Group) @@ -46,13 +46,13 @@ Describe "Verify Markdown Links" { $jobs.add($group.name,$job) } - Write-Verbose -verbose "Getting results ..." + Write-Verbose -Verbose "Getting results ..." # Get the results and verify foreach($key in $jobs.keys) { $job = $jobs.$key $results = Receive-Job -Job $job -Wait - Remove-job -job $Job + Remove-Job -Job $Job foreach($jobResult in $results) { $file = $jobResult.file @@ -85,14 +85,14 @@ Describe "Verify Markdown Links" { if($passes) { - it " should work" -TestCases $passes { + It " should work" -TestCases $passes { noop } } if($trueFailures) { - it " should work" -TestCases $trueFailures { + It " should work" -TestCases $trueFailures { param($url) # there could be multiple reasons why a failure is ok @@ -105,13 +105,13 @@ Describe "Verify Markdown Links" { $prefix = $url.Substring(0,7) # Logging for diagnosability. Azure DevOps sometimes redacts the full url. - Write-Verbose "prefix: '$prefix'" -Verbose + Write-Verbose "prefix: '$prefix'" if($url -match '^http(s)?:') { # If invoke-WebRequest can handle the URL, re-verify, with 6 retries try { - $null = Invoke-WebRequest -uri $url -RetryIntervalSec 10 -MaximumRetryCount 6 + $null = Invoke-WebRequest -Uri $url -RetryIntervalSec 10 -MaximumRetryCount 6 } catch [Microsoft.PowerShell.Commands.HttpResponseException] { @@ -128,7 +128,7 @@ Describe "Verify Markdown Links" { if($verifyFailures) { - it " should work" -TestCases $verifyFailures -Pending { + It " should work" -TestCases $verifyFailures -Pending { } } diff --git a/test/common/markdown/markdown.tests.ps1 b/test/common/markdown/markdown.tests.ps1 new file mode 100644 index 00000000000..ee152b5c703 --- /dev/null +++ b/test/common/markdown/markdown.tests.ps1 @@ -0,0 +1,100 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Import-Module HelpersCommon +$moduleRootFilePath = Split-Path -Path $PSScriptRoot -Parent + +# Identify the repository root path of the resource module +$repoRootPath = (Resolve-Path -LiteralPath (Join-Path $moduleRootFilePath "../..")).ProviderPath +$repoRootPathFound = $false + +Describe 'Common Tests - Validate Markdown Files' -Tag 'CI' { + BeforeAll { + Push-Location $psscriptroot + $skip = $false + $NpmInstalled = "not installed" + if (Get-Command -Name 'yarn' -ErrorAction SilentlyContinue) + { + $NpmInstalled = "Installed" + Write-Verbose -Message "Checking if Gulp is installed. This may take a few moments." -Verbose + start-nativeExecution { yarn } + if(!(Get-Command -Name 'gulp' -ErrorAction SilentlyContinue)) + { + start-nativeExecution { + sudo yarn global add 'gulp@4.0.2' + } + } + if(!(Get-Command -Name 'node' -ErrorAction SilentlyContinue)) + { + throw "node not found" + } + } + if(!(Get-Command -Name 'node' -ErrorAction SilentlyContinue)) + { + <# + On Windows, pre-requisites are missing + For now we will skip, and write a warning. Work to resolve this is tracked in: + https://github.com/PowerShell/PowerShell/issues/3429 + #> + Write-Warning "Node and yarn are required to run this test" + $skip = $true + } + + $mdIssuesPath = Join-Path -Path $PSScriptRoot -ChildPath "markdownissues.txt" + Remove-Item -Path $mdIssuesPath -Force -ErrorAction SilentlyContinue + } + + AfterAll { + Pop-Location + } + + It "Should not have errors in any markdown files" -Skip:$skip { + $NpmInstalled | Should -BeExactly "Installed" + $mdErrors = 0 + Push-Location -Path $PSScriptRoot + try + { + $docsToTest = @( + './.github/*.md' + './README.md' + './demos/python/*.md' + './docker/*.md' + './docs/building/*.md' + './docs/community/*.md' + './docs/host-powershell/*.md' + './docs/cmdlet-example/*.md' + './docs/maintainers/*.md' + './test/powershell/README.md' + './tools/*.md' + './.github/ISSUE_TEMPLATE/*.md' + ) + $filter = ($docsToTest -join ',') + + # Gulp 4 beta is returning non-zero exit code even when there is not an error + Start-NativeExecution { + &"gulp" test-mdsyntax --silent ` + --rootpath $repoRootPath ` + --filter $filter + } -VerboseOutputOnError -IgnoreExitcode + + } + finally + { + Pop-Location + } + + $mdIssuesPath | Should -Exist + + [string[]] $markdownErrors = Get-Content -Path $mdIssuesPath + Remove-Item -Path $mdIssuesPath -Force -ErrorAction SilentlyContinue + + if ($markdownErrors -ne "--EMPTY--") + { + $markdownErrors += ' (See https://github.com/DavidAnson/markdownlint/blob/master/doc/Rules.md for an explanation of the error codes)' + } + + $markdownErrors | Write-Host + + $markdownErrors -join "`n" | Should -BeExactly "--EMPTY--" + } +} diff --git a/test/common/markdown/package.json b/test/common/markdown/package.json new file mode 100644 index 00000000000..f5d23fa8a59 --- /dev/null +++ b/test/common/markdown/package.json @@ -0,0 +1,26 @@ +{ + "name": "powershell.common.markdown.tests", + "private": true, + "version": "1.0.0", + "description": "The PowerShell Common Markdown Tests.", + "main": "gulpfile.js", + "dependencies": { + "gulp": "^4.0.2", + "markdownlint": "^0.20.2", + "through2": "^3.0.1" + }, + "devDependencies": { + "gulp-concat": "^2.6.1", + "gulp-debug": "^4.0.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/PowerShell/PowerShell.git" + }, + "author": "Microsoft Corporation", + "license": "MIT", + "bugs": { + "url": "https://github.com/PowerShell/PowerShell/issues" + }, + "homepage": "https://github.com/PowerShell/PowerShell#readme" +} diff --git a/test/common/markdown/yarn.lock b/test/common/markdown/yarn.lock new file mode 100644 index 00000000000..7b1055e2836 --- /dev/null +++ b/test/common/markdown/yarn.lock @@ -0,0 +1,2337 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +ansi-colors@^1.0.1: + version "1.1.0" + resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-1.1.0.tgz#6374b4dd5d4718ff3ce27a671a3b1cad077132a9" + integrity sha512-SFKX67auSNoVR38N3L+nvsPjOE0bybKTYbkf5tRvushrAPQ9V75huw0ZxBkKVeRU9kqH3d6HA4xTckbwZ4ixmA== + dependencies: + ansi-wrap "^0.1.0" + +ansi-gray@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz#2962cf54ec9792c48510a3deb524436861ef7251" + integrity sha1-KWLPVOyXksSFEKPetSRDaGHvclE= + dependencies: + ansi-wrap "0.1.0" + +ansi-regex@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" + integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= + +ansi-styles@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" + integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== + dependencies: + color-convert "^1.9.0" + +ansi-wrap@0.1.0, ansi-wrap@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz#a82250ddb0015e9a27ca82e82ea603bbfa45efaf" + integrity sha1-qCJQ3bABXponyoLoLqYDu/pF768= + +anymatch@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb" + integrity sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw== + dependencies: + micromatch "^3.1.4" + normalize-path "^2.1.1" + +append-buffer@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/append-buffer/-/append-buffer-1.0.2.tgz#d8220cf466081525efea50614f3de6514dfa58f1" + integrity sha1-2CIM9GYIFSXv6lBhTz3mUU36WPE= + dependencies: + buffer-equal "^1.0.0" + +archy@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40" + integrity sha1-+cjBN1fMHde8N5rHeyxipcKGjEA= + +argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== + dependencies: + sprintf-js "~1.0.2" + +arr-diff@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/arr-diff/-/arr-diff-4.0.0.tgz#d6461074febfec71e7e15235761a329a5dc7c520" + integrity sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA= + +arr-filter@^1.1.1: + version "1.1.2" + resolved "https://registry.yarnpkg.com/arr-filter/-/arr-filter-1.1.2.tgz#43fdddd091e8ef11aa4c45d9cdc18e2dff1711ee" + integrity sha1-Q/3d0JHo7xGqTEXZzcGOLf8XEe4= + dependencies: + make-iterator "^1.0.0" + +arr-flatten@^1.0.1, arr-flatten@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/arr-flatten/-/arr-flatten-1.1.0.tgz#36048bbff4e7b47e136644316c99669ea5ae91f1" + integrity sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg== + +arr-map@^2.0.0, arr-map@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/arr-map/-/arr-map-2.0.2.tgz#3a77345ffc1cf35e2a91825601f9e58f2e24cac4" + integrity sha1-Onc0X/wc814qkYJWAfnljy4kysQ= + dependencies: + make-iterator "^1.0.0" + +arr-union@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/arr-union/-/arr-union-3.1.0.tgz#e39b09aea9def866a8f206e288af63919bae39c4" + integrity sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ= + +array-each@^1.0.0, array-each@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/array-each/-/array-each-1.0.1.tgz#a794af0c05ab1752846ee753a1f211a05ba0c44f" + integrity sha1-p5SvDAWrF1KEbudTofIRoFugxE8= + +array-initial@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/array-initial/-/array-initial-1.1.0.tgz#2fa74b26739371c3947bd7a7adc73be334b3d795" + integrity sha1-L6dLJnOTccOUe9enrcc74zSz15U= + dependencies: + array-slice "^1.0.0" + is-number "^4.0.0" + +array-last@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/array-last/-/array-last-1.3.0.tgz#7aa77073fec565ddab2493f5f88185f404a9d336" + integrity sha512-eOCut5rXlI6aCOS7Z7kCplKRKyiFQ6dHFBem4PwlwKeNFk2/XxTrhRh5T9PyaEWGy/NHTZWbY+nsZlNFJu9rYg== + dependencies: + is-number "^4.0.0" + +array-slice@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-1.1.0.tgz#e368ea15f89bc7069f7ffb89aec3a6c7d4ac22d4" + integrity sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w== + +array-sort@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/array-sort/-/array-sort-1.0.0.tgz#e4c05356453f56f53512a7d1d6123f2c54c0a88a" + integrity sha512-ihLeJkonmdiAsD7vpgN3CRcx2J2S0TiYW+IS/5zHBI7mKUq3ySvBdzzBfD236ubDBQFiiyG3SWCPc+msQ9KoYg== + dependencies: + default-compare "^1.0.0" + get-value "^2.0.6" + kind-of "^5.0.2" + +array-unique@^0.3.2: + version "0.3.2" + resolved "https://registry.yarnpkg.com/array-unique/-/array-unique-0.3.2.tgz#a894b75d4bc4f6cd679ef3244a9fd8f46ae2d428" + integrity sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg= + +assign-symbols@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/assign-symbols/-/assign-symbols-1.0.0.tgz#59667f41fadd4f20ccbc2bb96b8d4f7f78ec0367" + integrity sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c= + +async-done@^1.2.0, async-done@^1.2.2: + version "1.3.2" + resolved "https://registry.yarnpkg.com/async-done/-/async-done-1.3.2.tgz#5e15aa729962a4b07414f528a88cdf18e0b290a2" + integrity sha512-uYkTP8dw2og1tu1nmza1n1CMW0qb8gWWlwqMmLb7MhBVs4BXrFziT6HXUd+/RlRA/i4H9AkofYloUbs1fwMqlw== + dependencies: + end-of-stream "^1.1.0" + once "^1.3.2" + process-nextick-args "^2.0.0" + stream-exhaust "^1.0.1" + +async-each@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf" + integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ== + +async-settle@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/async-settle/-/async-settle-1.0.0.tgz#1d0a914bb02575bec8a8f3a74e5080f72b2c0c6b" + integrity sha1-HQqRS7Aldb7IqPOnTlCA9yssDGs= + dependencies: + async-done "^1.2.2" + +atob@^2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/atob/-/atob-2.1.2.tgz#6d9517eb9e030d2436666651e86bd9f6f13533c9" + integrity sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg== + +bach@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/bach/-/bach-1.2.0.tgz#4b3ce96bf27134f79a1b414a51c14e34c3bd9880" + integrity sha1-Szzpa/JxNPeaG0FKUcFONMO9mIA= + dependencies: + arr-filter "^1.1.1" + arr-flatten "^1.0.1" + arr-map "^2.0.0" + array-each "^1.0.0" + array-initial "^1.0.0" + array-last "^1.1.1" + async-done "^1.2.2" + async-settle "^1.0.0" + now-and-later "^2.0.0" + +balanced-match@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767" + integrity sha1-ibTRmasr7kneFk6gK4nORi1xt2c= + +base@^0.11.1: + version "0.11.2" + resolved "https://registry.yarnpkg.com/base/-/base-0.11.2.tgz#7bde5ced145b6d551a90db87f83c558b4eb48a8f" + integrity sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg== + dependencies: + cache-base "^1.0.1" + class-utils "^0.3.5" + component-emitter "^1.2.1" + define-property "^1.0.0" + isobject "^3.0.1" + mixin-deep "^1.2.0" + pascalcase "^0.1.1" + +binary-extensions@^1.0.0: + version "1.13.1" + resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-1.13.1.tgz#598afe54755b2868a5330d2aff9d4ebb53209b65" + integrity sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw== + +bindings@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + +brace-expansion@^1.1.7: + version "1.1.11" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd" + integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA== + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + +braces@^2.3.1, braces@^2.3.2: + version "2.3.2" + resolved "https://registry.yarnpkg.com/braces/-/braces-2.3.2.tgz#5979fd3f14cd531565e5fa2df1abfff1dfaee729" + integrity sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w== + dependencies: + arr-flatten "^1.1.0" + array-unique "^0.3.2" + extend-shallow "^2.0.1" + fill-range "^4.0.0" + isobject "^3.0.1" + repeat-element "^1.1.2" + snapdragon "^0.8.1" + snapdragon-node "^2.0.1" + split-string "^3.0.2" + to-regex "^3.0.1" + +buffer-equal@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/buffer-equal/-/buffer-equal-1.0.0.tgz#59616b498304d556abd466966b22eeda3eca5fbe" + integrity sha1-WWFrSYME1Var1GaWayLu2j7KX74= + +buffer-from@^1.0.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef" + integrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A== + +cache-base@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/cache-base/-/cache-base-1.0.1.tgz#0a7f46416831c8b662ee36fe4e7c59d76f666ab2" + integrity sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ== + dependencies: + collection-visit "^1.0.0" + component-emitter "^1.2.1" + get-value "^2.0.6" + has-value "^1.0.0" + isobject "^3.0.1" + set-value "^2.0.0" + to-object-path "^0.3.0" + union-value "^1.0.0" + unset-value "^1.0.0" + +camelcase@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a" + integrity sha1-MvxLn82vhF/N9+c7uXysImHwqwo= + +chalk@^2.3.0: + version "2.4.2" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" + integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== + dependencies: + ansi-styles "^3.2.1" + escape-string-regexp "^1.0.5" + supports-color "^5.3.0" + +chokidar@^2.0.0: + version "2.1.8" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-2.1.8.tgz#804b3a7b6a99358c3c5c61e71d8728f041cff917" + integrity sha512-ZmZUazfOzf0Nve7duiCKD23PFSCs4JPoYyccjUFF3aQkQadqBhfzhjkwBH2mNOG9cTBwhamM37EIsIkZw3nRgg== + dependencies: + anymatch "^2.0.0" + async-each "^1.0.1" + braces "^2.3.2" + glob-parent "^3.1.0" + inherits "^2.0.3" + is-binary-path "^1.0.0" + is-glob "^4.0.0" + normalize-path "^3.0.0" + path-is-absolute "^1.0.0" + readdirp "^2.2.1" + upath "^1.1.1" + optionalDependencies: + fsevents "^1.2.7" + +class-utils@^0.3.5: + version "0.3.6" + resolved "https://registry.yarnpkg.com/class-utils/-/class-utils-0.3.6.tgz#f93369ae8b9a7ce02fd41faad0ca83033190c463" + integrity sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg== + dependencies: + arr-union "^3.1.0" + define-property "^0.2.5" + isobject "^3.0.0" + static-extend "^0.1.1" + +cliui@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d" + integrity sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0= + dependencies: + string-width "^1.0.1" + strip-ansi "^3.0.1" + wrap-ansi "^2.0.0" + +clone-buffer@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/clone-buffer/-/clone-buffer-1.0.0.tgz#e3e25b207ac4e701af721e2cb5a16792cac3dc58" + integrity sha1-4+JbIHrE5wGvch4staFnksrD3Fg= + +clone-stats@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/clone-stats/-/clone-stats-1.0.0.tgz#b3782dff8bb5474e18b9b6bf0fdfe782f8777680" + integrity sha1-s3gt/4u1R04Yuba/D9/ngvh3doA= + +clone@^2.1.1: + version "2.1.2" + resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz#1b7f4b9f591f1e8f83670401600345a02887435f" + integrity sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18= + +cloneable-readable@^1.0.0: + version "1.1.3" + resolved "https://registry.yarnpkg.com/cloneable-readable/-/cloneable-readable-1.1.3.tgz#120a00cb053bfb63a222e709f9683ea2e11d8cec" + integrity sha512-2EF8zTQOxYq70Y4XKtorQupqF0m49MBz2/yf5Bj+MHjvpG3Hy7sImifnqD6UA+TKYxeSV+u6qqQPawN5UvnpKQ== + dependencies: + inherits "^2.0.1" + process-nextick-args "^2.0.0" + readable-stream "^2.3.5" + +code-point-at@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" + integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= + +collection-map@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/collection-map/-/collection-map-1.0.0.tgz#aea0f06f8d26c780c2b75494385544b2255af18c" + integrity sha1-rqDwb40mx4DCt1SUOFVEsiVa8Yw= + dependencies: + arr-map "^2.0.2" + for-own "^1.0.0" + make-iterator "^1.0.0" + +collection-visit@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/collection-visit/-/collection-visit-1.0.0.tgz#4bc0373c164bc3291b4d368c829cf1a80a59dca0" + integrity sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA= + dependencies: + map-visit "^1.0.0" + object-visit "^1.0.0" + +color-convert@^1.9.0: + version "1.9.3" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" + integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== + dependencies: + color-name "1.1.3" + +color-name@1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" + integrity sha1-p9BVi9icQveV3UIyj3QIMcpTvCU= + +color-support@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2" + integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg== + +component-emitter@^1.2.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0" + integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg== + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= + +concat-stream@^1.6.0: + version "1.6.2" + resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" + integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== + dependencies: + buffer-from "^1.0.0" + inherits "^2.0.3" + readable-stream "^2.2.2" + typedarray "^0.0.6" + +concat-with-sourcemaps@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/concat-with-sourcemaps/-/concat-with-sourcemaps-1.1.0.tgz#d4ea93f05ae25790951b99e7b3b09e3908a4082e" + integrity sha512-4gEjHJFT9e+2W/77h/DS5SGUgwDaOwprX8L/gl5+3ixnzkVJJsZWDSelmN3Oilw3LNDZjZV0yqH1hLG3k6nghg== + dependencies: + source-map "^0.6.1" + +convert-source-map@^1.5.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-1.7.0.tgz#17a2cb882d7f77d3490585e2ce6c524424a3a442" + integrity sha512-4FJkXzKXEDB1snCFZlLP4gpC3JILicCpGbzG9f9G7tGqGCzETQ2hWPrcinA9oU4wtf2biUaEH5065UnMeR33oA== + dependencies: + safe-buffer "~5.1.1" + +copy-descriptor@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/copy-descriptor/-/copy-descriptor-0.1.1.tgz#676f6eb3c39997c2ee1ac3a924fd6124748f578d" + integrity sha1-Z29us8OZl8LuGsOpJP1hJHSPV40= + +copy-props@^2.0.1: + version "2.0.4" + resolved "https://registry.yarnpkg.com/copy-props/-/copy-props-2.0.4.tgz#93bb1cadfafd31da5bb8a9d4b41f471ec3a72dfe" + integrity sha512-7cjuUME+p+S3HZlbllgsn2CDwS+5eCCX16qBgNC4jgSTf49qR1VKy/Zhl400m0IQXl/bPGEVqncgUUMjrr4s8A== + dependencies: + each-props "^1.3.0" + is-plain-object "^2.0.1" + +core-util-is@~1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" + integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= + +d@1, d@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/d/-/d-1.0.1.tgz#8698095372d58dbee346ffd0c7093f99f8f9eb5a" + integrity sha512-m62ShEObQ39CfralilEQRjH6oAMtNCV1xJyEx5LpRYUVN+EviphDgUc/F3hnYbADmkiNs67Y+3ylmlG7Lnu+FA== + dependencies: + es5-ext "^0.10.50" + type "^1.0.1" + +debug@^2.2.0, debug@^2.3.3: + version "2.6.9" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" + integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== + dependencies: + ms "2.0.0" + +decamelize@^1.1.1: + version "1.2.0" + resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290" + integrity sha1-9lNNFRSCabIDUue+4m9QH5oZEpA= + +decode-uri-component@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/decode-uri-component/-/decode-uri-component-0.2.0.tgz#eb3913333458775cb84cd1a1fae062106bb87545" + integrity sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU= + +default-compare@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/default-compare/-/default-compare-1.0.0.tgz#cb61131844ad84d84788fb68fd01681ca7781a2f" + integrity sha512-QWfXlM0EkAbqOCbD/6HjdwT19j7WCkMyiRhWilc4H9/5h/RzTF9gv5LYh1+CmDV5d1rki6KAWLtQale0xt20eQ== + dependencies: + kind-of "^5.0.2" + +default-resolution@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/default-resolution/-/default-resolution-2.0.0.tgz#bcb82baa72ad79b426a76732f1a81ad6df26d684" + integrity sha1-vLgrqnKtebQmp2cy8aga1t8m1oQ= + +define-properties@^1.1.2: + version "1.1.3" + resolved "https://registry.yarnpkg.com/define-properties/-/define-properties-1.1.3.tgz#cf88da6cbee26fe6db7094f61d870cbd84cee9f1" + integrity sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ== + dependencies: + object-keys "^1.0.12" + +define-property@^0.2.5: + version "0.2.5" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-0.2.5.tgz#c35b1ef918ec3c990f9a5bc57be04aacec5c8116" + integrity sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY= + dependencies: + is-descriptor "^0.1.0" + +define-property@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-1.0.0.tgz#769ebaaf3f4a63aad3af9e8d304c9bbe79bfb0e6" + integrity sha1-dp66rz9KY6rTr56NMEybvnm/sOY= + dependencies: + is-descriptor "^1.0.0" + +define-property@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/define-property/-/define-property-2.0.2.tgz#d459689e8d654ba77e02a817f8710d702cb16e9d" + integrity sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ== + dependencies: + is-descriptor "^1.0.2" + isobject "^3.0.1" + +detect-file@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz#f0d66d03672a825cb1b73bdb3fe62310c8e552b7" + integrity sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc= + +duplexify@^3.6.0: + version "3.7.1" + resolved "https://registry.yarnpkg.com/duplexify/-/duplexify-3.7.1.tgz#2a4df5317f6ccfd91f86d6fd25d8d8a103b88309" + integrity sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g== + dependencies: + end-of-stream "^1.0.0" + inherits "^2.0.1" + readable-stream "^2.0.0" + stream-shift "^1.0.0" + +each-props@^1.3.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/each-props/-/each-props-1.3.2.tgz#ea45a414d16dd5cfa419b1a81720d5ca06892333" + integrity sha512-vV0Hem3zAGkJAyU7JSjixeU66rwdynTAa1vofCrSA5fEln+m67Az9CcnkVD776/fsN/UjIWmBDoNRS6t6G9RfA== + dependencies: + is-plain-object "^2.0.1" + object.defaults "^1.1.0" + +end-of-stream@^1.0.0, end-of-stream@^1.1.0: + version "1.4.4" + resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" + integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== + dependencies: + once "^1.4.0" + +entities@~2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.2.tgz#ac74db0bba8d33808bbf36809c3a5c3683531436" + integrity sha512-dmD3AvJQBUjKpcNkoqr+x+IF0SdRtPz9Vk0uTy4yWqga9ibB6s4v++QFWNohjiUGoMlF552ZvNyXDxz5iW0qmw== + +error-ex@^1.2.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" + integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== + dependencies: + is-arrayish "^0.2.1" + +es5-ext@^0.10.35, es5-ext@^0.10.46, es5-ext@^0.10.50: + version "0.10.53" + resolved "https://registry.yarnpkg.com/es5-ext/-/es5-ext-0.10.53.tgz#93c5a3acfdbef275220ad72644ad02ee18368de1" + integrity sha512-Xs2Stw6NiNHWypzRTY1MtaG/uJlwCk8kH81920ma8mvN8Xq1gsfhZvpkImLQArw8AHnv8MT2I45J3c0R8slE+Q== + dependencies: + es6-iterator "~2.0.3" + es6-symbol "~3.1.3" + next-tick "~1.0.0" + +es6-iterator@^2.0.1, es6-iterator@^2.0.3, es6-iterator@~2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/es6-iterator/-/es6-iterator-2.0.3.tgz#a7de889141a05a94b0854403b2d0a0fbfa98f3b7" + integrity sha1-p96IkUGgWpSwhUQDstCg+/qY87c= + dependencies: + d "1" + es5-ext "^0.10.35" + es6-symbol "^3.1.1" + +es6-symbol@^3.1.1, es6-symbol@~3.1.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/es6-symbol/-/es6-symbol-3.1.3.tgz#bad5d3c1bcdac28269f4cb331e431c78ac705d18" + integrity sha512-NJ6Yn3FuDinBaBRWl/q5X/s4koRHBrgKAu+yGI6JCBeiu3qrcbJhwT2GeR/EXVfylRk8dpQVJoLEFhK+Mu31NA== + dependencies: + d "^1.0.1" + ext "^1.1.2" + +es6-weak-map@^2.0.1: + version "2.0.3" + resolved "https://registry.yarnpkg.com/es6-weak-map/-/es6-weak-map-2.0.3.tgz#b6da1f16cc2cc0d9be43e6bdbfc5e7dfcdf31d53" + integrity sha512-p5um32HOTO1kP+w7PRnB+5lQ43Z6muuMuIMffvDN8ZB4GcnjLBV6zGStpbASIMk4DCAvEaamhe2zhyCb/QXXsA== + dependencies: + d "1" + es5-ext "^0.10.46" + es6-iterator "^2.0.3" + es6-symbol "^3.1.1" + +escape-string-regexp@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" + integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= + +expand-brackets@^2.1.4: + version "2.1.4" + resolved "https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-2.1.4.tgz#b77735e315ce30f6b6eff0f83b04151a22449622" + integrity sha1-t3c14xXOMPa27/D4OwQVGiJEliI= + dependencies: + debug "^2.3.3" + define-property "^0.2.5" + extend-shallow "^2.0.1" + posix-character-classes "^0.1.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +expand-tilde@^2.0.0, expand-tilde@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/expand-tilde/-/expand-tilde-2.0.2.tgz#97e801aa052df02454de46b02bf621642cdc8502" + integrity sha1-l+gBqgUt8CRU3kawK/YhZCzchQI= + dependencies: + homedir-polyfill "^1.0.1" + +ext@^1.1.2: + version "1.4.0" + resolved "https://registry.yarnpkg.com/ext/-/ext-1.4.0.tgz#89ae7a07158f79d35517882904324077e4379244" + integrity sha512-Key5NIsUxdqKg3vIsdw9dSuXpPCQ297y6wBjL30edxwPgt2E44WcWBZey/ZvUc6sERLTxKdyCu4gZFmUbk1Q7A== + dependencies: + type "^2.0.0" + +extend-shallow@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-2.0.1.tgz#51af7d614ad9a9f610ea1bafbb989d6b1c56890f" + integrity sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8= + dependencies: + is-extendable "^0.1.0" + +extend-shallow@^3.0.0, extend-shallow@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/extend-shallow/-/extend-shallow-3.0.2.tgz#26a71aaf073b39fb2127172746131c2704028db8" + integrity sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg= + dependencies: + assign-symbols "^1.0.0" + is-extendable "^1.0.1" + +extend@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" + integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== + +extglob@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/extglob/-/extglob-2.0.4.tgz#ad00fe4dc612a9232e8718711dc5cb5ab0285543" + integrity sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw== + dependencies: + array-unique "^0.3.2" + define-property "^1.0.0" + expand-brackets "^2.1.4" + extend-shallow "^2.0.1" + fragment-cache "^0.2.1" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +fancy-log@^1.3.2: + version "1.3.3" + resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.3.tgz#dbc19154f558690150a23953a0adbd035be45fc7" + integrity sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw== + dependencies: + ansi-gray "^0.1.1" + color-support "^1.1.3" + parse-node-version "^1.0.0" + time-stamp "^1.0.0" + +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + +fill-range@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-4.0.0.tgz#d544811d428f98eb06a63dc402d2403c328c38f7" + integrity sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc= + dependencies: + extend-shallow "^2.0.1" + is-number "^3.0.0" + repeat-string "^1.6.1" + to-regex-range "^2.1.0" + +find-up@^1.0.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f" + integrity sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8= + dependencies: + path-exists "^2.0.0" + pinkie-promise "^2.0.0" + +findup-sync@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-2.0.0.tgz#9326b1488c22d1a6088650a86901b2d9a90a2cbc" + integrity sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw= + dependencies: + detect-file "^1.0.0" + is-glob "^3.1.0" + micromatch "^3.0.4" + resolve-dir "^1.0.1" + +findup-sync@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-3.0.0.tgz#17b108f9ee512dfb7a5c7f3c8b27ea9e1a9c08d1" + integrity sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg== + dependencies: + detect-file "^1.0.0" + is-glob "^4.0.0" + micromatch "^3.0.4" + resolve-dir "^1.0.1" + +fined@^1.0.1: + version "1.2.0" + resolved "https://registry.yarnpkg.com/fined/-/fined-1.2.0.tgz#d00beccf1aa2b475d16d423b0238b713a2c4a37b" + integrity sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng== + dependencies: + expand-tilde "^2.0.2" + is-plain-object "^2.0.3" + object.defaults "^1.1.0" + object.pick "^1.2.0" + parse-filepath "^1.0.1" + +flagged-respawn@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/flagged-respawn/-/flagged-respawn-1.0.1.tgz#e7de6f1279ddd9ca9aac8a5971d618606b3aab41" + integrity sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q== + +flush-write-stream@^1.0.2: + version "1.1.1" + resolved "https://registry.yarnpkg.com/flush-write-stream/-/flush-write-stream-1.1.1.tgz#8dd7d873a1babc207d94ead0c2e0e44276ebf2e8" + integrity sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w== + dependencies: + inherits "^2.0.3" + readable-stream "^2.3.6" + +for-in@^1.0.1, for-in@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80" + integrity sha1-gQaNKVqBQuwKxybG4iAMMPttXoA= + +for-own@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/for-own/-/for-own-1.0.0.tgz#c63332f415cedc4b04dbfe70cf836494c53cb44b" + integrity sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs= + dependencies: + for-in "^1.0.1" + +fragment-cache@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/fragment-cache/-/fragment-cache-0.2.1.tgz#4290fad27f13e89be7f33799c6bc5a0abfff0d19" + integrity sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk= + dependencies: + map-cache "^0.2.2" + +fs-mkdirp-stream@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz#0b7815fc3201c6a69e14db98ce098c16935259eb" + integrity sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes= + dependencies: + graceful-fs "^4.1.11" + through2 "^2.0.3" + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8= + +fsevents@^1.2.7: + version "1.2.13" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.13.tgz#f325cb0455592428bcf11b383370ef70e3bfcc38" + integrity sha512-oWb1Z6mkHIskLzEJ/XWX0srkpkTQ7vaopMQkyaEIoq0fmtFVxOthb8cCxeT+p3ynTdkk/RZwbgG4brR5BeWECw== + dependencies: + bindings "^1.5.0" + nan "^2.12.1" + +function-bind@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" + integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A== + +get-caller-file@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.3.tgz#f978fa4c90d1dfe7ff2d6beda2a515e713bdcf4a" + integrity sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w== + +get-own-enumerable-property-symbols@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/get-own-enumerable-property-symbols/-/get-own-enumerable-property-symbols-3.0.2.tgz#b5fde77f22cbe35f390b4e089922c50bce6ef664" + integrity sha512-I0UBV/XOz1XkIJHEUDMZAbzCThU/H8DxmSfmdGcKPnVhu2VfFqr34jr9777IyaTYvxjedWhqVIilEDsCdP5G6g== + +get-value@^2.0.3, get-value@^2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28" + integrity sha1-3BXKHGcjh8p2vTesCjlbogQqLCg= + +glob-parent@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-3.1.0.tgz#9e6af6299d8d3bd2bd40430832bd113df906c5ae" + integrity sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4= + dependencies: + is-glob "^3.1.0" + path-dirname "^1.0.0" + +glob-stream@^6.1.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/glob-stream/-/glob-stream-6.1.0.tgz#7045c99413b3eb94888d83ab46d0b404cc7bdde4" + integrity sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ= + dependencies: + extend "^3.0.0" + glob "^7.1.1" + glob-parent "^3.1.0" + is-negated-glob "^1.0.0" + ordered-read-streams "^1.0.0" + pumpify "^1.3.5" + readable-stream "^2.1.5" + remove-trailing-separator "^1.0.1" + to-absolute-glob "^2.0.0" + unique-stream "^2.0.2" + +glob-watcher@^5.0.3: + version "5.0.3" + resolved "https://registry.yarnpkg.com/glob-watcher/-/glob-watcher-5.0.3.tgz#88a8abf1c4d131eb93928994bc4a593c2e5dd626" + integrity sha512-8tWsULNEPHKQ2MR4zXuzSmqbdyV5PtwwCaWSGQ1WwHsJ07ilNeN1JB8ntxhckbnpSHaf9dXFUHzIWvm1I13dsg== + dependencies: + anymatch "^2.0.0" + async-done "^1.2.0" + chokidar "^2.0.0" + is-negated-glob "^1.0.0" + just-debounce "^1.0.0" + object.defaults "^1.1.0" + +glob@^7.1.1: + version "7.1.6" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" + integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.0.4" + once "^1.3.0" + path-is-absolute "^1.0.0" + +global-modules@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/global-modules/-/global-modules-1.0.0.tgz#6d770f0eb523ac78164d72b5e71a8877265cc3ea" + integrity sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg== + dependencies: + global-prefix "^1.0.1" + is-windows "^1.0.1" + resolve-dir "^1.0.0" + +global-prefix@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-1.0.2.tgz#dbf743c6c14992593c655568cb66ed32c0122ebe" + integrity sha1-2/dDxsFJklk8ZVVoy2btMsASLr4= + dependencies: + expand-tilde "^2.0.2" + homedir-polyfill "^1.0.1" + ini "^1.3.4" + is-windows "^1.0.1" + which "^1.2.14" + +glogg@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.2.tgz#2d7dd702beda22eb3bffadf880696da6d846313f" + integrity sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA== + dependencies: + sparkles "^1.0.0" + +graceful-fs@^4.0.0, graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6: + version "4.2.4" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" + integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== + +gulp-cli@^2.2.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/gulp-cli/-/gulp-cli-2.2.1.tgz#376e427661b7996430a89d71c15df75defa3360a" + integrity sha512-yEMxrXqY8mJFlaauFQxNrCpzWJThu0sH1sqlToaTOT063Hub9s/Nt2C+GSLe6feQ/IMWrHvGOOsyES7CQc9O+A== + dependencies: + ansi-colors "^1.0.1" + archy "^1.0.0" + array-sort "^1.0.0" + color-support "^1.1.3" + concat-stream "^1.6.0" + copy-props "^2.0.1" + fancy-log "^1.3.2" + gulplog "^1.0.0" + interpret "^1.1.0" + isobject "^3.0.1" + liftoff "^3.1.0" + matchdep "^2.0.0" + mute-stdout "^1.0.0" + pretty-hrtime "^1.0.0" + replace-homedir "^1.0.0" + semver-greatest-satisfied-range "^1.1.0" + v8flags "^3.0.1" + yargs "^7.1.0" + +gulp-concat@^2.6.1: + version "2.6.1" + resolved "https://registry.yarnpkg.com/gulp-concat/-/gulp-concat-2.6.1.tgz#633d16c95d88504628ad02665663cee5a4793353" + integrity sha1-Yz0WyV2IUEYorQJmVmPO5aR5M1M= + dependencies: + concat-with-sourcemaps "^1.0.0" + through2 "^2.0.0" + vinyl "^2.0.0" + +gulp-debug@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/gulp-debug/-/gulp-debug-4.0.0.tgz#036f9539c3fb6af720e01a9ea5c195fc73f29d5b" + integrity sha512-cn/GhMD2nVZCVxAl5vWao4/dcoZ8wUJ8w3oqTvQaGDmC1vT7swNOEbhQTWJp+/otKePT64aENcqAQXDcdj5H1g== + dependencies: + chalk "^2.3.0" + fancy-log "^1.3.2" + plur "^3.0.0" + stringify-object "^3.0.0" + through2 "^2.0.0" + tildify "^1.1.2" + +gulp@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.2.tgz#543651070fd0f6ab0a0650c6a3e6ff5a7cb09caa" + integrity sha512-dvEs27SCZt2ibF29xYgmnwwCYZxdxhQ/+LFWlbAW8y7jt68L/65402Lz3+CKy0Ov4rOs+NERmDq7YlZaDqUIfA== + dependencies: + glob-watcher "^5.0.3" + gulp-cli "^2.2.0" + undertaker "^1.2.1" + vinyl-fs "^3.0.0" + +gulplog@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz#e28c4d45d05ecbbed818363ce8f9c5926229ffe5" + integrity sha1-4oxNRdBey77YGDY86PnFkmIp/+U= + dependencies: + glogg "^1.0.0" + +has-flag@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" + integrity sha1-tdRU3CGZriJWmfNGfloH87lVuv0= + +has-symbols@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.1.tgz#9f5214758a44196c406d9bd76cebf81ec2dd31e8" + integrity sha512-PLcsoqu++dmEIZB+6totNFKq/7Do+Z0u4oT0zKOJNl3lYK6vGwwu2hjHs+68OEZbTjiUE9bgOABXbP/GvrS0Kg== + +has-value@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" + integrity sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8= + dependencies: + get-value "^2.0.3" + has-values "^0.1.4" + isobject "^2.0.0" + +has-value@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-value/-/has-value-1.0.0.tgz#18b281da585b1c5c51def24c930ed29a0be6b177" + integrity sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc= + dependencies: + get-value "^2.0.6" + has-values "^1.0.0" + isobject "^3.0.0" + +has-values@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-0.1.4.tgz#6d61de95d91dfca9b9a02089ad384bff8f62b771" + integrity sha1-bWHeldkd/Km5oCCJrThL/49it3E= + +has-values@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/has-values/-/has-values-1.0.0.tgz#95b0b63fec2146619a6fe57fe75628d5a39efe4f" + integrity sha1-lbC2P+whRmGab+V/51Yo1aOe/k8= + dependencies: + is-number "^3.0.0" + kind-of "^4.0.0" + +homedir-polyfill@^1.0.1: + version "1.0.3" + resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz#743298cef4e5af3e194161fbadcc2151d3a058e8" + integrity sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA== + dependencies: + parse-passwd "^1.0.0" + +hosted-git-info@^2.1.4: + version "2.8.8" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz#7539bd4bc1e0e0a895815a2e0262420b12858488" + integrity sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg== + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + integrity sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk= + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@~2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +ini@^1.3.4: + version "1.3.5" + resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.5.tgz#eee25f56db1c9ec6085e0c22778083f596abf927" + integrity sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw== + +interpret@^1.1.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.2.0.tgz#d5061a6224be58e8083985f5014d844359576296" + integrity sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw== + +invert-kv@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6" + integrity sha1-EEqOSqym09jNFXqO+L+rLXo//bY= + +irregular-plurals@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-2.0.0.tgz#39d40f05b00f656d0b7fa471230dd3b714af2872" + integrity sha512-Y75zBYLkh0lJ9qxeHlMjQ7bSbyiSqNW/UOPWDmzC7cXskL1hekSITh1Oc6JV0XCWWZ9DE8VYSB71xocLk3gmGw== + +is-absolute@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-absolute/-/is-absolute-1.0.0.tgz#395e1ae84b11f26ad1795e73c17378e48a301576" + integrity sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA== + dependencies: + is-relative "^1.0.0" + is-windows "^1.0.1" + +is-accessor-descriptor@^0.1.6: + version "0.1.6" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz#a9e12cb3ae8d876727eeef3843f8a0897b5c98d6" + integrity sha1-qeEss66Nh2cn7u84Q/igiXtcmNY= + dependencies: + kind-of "^3.0.2" + +is-accessor-descriptor@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz#169c2f6d3df1f992618072365c9b0ea1f6878656" + integrity sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ== + dependencies: + kind-of "^6.0.0" + +is-arrayish@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0= + +is-binary-path@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" + integrity sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg= + dependencies: + binary-extensions "^1.0.0" + +is-buffer@^1.1.5: + version "1.1.6" + resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" + integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== + +is-data-descriptor@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz#0b5ee648388e2c860282e793f1856fec3f301b56" + integrity sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y= + dependencies: + kind-of "^3.0.2" + +is-data-descriptor@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz#d84876321d0e7add03990406abbbbd36ba9268c7" + integrity sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ== + dependencies: + kind-of "^6.0.0" + +is-descriptor@^0.1.0: + version "0.1.6" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-0.1.6.tgz#366d8240dde487ca51823b1ab9f07a10a78251ca" + integrity sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg== + dependencies: + is-accessor-descriptor "^0.1.6" + is-data-descriptor "^0.1.4" + kind-of "^5.0.0" + +is-descriptor@^1.0.0, is-descriptor@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-descriptor/-/is-descriptor-1.0.2.tgz#3b159746a66604b04f8c81524ba365c5f14d86ec" + integrity sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg== + dependencies: + is-accessor-descriptor "^1.0.0" + is-data-descriptor "^1.0.0" + kind-of "^6.0.2" + +is-extendable@^0.1.0, is-extendable@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-0.1.1.tgz#62b110e289a471418e3ec36a617d472e301dfc89" + integrity sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik= + +is-extendable@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-extendable/-/is-extendable-1.0.1.tgz#a7470f9e426733d81bd81e1155264e3a3507cab4" + integrity sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA== + dependencies: + is-plain-object "^2.0.4" + +is-extglob@^2.1.0, is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= + +is-fullwidth-code-point@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" + integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= + dependencies: + number-is-nan "^1.0.0" + +is-glob@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-3.1.0.tgz#7ba5ae24217804ac70707b96922567486cc3e84a" + integrity sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo= + dependencies: + is-extglob "^2.1.0" + +is-glob@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.1.tgz#7567dbe9f2f5e2467bc77ab83c4a29482407a5dc" + integrity sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg== + dependencies: + is-extglob "^2.1.1" + +is-negated-glob@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-negated-glob/-/is-negated-glob-1.0.0.tgz#6910bca5da8c95e784b5751b976cf5a10fee36d2" + integrity sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI= + +is-number@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-3.0.0.tgz#24fd6201a4782cf50561c810276afc7d12d71195" + integrity sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU= + dependencies: + kind-of "^3.0.2" + +is-number@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-4.0.0.tgz#0026e37f5454d73e356dfe6564699867c6a7f0ff" + integrity sha512-rSklcAIlf1OmFdyAqbnWTLVelsQ58uvZ66S/ZyawjWqIviTWCjg2PzVGw8WUA+nNuPTqb4wgA+NszrJ+08LlgQ== + +is-obj@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/is-obj/-/is-obj-1.0.1.tgz#3e4729ac1f5fde025cd7d83a896dab9f4f67db0f" + integrity sha1-PkcprB9f3gJc19g6iW2rn09n2w8= + +is-plain-object@^2.0.1, is-plain-object@^2.0.3, is-plain-object@^2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-2.0.4.tgz#2c163b3fafb1b606d9d17928f05c2a1c38e07677" + integrity sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og== + dependencies: + isobject "^3.0.1" + +is-regexp@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" + integrity sha1-/S2INUXEa6xaYz57mgnof6LLUGk= + +is-relative@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-relative/-/is-relative-1.0.0.tgz#a1bb6935ce8c5dba1e8b9754b9b2dcc020e2260d" + integrity sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA== + dependencies: + is-unc-path "^1.0.0" + +is-unc-path@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-unc-path/-/is-unc-path-1.0.0.tgz#d731e8898ed090a12c352ad2eaed5095ad322c9d" + integrity sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ== + dependencies: + unc-path-regex "^0.1.2" + +is-utf8@^0.2.0, is-utf8@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72" + integrity sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI= + +is-valid-glob@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-valid-glob/-/is-valid-glob-1.0.0.tgz#29bf3eff701be2d4d315dbacc39bc39fe8f601aa" + integrity sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao= + +is-windows@^1.0.1, is-windows@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-windows/-/is-windows-1.0.2.tgz#d1850eb9791ecd18e6182ce12a30f396634bb19d" + integrity sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA== + +isarray@1.0.0, isarray@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11" + integrity sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE= + +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha1-6PvzdNxVb/iUehDcsFctYz8s+hA= + +isobject@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-2.1.0.tgz#f065561096a3f1da2ef46272f815c840d87e0c89" + integrity sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk= + dependencies: + isarray "1.0.0" + +isobject@^3.0.0, isobject@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/isobject/-/isobject-3.0.1.tgz#4e431e92b11a9731636aa1f9c8d1ccbcfdab78df" + integrity sha1-TkMekrEalzFjaqH5yNHMvP2reN8= + +json-stable-stringify-without-jsonify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" + integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= + +just-debounce@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/just-debounce/-/just-debounce-1.0.0.tgz#87fccfaeffc0b68cd19d55f6722943f929ea35ea" + integrity sha1-h/zPrv/AtozRnVX2cilD+SnqNeo= + +kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: + version "3.2.2" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" + integrity sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ= + dependencies: + is-buffer "^1.1.5" + +kind-of@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-4.0.0.tgz#20813df3d712928b207378691a45066fae72dd57" + integrity sha1-IIE989cSkosgc3hpGkUGb65y3Vc= + dependencies: + is-buffer "^1.1.5" + +kind-of@^5.0.0, kind-of@^5.0.2: + version "5.1.0" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" + integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== + +kind-of@^6.0.0, kind-of@^6.0.2: + version "6.0.3" + resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" + integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== + +last-run@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/last-run/-/last-run-1.1.1.tgz#45b96942c17b1c79c772198259ba943bebf8ca5b" + integrity sha1-RblpQsF7HHnHchmCWbqUO+v4yls= + dependencies: + default-resolution "^2.0.0" + es6-weak-map "^2.0.1" + +lazystream@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz#f6995fe0f820392f61396be89462407bb77168e4" + integrity sha1-9plf4PggOS9hOWvolGJAe7dxaOQ= + dependencies: + readable-stream "^2.0.5" + +lcid@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835" + integrity sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU= + dependencies: + invert-kv "^1.0.0" + +lead@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/lead/-/lead-1.0.0.tgz#6f14f99a37be3a9dd784f5495690e5903466ee42" + integrity sha1-bxT5mje+Op3XhPVJVpDlkDRm7kI= + dependencies: + flush-write-stream "^1.0.2" + +liftoff@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/liftoff/-/liftoff-3.1.0.tgz#c9ba6081f908670607ee79062d700df062c52ed3" + integrity sha512-DlIPlJUkCV0Ips2zf2pJP0unEoT1kwYhiiPUGF3s/jtxTCjziNLoiVVh+jqWOWeFi6mmwQ5fNxvAUyPad4Dfog== + dependencies: + extend "^3.0.0" + findup-sync "^3.0.0" + fined "^1.0.1" + flagged-respawn "^1.0.0" + is-plain-object "^2.0.4" + object.map "^1.0.0" + rechoir "^0.6.2" + resolve "^1.1.7" + +linkify-it@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.2.0.tgz#e3b54697e78bf915c70a38acd78fd09e0058b1cf" + integrity sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw== + dependencies: + uc.micro "^1.0.1" + +load-json-file@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0" + integrity sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA= + dependencies: + graceful-fs "^4.1.2" + parse-json "^2.2.0" + pify "^2.0.0" + pinkie-promise "^2.0.0" + strip-bom "^2.0.0" + +make-iterator@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/make-iterator/-/make-iterator-1.0.1.tgz#29b33f312aa8f547c4a5e490f56afcec99133ad6" + integrity sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw== + dependencies: + kind-of "^6.0.2" + +map-cache@^0.2.0, map-cache@^0.2.2: + version "0.2.2" + resolved "https://registry.yarnpkg.com/map-cache/-/map-cache-0.2.2.tgz#c32abd0bd6525d9b051645bb4f26ac5dc98a0dbf" + integrity sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8= + +map-visit@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/map-visit/-/map-visit-1.0.0.tgz#ecdca8f13144e660f1b5bd41f12f3479d98dfb8f" + integrity sha1-7Nyo8TFE5mDxtb1B8S80edmN+48= + dependencies: + object-visit "^1.0.0" + +markdown-it@10.0.0: + version "10.0.0" + resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-10.0.0.tgz#abfc64f141b1722d663402044e43927f1f50a8dc" + integrity sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg== + dependencies: + argparse "^1.0.7" + entities "~2.0.0" + linkify-it "^2.0.0" + mdurl "^1.0.1" + uc.micro "^1.0.5" + +markdownlint@^0.20.2: + version "0.20.3" + resolved "https://registry.yarnpkg.com/markdownlint/-/markdownlint-0.20.3.tgz#6f56d3e16d990af79d42e58bd2849f70b3358595" + integrity sha512-J93s59tGvSFvAPWVUtEgxqPI0CHayTx1Z8poj1/4UJAquHGPIruWRMurkRldiNbgBiaQ4OOt15rHZbFfU6u05A== + dependencies: + markdown-it "10.0.0" + +matchdep@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/matchdep/-/matchdep-2.0.0.tgz#c6f34834a0d8dbc3b37c27ee8bbcb27c7775582e" + integrity sha1-xvNINKDY28OzfCfui7yyfHd1WC4= + dependencies: + findup-sync "^2.0.0" + micromatch "^3.0.4" + resolve "^1.4.0" + stack-trace "0.0.10" + +mdurl@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" + integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= + +micromatch@^3.0.4, micromatch@^3.1.10, micromatch@^3.1.4: + version "3.1.10" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-3.1.10.tgz#70859bc95c9840952f359a068a3fc49f9ecfac23" + integrity sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg== + dependencies: + arr-diff "^4.0.0" + array-unique "^0.3.2" + braces "^2.3.1" + define-property "^2.0.2" + extend-shallow "^3.0.2" + extglob "^2.0.4" + fragment-cache "^0.2.1" + kind-of "^6.0.2" + nanomatch "^1.2.9" + object.pick "^1.3.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.2" + +minimatch@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083" + integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA== + dependencies: + brace-expansion "^1.1.7" + +mixin-deep@^1.2.0: + version "1.3.2" + resolved "https://registry.yarnpkg.com/mixin-deep/-/mixin-deep-1.3.2.tgz#1120b43dc359a785dce65b55b82e257ccf479566" + integrity sha512-WRoDn//mXBiJ1H40rqa3vH0toePwSsGb45iInWlTySa+Uu4k3tYUSxa2v1KqAiLtvlrSzaExqS1gtk96A9zvEA== + dependencies: + for-in "^1.0.2" + is-extendable "^1.0.1" + +ms@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g= + +mute-stdout@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/mute-stdout/-/mute-stdout-1.0.1.tgz#acb0300eb4de23a7ddeec014e3e96044b3472331" + integrity sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg== + +nan@^2.12.1: + version "2.14.1" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.14.1.tgz#d7be34dfa3105b91494c3147089315eff8874b01" + integrity sha512-isWHgVjnFjh2x2yuJ/tj3JbwoHu3UC2dX5G/88Cm24yB6YopVgxvBObDY7n5xW6ExmFhJpSEQqFPvq9zaXc8Jw== + +nanomatch@^1.2.9: + version "1.2.13" + resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119" + integrity sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA== + dependencies: + arr-diff "^4.0.0" + array-unique "^0.3.2" + define-property "^2.0.2" + extend-shallow "^3.0.2" + fragment-cache "^0.2.1" + is-windows "^1.0.2" + kind-of "^6.0.2" + object.pick "^1.3.0" + regex-not "^1.0.0" + snapdragon "^0.8.1" + to-regex "^3.0.1" + +next-tick@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/next-tick/-/next-tick-1.0.0.tgz#ca86d1fe8828169b0120208e3dc8424b9db8342c" + integrity sha1-yobR/ogoFpsBICCOPchCS524NCw= + +normalize-package-data@^2.3.2: + version "2.5.0" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" + integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== + dependencies: + hosted-git-info "^2.1.4" + resolve "^1.10.0" + semver "2 || 3 || 4 || 5" + validate-npm-package-license "^3.0.1" + +normalize-path@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9" + integrity sha1-GrKLVW4Zg2Oowab35vogE3/mrtk= + dependencies: + remove-trailing-separator "^1.0.1" + +normalize-path@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" + integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== + +now-and-later@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/now-and-later/-/now-and-later-2.0.1.tgz#8e579c8685764a7cc02cb680380e94f43ccb1f7c" + integrity sha512-KGvQ0cB70AQfg107Xvs/Fbu+dGmZoTRJp2TaPwcwQm3/7PteUyN2BCgk8KBMPGBUXZdVwyWS8fDCGFygBm19UQ== + dependencies: + once "^1.3.2" + +number-is-nan@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" + integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= + +object-copy@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/object-copy/-/object-copy-0.1.0.tgz#7e7d858b781bd7c991a41ba975ed3812754e998c" + integrity sha1-fn2Fi3gb18mRpBupde04EnVOmYw= + dependencies: + copy-descriptor "^0.1.0" + define-property "^0.2.5" + kind-of "^3.0.3" + +object-keys@^1.0.11, object-keys@^1.0.12: + version "1.1.1" + resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" + integrity sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA== + +object-visit@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/object-visit/-/object-visit-1.0.1.tgz#f79c4493af0c5377b59fe39d395e41042dd045bb" + integrity sha1-95xEk68MU3e1n+OdOV5BBC3QRbs= + dependencies: + isobject "^3.0.0" + +object.assign@^4.0.4, object.assign@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/object.assign/-/object.assign-4.1.0.tgz#968bf1100d7956bb3ca086f006f846b3bc4008da" + integrity sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w== + dependencies: + define-properties "^1.1.2" + function-bind "^1.1.1" + has-symbols "^1.0.0" + object-keys "^1.0.11" + +object.defaults@^1.0.0, object.defaults@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/object.defaults/-/object.defaults-1.1.0.tgz#3a7f868334b407dea06da16d88d5cd29e435fecf" + integrity sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8= + dependencies: + array-each "^1.0.1" + array-slice "^1.0.0" + for-own "^1.0.0" + isobject "^3.0.0" + +object.map@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/object.map/-/object.map-1.0.1.tgz#cf83e59dc8fcc0ad5f4250e1f78b3b81bd801d37" + integrity sha1-z4Plncj8wK1fQlDh94s7gb2AHTc= + dependencies: + for-own "^1.0.0" + make-iterator "^1.0.0" + +object.pick@^1.2.0, object.pick@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/object.pick/-/object.pick-1.3.0.tgz#87a10ac4c1694bd2e1cbf53591a66141fb5dd747" + integrity sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c= + dependencies: + isobject "^3.0.1" + +object.reduce@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/object.reduce/-/object.reduce-1.0.1.tgz#6fe348f2ac7fa0f95ca621226599096825bb03ad" + integrity sha1-b+NI8qx/oPlcpiEiZZkJaCW7A60= + dependencies: + for-own "^1.0.0" + make-iterator "^1.0.0" + +once@^1.3.0, once@^1.3.1, once@^1.3.2, once@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= + dependencies: + wrappy "1" + +ordered-read-streams@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz#77c0cb37c41525d64166d990ffad7ec6a0e1363e" + integrity sha1-d8DLN8QVJdZBZtmQ/61+xqDhNj4= + dependencies: + readable-stream "^2.0.1" + +os-homedir@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" + integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= + +os-locale@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9" + integrity sha1-IPnxeuKe00XoveWDsT0gCYA8FNk= + dependencies: + lcid "^1.0.0" + +parse-filepath@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/parse-filepath/-/parse-filepath-1.0.2.tgz#a632127f53aaf3d15876f5872f3ffac763d6c891" + integrity sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE= + dependencies: + is-absolute "^1.0.0" + map-cache "^0.2.0" + path-root "^0.1.1" + +parse-json@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9" + integrity sha1-9ID0BDTvgHQfhGkJn43qGPVaTck= + dependencies: + error-ex "^1.2.0" + +parse-node-version@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/parse-node-version/-/parse-node-version-1.0.1.tgz#e2b5dbede00e7fa9bc363607f53327e8b073189b" + integrity sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA== + +parse-passwd@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/parse-passwd/-/parse-passwd-1.0.0.tgz#6d5b934a456993b23d37f40a382d6f1666a8e5c6" + integrity sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY= + +pascalcase@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/pascalcase/-/pascalcase-0.1.1.tgz#b363e55e8006ca6fe21784d2db22bd15d7917f14" + integrity sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ= + +path-dirname@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/path-dirname/-/path-dirname-1.0.2.tgz#cc33d24d525e099a5388c0336c6e32b9160609e0" + integrity sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA= + +path-exists@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" + integrity sha1-D+tsZPD8UY2adU3V77YscCJ2H0s= + dependencies: + pinkie-promise "^2.0.0" + +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + integrity sha1-F0uSaHNVNP+8es5r9TpanhtcX18= + +path-parse@^1.0.6: + version "1.0.6" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c" + integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw== + +path-root-regex@^0.1.0: + version "0.1.2" + resolved "https://registry.yarnpkg.com/path-root-regex/-/path-root-regex-0.1.2.tgz#bfccdc8df5b12dc52c8b43ec38d18d72c04ba96d" + integrity sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0= + +path-root@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/path-root/-/path-root-0.1.1.tgz#9a4a6814cac1c0cd73360a95f32083c8ea4745b7" + integrity sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc= + dependencies: + path-root-regex "^0.1.0" + +path-type@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441" + integrity sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE= + dependencies: + graceful-fs "^4.1.2" + pify "^2.0.0" + pinkie-promise "^2.0.0" + +pify@^2.0.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c" + integrity sha1-7RQaasBDqEnqWISY59yosVMw6Qw= + +pinkie-promise@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa" + integrity sha1-ITXW36ejWMBprJsXh3YogihFD/o= + dependencies: + pinkie "^2.0.0" + +pinkie@^2.0.0: + version "2.0.4" + resolved "https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870" + integrity sha1-clVrgM+g1IqXToDnckjoDtT3+HA= + +plur@^3.0.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/plur/-/plur-3.1.1.tgz#60267967866a8d811504fe58f2faaba237546a5b" + integrity sha512-t1Ax8KUvV3FFII8ltczPn2tJdjqbd1sIzu6t4JL7nQ3EyeL/lTrj5PWKb06ic5/6XYDr65rQ4uzQEGN70/6X5w== + dependencies: + irregular-plurals "^2.0.0" + +posix-character-classes@^0.1.0: + version "0.1.1" + resolved "https://registry.yarnpkg.com/posix-character-classes/-/posix-character-classes-0.1.1.tgz#01eac0fe3b5af71a2a6c02feabb8c1fef7e00eab" + integrity sha1-AerA/jta9xoqbAL+q7jB/vfgDqs= + +pretty-hrtime@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz#b7e3ea42435a4c9b2759d99e0f201eb195802ee1" + integrity sha1-t+PqQkNaTJsnWdmeDyAesZWALuE= + +process-nextick-args@^2.0.0, process-nextick-args@~2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-2.0.1.tgz#7820d9b16120cc55ca9ae7792680ae7dba6d7fe2" + integrity sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag== + +pump@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/pump/-/pump-2.0.1.tgz#12399add6e4cf7526d973cbc8b5ce2e2908b3909" + integrity sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA== + dependencies: + end-of-stream "^1.1.0" + once "^1.3.1" + +pumpify@^1.3.5: + version "1.5.1" + resolved "https://registry.yarnpkg.com/pumpify/-/pumpify-1.5.1.tgz#36513be246ab27570b1a374a5ce278bfd74370ce" + integrity sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ== + dependencies: + duplexify "^3.6.0" + inherits "^2.0.3" + pump "^2.0.0" + +read-pkg-up@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" + integrity sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI= + dependencies: + find-up "^1.0.0" + read-pkg "^1.0.0" + +read-pkg@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28" + integrity sha1-9f+qXs0pyzHAR0vKfXVra7KePyg= + dependencies: + load-json-file "^1.0.0" + normalize-package-data "^2.3.2" + path-type "^1.0.0" + +"readable-stream@2 || 3": + version "3.6.0" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198" + integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.3, readable-stream@^2.3.5, readable-stream@^2.3.6, readable-stream@~2.3.6: + version "2.3.7" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" + integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== + dependencies: + core-util-is "~1.0.0" + inherits "~2.0.3" + isarray "~1.0.0" + process-nextick-args "~2.0.0" + safe-buffer "~5.1.1" + string_decoder "~1.1.1" + util-deprecate "~1.0.1" + +readdirp@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-2.2.1.tgz#0e87622a3325aa33e892285caf8b4e846529a525" + integrity sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ== + dependencies: + graceful-fs "^4.1.11" + micromatch "^3.1.10" + readable-stream "^2.0.2" + +rechoir@^0.6.2: + version "0.6.2" + resolved "https://registry.yarnpkg.com/rechoir/-/rechoir-0.6.2.tgz#85204b54dba82d5742e28c96756ef43af50e3384" + integrity sha1-hSBLVNuoLVdC4oyWdW70OvUOM4Q= + dependencies: + resolve "^1.1.6" + +regex-not@^1.0.0, regex-not@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/regex-not/-/regex-not-1.0.2.tgz#1f4ece27e00b0b65e0247a6810e6a85d83a5752c" + integrity sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A== + dependencies: + extend-shallow "^3.0.2" + safe-regex "^1.1.0" + +remove-bom-buffer@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/remove-bom-buffer/-/remove-bom-buffer-3.0.0.tgz#c2bf1e377520d324f623892e33c10cac2c252b53" + integrity sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ== + dependencies: + is-buffer "^1.1.5" + is-utf8 "^0.2.1" + +remove-bom-stream@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/remove-bom-stream/-/remove-bom-stream-1.2.0.tgz#05f1a593f16e42e1fb90ebf59de8e569525f9523" + integrity sha1-BfGlk/FuQuH7kOv1nejlaVJflSM= + dependencies: + remove-bom-buffer "^3.0.0" + safe-buffer "^5.1.0" + through2 "^2.0.3" + +remove-trailing-separator@^1.0.1, remove-trailing-separator@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz#c24bce2a283adad5bc3f58e0d48249b92379d8ef" + integrity sha1-wkvOKig62tW8P1jg1IJJuSN52O8= + +repeat-element@^1.1.2: + version "1.1.3" + resolved "https://registry.yarnpkg.com/repeat-element/-/repeat-element-1.1.3.tgz#782e0d825c0c5a3bb39731f84efee6b742e6b1ce" + integrity sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g== + +repeat-string@^1.6.1: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= + +replace-ext@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-1.0.1.tgz#2d6d996d04a15855d967443631dd5f77825b016a" + integrity sha512-yD5BHCe7quCgBph4rMQ+0KkIRKwWCrHDOX1p1Gp6HwjPM5kVoCdKGNhN7ydqqsX6lJEnQDKZ/tFMiEdQ1dvPEw== + +replace-homedir@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/replace-homedir/-/replace-homedir-1.0.0.tgz#e87f6d513b928dde808260c12be7fec6ff6e798c" + integrity sha1-6H9tUTuSjd6AgmDBK+f+xv9ueYw= + dependencies: + homedir-polyfill "^1.0.1" + is-absolute "^1.0.0" + remove-trailing-separator "^1.1.0" + +require-directory@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" + integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I= + +require-main-filename@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1" + integrity sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE= + +resolve-dir@^1.0.0, resolve-dir@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/resolve-dir/-/resolve-dir-1.0.1.tgz#79a40644c362be82f26effe739c9bb5382046f43" + integrity sha1-eaQGRMNivoLybv/nOcm7U4IEb0M= + dependencies: + expand-tilde "^2.0.0" + global-modules "^1.0.0" + +resolve-options@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/resolve-options/-/resolve-options-1.1.0.tgz#32bb9e39c06d67338dc9378c0d6d6074566ad131" + integrity sha1-MrueOcBtZzONyTeMDW1gdFZq0TE= + dependencies: + value-or-function "^3.0.0" + +resolve-url@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/resolve-url/-/resolve-url-0.2.1.tgz#2c637fe77c893afd2a663fe21aa9080068e2052a" + integrity sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo= + +resolve@^1.1.6, resolve@^1.1.7, resolve@^1.10.0, resolve@^1.4.0: + version "1.17.0" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.17.0.tgz#b25941b54968231cc2d1bb76a79cb7f2c0bf8444" + integrity sha512-ic+7JYiV8Vi2yzQGFWOkiZD5Z9z7O2Zhm9XMaTxdJExKasieFCr+yXZ/WmXsckHiKl12ar0y6XiXDx3m4RHn1w== + dependencies: + path-parse "^1.0.6" + +ret@~0.1.10: + version "0.1.15" + resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" + integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== + +safe-buffer@^5.1.0, safe-buffer@~5.2.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== + +safe-buffer@~5.1.0, safe-buffer@~5.1.1: + version "5.1.2" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" + integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== + +safe-regex@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/safe-regex/-/safe-regex-1.1.0.tgz#40a3669f3b077d1e943d44629e157dd48023bf2e" + integrity sha1-QKNmnzsHfR6UPURinhV91IAjvy4= + dependencies: + ret "~0.1.10" + +semver-greatest-satisfied-range@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/semver-greatest-satisfied-range/-/semver-greatest-satisfied-range-1.1.0.tgz#13e8c2658ab9691cb0cd71093240280d36f77a5b" + integrity sha1-E+jCZYq5aRywzXEJMkAoDTb3els= + dependencies: + sver-compat "^1.5.0" + +"semver@2 || 3 || 4 || 5": + version "5.7.1" + resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" + integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== + +set-blocking@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" + integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= + +set-value@^2.0.0, set-value@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/set-value/-/set-value-2.0.1.tgz#a18d40530e6f07de4228c7defe4227af8cad005b" + integrity sha512-JxHc1weCN68wRY0fhCoXpyK55m/XPHafOmK4UWD7m2CI14GMcFypt4w/0+NV5f/ZMby2F6S2wwA7fgynh9gWSw== + dependencies: + extend-shallow "^2.0.1" + is-extendable "^0.1.1" + is-plain-object "^2.0.3" + split-string "^3.0.1" + +snapdragon-node@^2.0.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/snapdragon-node/-/snapdragon-node-2.1.1.tgz#6c175f86ff14bdb0724563e8f3c1b021a286853b" + integrity sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw== + dependencies: + define-property "^1.0.0" + isobject "^3.0.0" + snapdragon-util "^3.0.1" + +snapdragon-util@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/snapdragon-util/-/snapdragon-util-3.0.1.tgz#f956479486f2acd79700693f6f7b805e45ab56e2" + integrity sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ== + dependencies: + kind-of "^3.2.0" + +snapdragon@^0.8.1: + version "0.8.2" + resolved "https://registry.yarnpkg.com/snapdragon/-/snapdragon-0.8.2.tgz#64922e7c565b0e14204ba1aa7d6964278d25182d" + integrity sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg== + dependencies: + base "^0.11.1" + debug "^2.2.0" + define-property "^0.2.5" + extend-shallow "^2.0.1" + map-cache "^0.2.2" + source-map "^0.5.6" + source-map-resolve "^0.5.0" + use "^3.1.0" + +source-map-resolve@^0.5.0: + version "0.5.3" + resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz#190866bece7553e1f8f267a2ee82c606b5509a1a" + integrity sha512-Htz+RnsXWk5+P2slx5Jh3Q66vhQj1Cllm0zvnaY98+NFx+Dv2CF/f5O/t8x+KaNdrdIAsruNzoh/KpialbqAnw== + dependencies: + atob "^2.1.2" + decode-uri-component "^0.2.0" + resolve-url "^0.2.1" + source-map-url "^0.4.0" + urix "^0.1.0" + +source-map-url@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/source-map-url/-/source-map-url-0.4.0.tgz#3e935d7ddd73631b97659956d55128e87b5084a3" + integrity sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM= + +source-map@^0.5.6: + version "0.5.7" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + integrity sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w= + +source-map@^0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" + integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== + +sparkles@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.1.tgz#008db65edce6c50eec0c5e228e1945061dd0437c" + integrity sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw== + +spdx-correct@^3.0.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.1.1.tgz#dece81ac9c1e6713e5f7d1b6f17d468fa53d89a9" + integrity sha512-cOYcUWwhCuHCXi49RhFRCyJEK3iPj1Ziz9DpViV3tbZOwXD49QzIN3MpOLJNxh2qwq2lJJZaKMVw9qNi4jTC0w== + dependencies: + spdx-expression-parse "^3.0.0" + spdx-license-ids "^3.0.0" + +spdx-exceptions@^2.1.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.3.0.tgz#3f28ce1a77a00372683eade4a433183527a2163d" + integrity sha512-/tTrYOC7PPI1nUAgx34hUpqXuyJG+DTHJTnIULG4rDygi4xu/tfgmq1e1cIRwRzwZgo4NLySi+ricLkZkw4i5A== + +spdx-expression-parse@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" + integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== + dependencies: + spdx-exceptions "^2.1.0" + spdx-license-ids "^3.0.0" + +spdx-license-ids@^3.0.0: + version "3.0.5" + resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.5.tgz#3694b5804567a458d3c8045842a6358632f62654" + integrity sha512-J+FWzZoynJEXGphVIS+XEh3kFSjZX/1i9gFBaWQcB+/tmpe2qUsSBABpcxqxnAxFdiUFEgAX1bjYGQvIZmoz9Q== + +split-string@^3.0.1, split-string@^3.0.2: + version "3.1.0" + resolved "https://registry.yarnpkg.com/split-string/-/split-string-3.1.0.tgz#7cb09dda3a86585705c64b39a6466038682e8fe2" + integrity sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw== + dependencies: + extend-shallow "^3.0.0" + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + integrity sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw= + +stack-trace@0.0.10: + version "0.0.10" + resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0" + integrity sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA= + +static-extend@^0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/static-extend/-/static-extend-0.1.2.tgz#60809c39cbff55337226fd5e0b520f341f1fb5c6" + integrity sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY= + dependencies: + define-property "^0.2.5" + object-copy "^0.1.0" + +stream-exhaust@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/stream-exhaust/-/stream-exhaust-1.0.2.tgz#acdac8da59ef2bc1e17a2c0ccf6c320d120e555d" + integrity sha512-b/qaq/GlBK5xaq1yrK9/zFcyRSTNxmcZwFLGSTG0mXgZl/4Z6GgiyYOXOvY7N3eEvFRAG1bkDRz5EPGSvPYQlw== + +stream-shift@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.1.tgz#d7088281559ab2778424279b0877da3c392d5a3d" + integrity sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ== + +string-width@^1.0.1, string-width@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" + integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= + dependencies: + code-point-at "^1.0.0" + is-fullwidth-code-point "^1.0.0" + strip-ansi "^3.0.0" + +string_decoder@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== + dependencies: + safe-buffer "~5.2.0" + +string_decoder@~1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.1.1.tgz#9cf1611ba62685d7030ae9e4ba34149c3af03fc8" + integrity sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg== + dependencies: + safe-buffer "~5.1.0" + +stringify-object@^3.0.0: + version "3.3.0" + resolved "https://registry.yarnpkg.com/stringify-object/-/stringify-object-3.3.0.tgz#703065aefca19300d3ce88af4f5b3956d7556629" + integrity sha512-rHqiFh1elqCQ9WPLIC8I0Q/g/wj5J1eMkyoiD6eoQApWHP0FtlK7rqnhmabL5VUY9JQCcqwwvlOaSuutekgyrw== + dependencies: + get-own-enumerable-property-symbols "^3.0.0" + is-obj "^1.0.1" + is-regexp "^1.0.0" + +strip-ansi@^3.0.0, strip-ansi@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" + integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= + dependencies: + ansi-regex "^2.0.0" + +strip-bom@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e" + integrity sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4= + dependencies: + is-utf8 "^0.2.0" + +supports-color@^5.3.0: + version "5.5.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" + integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== + dependencies: + has-flag "^3.0.0" + +sver-compat@^1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/sver-compat/-/sver-compat-1.5.0.tgz#3cf87dfeb4d07b4a3f14827bc186b3fd0c645cd8" + integrity sha1-PPh9/rTQe0o/FIJ7wYaz/QxkXNg= + dependencies: + es6-iterator "^2.0.1" + es6-symbol "^3.1.1" + +through2-filter@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/through2-filter/-/through2-filter-3.0.0.tgz#700e786df2367c2c88cd8aa5be4cf9c1e7831254" + integrity sha512-jaRjI2WxN3W1V8/FMZ9HKIBXixtiqs3SQSX4/YGIiP3gL6djW48VoZq9tDqeCWs3MT8YY5wb/zli8VW8snY1CA== + dependencies: + through2 "~2.0.0" + xtend "~4.0.0" + +through2@^2.0.0, through2@^2.0.3, through2@~2.0.0: + version "2.0.5" + resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd" + integrity sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ== + dependencies: + readable-stream "~2.3.6" + xtend "~4.0.1" + +through2@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/through2/-/through2-3.0.1.tgz#39276e713c3302edf9e388dd9c812dd3b825bd5a" + integrity sha512-M96dvTalPT3YbYLaKaCuwu+j06D/8Jfib0o/PxbVt6Amhv3dUAtW6rTV1jPgJSBG83I/e04Y6xkVdVhSRhi0ww== + dependencies: + readable-stream "2 || 3" + +tildify@^1.1.2: + version "1.2.0" + resolved "https://registry.yarnpkg.com/tildify/-/tildify-1.2.0.tgz#dcec03f55dca9b7aa3e5b04f21817eb56e63588a" + integrity sha1-3OwD9V3Km3qj5bBPIYF+tW5jWIo= + dependencies: + os-homedir "^1.0.0" + +time-stamp@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz#764a5a11af50561921b133f3b44e618687e0f5c3" + integrity sha1-dkpaEa9QVhkhsTPztE5hhofg9cM= + +to-absolute-glob@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz#1865f43d9e74b0822db9f145b78cff7d0f7c849b" + integrity sha1-GGX0PZ50sIItufFFt4z/fQ98hJs= + dependencies: + is-absolute "^1.0.0" + is-negated-glob "^1.0.0" + +to-object-path@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/to-object-path/-/to-object-path-0.3.0.tgz#297588b7b0e7e0ac08e04e672f85c1f4999e17af" + integrity sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68= + dependencies: + kind-of "^3.0.2" + +to-regex-range@^2.1.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-2.1.1.tgz#7c80c17b9dfebe599e27367e0d4dd5590141db38" + integrity sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg= + dependencies: + is-number "^3.0.0" + repeat-string "^1.6.1" + +to-regex@^3.0.1, to-regex@^3.0.2: + version "3.0.2" + resolved "https://registry.yarnpkg.com/to-regex/-/to-regex-3.0.2.tgz#13cfdd9b336552f30b51f33a8ae1b42a7a7599ce" + integrity sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw== + dependencies: + define-property "^2.0.2" + extend-shallow "^3.0.2" + regex-not "^1.0.2" + safe-regex "^1.1.0" + +to-through@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/to-through/-/to-through-2.0.0.tgz#fc92adaba072647bc0b67d6b03664aa195093af6" + integrity sha1-/JKtq6ByZHvAtn1rA2ZKoZUJOvY= + dependencies: + through2 "^2.0.3" + +type@^1.0.1: + version "1.2.0" + resolved "https://registry.yarnpkg.com/type/-/type-1.2.0.tgz#848dd7698dafa3e54a6c479e759c4bc3f18847a0" + integrity sha512-+5nt5AAniqsCnu2cEQQdpzCAh33kVx8n0VoFidKpB1dVVLAN/F+bgVOqOJqOnEnrhp222clB5p3vUlD+1QAnfg== + +type@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/type/-/type-2.0.0.tgz#5f16ff6ef2eb44f260494dae271033b29c09a9c3" + integrity sha512-KBt58xCHry4Cejnc2ISQAF7QY+ORngsWfxezO68+12hKV6lQY8P/psIkcbjeHWn7MqcgciWJyCCevFMJdIXpow== + +typedarray@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" + integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= + +uc.micro@^1.0.1, uc.micro@^1.0.5: + version "1.0.6" + resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" + integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== + +unc-path-regex@^0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/unc-path-regex/-/unc-path-regex-0.1.2.tgz#e73dd3d7b0d7c5ed86fbac6b0ae7d8c6a69d50fa" + integrity sha1-5z3T17DXxe2G+6xrCufYxqadUPo= + +undertaker-registry@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/undertaker-registry/-/undertaker-registry-1.0.1.tgz#5e4bda308e4a8a2ae584f9b9a4359a499825cc50" + integrity sha1-XkvaMI5KiirlhPm5pDWaSZglzFA= + +undertaker@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/undertaker/-/undertaker-1.2.1.tgz#701662ff8ce358715324dfd492a4f036055dfe4b" + integrity sha512-71WxIzDkgYk9ZS+spIB8iZXchFhAdEo2YU8xYqBYJ39DIUIqziK78ftm26eecoIY49X0J2MLhG4hr18Yp6/CMA== + dependencies: + arr-flatten "^1.0.1" + arr-map "^2.0.0" + bach "^1.0.0" + collection-map "^1.0.0" + es6-weak-map "^2.0.1" + last-run "^1.1.0" + object.defaults "^1.0.0" + object.reduce "^1.0.0" + undertaker-registry "^1.0.0" + +union-value@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.1.tgz#0b6fe7b835aecda61c6ea4d4f02c14221e109847" + integrity sha512-tJfXmxMeWYnczCVs7XAEvIV7ieppALdyepWMkHkwciRpZraG/xwT+s2JN8+pr1+8jCRf80FFzvr+MpQeeoF4Xg== + dependencies: + arr-union "^3.1.0" + get-value "^2.0.6" + is-extendable "^0.1.1" + set-value "^2.0.1" + +unique-stream@^2.0.2: + version "2.3.1" + resolved "https://registry.yarnpkg.com/unique-stream/-/unique-stream-2.3.1.tgz#c65d110e9a4adf9a6c5948b28053d9a8d04cbeac" + integrity sha512-2nY4TnBE70yoxHkDli7DMazpWiP7xMdCYqU2nBRO0UB+ZpEkGsSija7MvmvnZFUeC+mrgiUfcHSr3LmRFIg4+A== + dependencies: + json-stable-stringify-without-jsonify "^1.0.1" + through2-filter "^3.0.0" + +unset-value@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" + integrity sha1-g3aHP30jNRef+x5vw6jtDfyKtVk= + dependencies: + has-value "^0.3.1" + isobject "^3.0.0" + +upath@^1.1.1: + version "1.2.0" + resolved "https://registry.yarnpkg.com/upath/-/upath-1.2.0.tgz#8f66dbcd55a883acdae4408af8b035a5044c1894" + integrity sha512-aZwGpamFO61g3OlfT7OQCHqhGnW43ieH9WZeP7QxN/G/jS4jfqUkZxoryvJgVPEcrl5NL/ggHsSmLMHuH64Lhg== + +urix@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/urix/-/urix-0.1.0.tgz#da937f7a62e21fec1fd18d49b35c2935067a6c72" + integrity sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI= + +use@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f" + integrity sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ== + +util-deprecate@^1.0.1, util-deprecate@~1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8= + +v8flags@^3.0.1: + version "3.1.3" + resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-3.1.3.tgz#fc9dc23521ca20c5433f81cc4eb9b3033bb105d8" + integrity sha512-amh9CCg3ZxkzQ48Mhcb8iX7xpAfYJgePHxWMQCBWECpOSqJUXgY26ncA61UTV0BkPqfhcy6mzwCIoP4ygxpW8w== + dependencies: + homedir-polyfill "^1.0.1" + +validate-npm-package-license@^3.0.1: + version "3.0.4" + resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" + integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== + dependencies: + spdx-correct "^3.0.0" + spdx-expression-parse "^3.0.0" + +value-or-function@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/value-or-function/-/value-or-function-3.0.0.tgz#1c243a50b595c1be54a754bfece8563b9ff8d813" + integrity sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM= + +vinyl-fs@^3.0.0: + version "3.0.3" + resolved "https://registry.yarnpkg.com/vinyl-fs/-/vinyl-fs-3.0.3.tgz#c85849405f67428feabbbd5c5dbdd64f47d31bc7" + integrity sha512-vIu34EkyNyJxmP0jscNzWBSygh7VWhqun6RmqVfXePrOwi9lhvRs//dOaGOTRUQr4tx7/zd26Tk5WeSVZitgng== + dependencies: + fs-mkdirp-stream "^1.0.0" + glob-stream "^6.1.0" + graceful-fs "^4.0.0" + is-valid-glob "^1.0.0" + lazystream "^1.0.0" + lead "^1.0.0" + object.assign "^4.0.4" + pumpify "^1.3.5" + readable-stream "^2.3.3" + remove-bom-buffer "^3.0.0" + remove-bom-stream "^1.2.0" + resolve-options "^1.1.0" + through2 "^2.0.0" + to-through "^2.0.0" + value-or-function "^3.0.0" + vinyl "^2.0.0" + vinyl-sourcemap "^1.1.0" + +vinyl-sourcemap@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/vinyl-sourcemap/-/vinyl-sourcemap-1.1.0.tgz#92a800593a38703a8cdb11d8b300ad4be63b3e16" + integrity sha1-kqgAWTo4cDqM2xHYswCtS+Y7PhY= + dependencies: + append-buffer "^1.0.2" + convert-source-map "^1.5.0" + graceful-fs "^4.1.6" + normalize-path "^2.1.1" + now-and-later "^2.0.0" + remove-bom-buffer "^3.0.0" + vinyl "^2.0.0" + +vinyl@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/vinyl/-/vinyl-2.2.0.tgz#d85b07da96e458d25b2ffe19fece9f2caa13ed86" + integrity sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg== + dependencies: + clone "^2.1.1" + clone-buffer "^1.0.0" + clone-stats "^1.0.0" + cloneable-readable "^1.0.0" + remove-trailing-separator "^1.0.1" + replace-ext "^1.0.0" + +which-module@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz#bba63ca861948994ff307736089e3b96026c2a4f" + integrity sha1-u6Y8qGGUiZT/MHc2CJ47lgJsKk8= + +which@^1.2.14: + version "1.3.1" + resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" + integrity sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ== + dependencies: + isexe "^2.0.0" + +wrap-ansi@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85" + integrity sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU= + dependencies: + string-width "^1.0.1" + strip-ansi "^3.0.1" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + integrity sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8= + +xtend@~4.0.0, xtend@~4.0.1: + version "4.0.2" + resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.2.tgz#bb72779f5fa465186b1f438f674fa347fdb5db54" + integrity sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ== + +y18n@^3.2.1: + version "3.2.1" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41" + integrity sha1-bRX7qITAhnnA136I53WegR4H+kE= + +yargs-parser@5.0.0-security.0: + version "5.0.0-security.0" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-5.0.0-security.0.tgz#4ff7271d25f90ac15643b86076a2ab499ec9ee24" + integrity sha512-T69y4Ps64LNesYxeYGYPvfoMTt/7y1XtfpIslUeK4um+9Hu7hlGoRtaDLvdXb7+/tfq4opVa2HRY5xGip022rQ== + dependencies: + camelcase "^3.0.0" + object.assign "^4.1.0" + +yargs@^7.1.0: + version "7.1.1" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-7.1.1.tgz#67f0ef52e228d4ee0d6311acede8850f53464df6" + integrity sha512-huO4Fr1f9PmiJJdll5kwoS2e4GqzGSsMT3PPMpOwoVkOK8ckqAewMTZyA6LXVQWflleb/Z8oPBEvNsMft0XE+g== + dependencies: + camelcase "^3.0.0" + cliui "^3.2.0" + decamelize "^1.1.1" + get-caller-file "^1.0.1" + os-locale "^1.4.0" + read-pkg-up "^1.0.1" + require-directory "^2.1.1" + require-main-filename "^1.0.1" + set-blocking "^2.0.0" + string-width "^1.0.2" + which-module "^1.0.0" + y18n "^3.2.1" + yargs-parser "5.0.0-security.0" diff --git a/test/docker/networktest/DockerRemoting.Tests.ps1 b/test/docker/networktest/DockerRemoting.Tests.ps1 index ae9db267d6d..5f5a13c5b4c 100644 --- a/test/docker/networktest/DockerRemoting.Tests.ps1 +++ b/test/docker/networktest/DockerRemoting.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. $imageName = "remotetestimage" Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ @@ -7,7 +7,7 @@ Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ $dockerimage = docker images --format "{{ .Repository }}" $imageName if ( $dockerimage -ne $imageName ) { $pending = $true - write-warning "Docker image '$imageName' not found, not running tests" + Write-Warning "Docker image '$imageName' not found, not running tests" return } else { @@ -15,18 +15,18 @@ Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ } # give the containers something to do, otherwise they will exit and be removed - Write-Verbose -verbose "setting up docker container PowerShell server" + Write-Verbose -Verbose "setting up docker container PowerShell server" $server = docker run -d $imageName powershell -c Start-Sleep -Seconds $timeout - Write-Verbose -verbose "setting up docker container PowerShell client" + Write-Verbose -Verbose "setting up docker container PowerShell client" $client = docker run -d $imageName powershell -c Start-Sleep -Seconds $timeout # get fullpath to installed core powershell - Write-Verbose -verbose "Getting path to PowerShell" + Write-Verbose -Verbose "Getting path to PowerShell" $powershellcorepath = docker exec $server powershell -c "(get-childitem 'c:\program files\powershell\*\pwsh.exe').fullname" if ( ! $powershellcorepath ) { $pending = $true - write-warning "Cannot find powershell executable, not running tests" + Write-Warning "Cannot find powershell executable, not running tests" return } $powershellcoreversion = ($powershellcorepath -split "[\\/]")[-2] @@ -34,27 +34,27 @@ Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ $powershellcoreConfiguration = "powershell.${powershellcoreversion}" # capture the hostnames of the containers which will be used by the tests - write-verbose -verbose "getting server hostname" + Write-Verbose -Verbose "getting server hostname" $serverhostname = docker exec $server hostname - write-verbose -verbose "getting client hostname" + Write-Verbose -Verbose "getting client hostname" $clienthostname = docker exec $client hostname # capture the versions of full and core PowerShell - write-verbose -verbose "getting powershell full version" + Write-Verbose -Verbose "getting powershell full version" $fullVersion = docker exec $client powershell -c "`$PSVersionTable.psversion.tostring()" if ( ! $fullVersion ) { $pending = $true - write-warning "Cannot determine PowerShell full version, not running tests" + Write-Warning "Cannot determine PowerShell full version, not running tests" return } - write-verbose -verbose "getting powershell version" + Write-Verbose -Verbose "getting powershell version" $coreVersion = docker exec $client "$powershellcorepath" -c "`$PSVersionTable.psversion.tostring()" if ( ! $coreVersion ) { $pending = $true - write-warning "Cannot determine PowerShell version, not running tests" + Write-Warning "Cannot determine PowerShell version, not running tests" return } } @@ -67,22 +67,22 @@ Describe "Basic remoting test with docker" -tags @("Scenario","Slow"){ } } - It "Full powershell can get correct remote powershell version" -pending:$pending { + It "Full powershell can get correct remote powershell version" -Pending:$pending { $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$PSVersionTable.psversion.tostring() }" $result | Should -Be $coreVersion } - It "Full powershell can get correct remote powershell full version" -pending:$pending { + It "Full powershell can get correct remote powershell full version" -Pending:$pending { $result = docker exec $client powershell -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$PSVersionTable.psversion.tostring() }" $result | Should -Be $fullVersion } - It "Core powershell can get correct remote powershell version" -pending:$pending { + It "Core powershell can get correct remote powershell version" -Pending:$pending { $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -configurationname $powershellcoreConfiguration -auth basic -credential `$c; invoke-command -session `$ses { `$PSVersionTable.psversion.tostring() }" $result | Should -Be $coreVersion } - It "Core powershell can get correct remote powershell full version" -pending:$pending { + It "Core powershell can get correct remote powershell full version" -Pending:$pending { $result = docker exec $client "$powershellcorepath" -c "`$ss = [security.securestring]::new(); '11aa!!AA'.ToCharArray() | ForEach-Object { `$ss.appendchar(`$_)}; `$c = [pscredential]::new('testuser',`$ss); `$ses=new-pssession $serverhostname -auth basic -credential `$c; invoke-command -session `$ses { `$PSVersionTable.psversion.tostring() }" $result | Should -Be $fullVersion } diff --git a/test/docker/networktest/New-DockerTestBuild.ps1 b/test/docker/networktest/New-DockerTestBuild.ps1 deleted file mode 100644 index fbb0c4e0be8..00000000000 --- a/test/docker/networktest/New-DockerTestBuild.ps1 +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. -param ( [switch]$Force, [switch]$UseExistingMsi ) - -$script:Constants = @{ - AccountName = 'PowerShell' - ProjectName = 'powershell-f975h' - TestImageName = "remotetestimage" - MsiName = "PSCore.msi" - Token = "" # in this particular use we don't need a token -} - -############ -### MAIN ### -############ - -#### DOCKER OPS ##### -# is docker installed? -$dockerExe = get-command docker -ea silentlycontinue -if ( $dockerExe.name -ne "docker.exe" ) { - throw "Cannot find docker, is it installed?" -} -# Check to see if we already have an image, and if so -# delete it if -Force was used, otherwise throw and exit -$TestImage = docker images $Constants.TestImageName --format '{{.Repository}}' -if ( $TestImage -eq $Constants.TestImageName) -{ - if ( $Force ) - { - docker rmi $Constants.TestImageName - } - else - { - throw ("{0} already exists, use '-Force' to remove" -f $Constants.TestImageName) - } -} -# check again - there could be some permission problems -$TestImage = docker images $Constants.TestImageName --format '{{.Repository}}' -if ( $TestImage -eq $Constants.TestImageName) -{ - throw ("'{0}' still exists, giving up" -f $Constants.TestImageName) -} - -#### MSI CHECKS #### -# check to see if the MSI is present -$MsiExists = test-path $Constants.MsiName -$msg = "{0} exists, use -Force to remove or -UseExistingMsi to use" -f $Constants.MsiName -if ( $MsiExists -and ! ($force -or $useExistingMsi)) -{ - throw $msg -} - -# remove the msi -if ( $MsiExists -and $Force -and ! $UseExistingMsi ) -{ - Remove-Item -force $Constants.MsiName - $MsiExists = $false -} - -# a couple of checks before downloading or using the existing one -# if the msi exists and -UseExistingMsi is present, we'll use the -# one we found -if ( ! $MsiExists -and $UseExistingMsi ) -{ - throw ("{0} does not exist" -f $Constants.MsiName) -} -elseif ( $MsiExists -and ! $UseExistingMsi ) -{ - throw $msg -} - -# last check before bulding the image -if ( ! (test-path $Constants.MsiName) ) -{ - throw ("{0} does not exist, giving up" -f $Constants.MsiName) -} - -# collect the builds and select the last one -Docker build --tag $Constants.TestImageName . diff --git a/test/hosting/test_HostingBasic.cs b/test/hosting/test_HostingBasic.cs index b214c13a9ae..efd3043d514 100644 --- a/test/hosting/test_HostingBasic.cs +++ b/test/hosting/test_HostingBasic.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. +// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; @@ -182,5 +182,30 @@ public static void TestConsoleShellScenario() int ret = ConsoleShell.Start("Hello", string.Empty, new string[] { "-noprofile", "-c", "exit 42" }); Assert.Equal(42, ret); } + + [Fact] + public static void TestBuiltInModules() + { + var iss = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault2(); + if (System.Management.Automation.Platform.IsWindows) + { + iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.RemoteSigned; + } + + using var runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(iss); + runspace.Open(); + + using var ps = System.Management.Automation.PowerShell.Create(runspace); + var results_1 = ps.AddScript("Write-Output Hello > $null; Get-Module").Invoke(); + Assert.Single(results_1); + + var module = results_1[0]; + Assert.Equal("Microsoft.PowerShell.Utility", module.Name); + + ps.Commands.Clear(); + var results_2 = ps.AddScript("Join-Path $PSHOME 'Modules' 'Microsoft.PowerShell.Utility' 'Microsoft.PowerShell.Utility.psd1'").Invoke(); + var moduleManifestPath = results_2[0]; + Assert.Equal(moduleManifestPath, module.Path, ignoreCase: true); + } } } diff --git a/test/nanoserver/nanoserver.tests.ps1 b/test/nanoserver/nanoserver.tests.ps1 index e9a776385a4..85112f461f0 100644 --- a/test/nanoserver/nanoserver.tests.ps1 +++ b/test/nanoserver/nanoserver.tests.ps1 @@ -1,17 +1,17 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Verify PowerShell Runs" { BeforeAll{ $options = (Get-PSOptions) - $path = split-path -path $options.Output + $path = Split-Path -Path $options.Output Write-Verbose "Path: '$path'" -Verbose - $rootPath = split-Path -path $path + $rootPath = Split-Path -Path $path $mount = 'C:\powershell' $container = 'mcr.microsoft.com/powershell:nanoserver-1803' } - it "Verify Version " { + It "Verify Version " { $version = docker run --rm -v "${rootPath}:${mount}" ${container} "${mount}\publish\pwsh" -NoLogo -NoProfile -Command '$PSVersionTable.PSVersion.ToString()' $version | Should -Match '^7\.' } diff --git a/test/packaging/windows/msi.tests.ps1 b/test/packaging/windows/msi.tests.ps1 index 20b6c4f2200..ec488f6cf57 100644 --- a/test/packaging/windows/msi.tests.ps1 +++ b/test/packaging/windows/msi.tests.ps1 @@ -1,57 +1,57 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -function Test-Elevated { - [CmdletBinding()] - [OutputType([bool])] - Param() - - # if the current Powershell session was called with administrator privileges, - # the Administrator Group's well-known SID will show up in the Groups for the current identity. - # Note that the SID won't show up unless the process is elevated. - return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") -} - -function Invoke-Msiexec { - param( - [Parameter(ParameterSetName = 'Install', Mandatory)] - [Switch]$Install, - - [Parameter(ParameterSetName = 'Uninstall', Mandatory)] - [Switch]$Uninstall, - - [Parameter(Mandatory)] - [ValidateScript({Test-Path -Path $_})] - [String]$MsiPath, - - [Parameter(ParameterSetName = 'Install')] - [HashTable] $Properties - - ) - $action = "$($PSCmdlet.ParameterSetName)ing" - if ($Install.IsPresent) { - $switch = '/I' - } else { - $switch = '/x' - } - - $additionalOptions = @() - if ($Properties) { - foreach ($key in $Properties.Keys) { - $additionalOptions += "$key=$($Properties.$key)" +Describe -Name "Windows MSI" -Fixture { + BeforeAll { + function Test-Elevated { + [CmdletBinding()] + [OutputType([bool])] + Param() + + # if the current Powershell session was called with administrator privileges, + # the Administrator Group's well-known SID will show up in the Groups for the current identity. + # Note that the SID won't show up unless the process is elevated. + return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") } - } - $argumentList = "$switch $MsiPath /quiet /l*vx $msiLog $additionalOptions" - $msiExecProcess = Start-Process msiexec.exe -Wait -ArgumentList $argumentList -NoNewWindow -PassThru - if ($msiExecProcess.ExitCode -ne 0) { - $exitCode = $msiExecProcess.ExitCode - throw "$action MSI failed and returned error code $exitCode." - } -} + function Invoke-Msiexec { + param( + [Parameter(ParameterSetName = 'Install', Mandatory)] + [Switch]$Install, + + [Parameter(ParameterSetName = 'Uninstall', Mandatory)] + [Switch]$Uninstall, + + [Parameter(Mandatory)] + [ValidateScript({Test-Path -Path $_})] + [String]$MsiPath, + + [Parameter(ParameterSetName = 'Install')] + [HashTable] $Properties + + ) + $action = "$($PSCmdlet.ParameterSetName)ing" + if ($Install.IsPresent) { + $switch = '/I' + } else { + $switch = '/x' + } + + $additionalOptions = @() + if ($Properties) { + foreach ($key in $Properties.Keys) { + $additionalOptions += "$key=$($Properties.$key)" + } + } + + $argumentList = "$switch $MsiPath /quiet /l*vx $msiLog $additionalOptions" + $msiExecProcess = Start-Process msiexec.exe -Wait -ArgumentList $argumentList -NoNewWindow -PassThru + if ($msiExecProcess.ExitCode -ne 0) { + $exitCode = $msiExecProcess.ExitCode + throw "$action MSI failed and returned error code $exitCode." + } + } -Describe -Name "Windows MSI" -Fixture { - BeforeAll { $msiX64Path = $env:PsMsiX64Path # Get any existing powershell in the path diff --git a/test/powershell/Host/Base-Directory.Tests.ps1 b/test/powershell/Host/Base-Directory.Tests.ps1 index 71f6e682edb..a55af971f09 100644 --- a/test/powershell/Host/Base-Directory.Tests.ps1 +++ b/test/powershell/Host/Base-Directory.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Configuration file locations" -tags "CI","Slow" { @@ -50,7 +50,7 @@ Describe "Configuration file locations" -tags "CI","Slow" { } It @ItArgs "PSReadLine history save location should be correct" { - & $powershell -noprofile { (Get-PSReadlineOption).HistorySavePath } | Should -Be $expectedReadline + & $powershell -noprofile { (Get-PSReadLineOption).HistorySavePath } | Should -Be $expectedReadline } # This feature (and thus test) has been disabled because of the AssemblyLoadContext scenario @@ -104,7 +104,7 @@ Describe "Configuration file locations" -tags "CI","Slow" { It @ItArgs "PSReadLine history should respect XDG_DATA_HOME" { $env:XDG_DATA_HOME = $TestDrive $expected = [IO.Path]::Combine($TestDrive, "powershell", "PSReadLine", "ConsoleHost_history.txt") - & $powershell -noprofile { (Get-PSReadlineOption).HistorySavePath } | Should -Be $expected + & $powershell -noprofile { (Get-PSReadLineOption).HistorySavePath } | Should -Be $expected } # This feature (and thus test) has been disabled because of the AssemblyLoadContext scenario diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 5041a21f1bb..d8eec255184 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. using namespace System.Diagnostics @@ -351,12 +351,12 @@ export $envVarName='$guid' # must use an explicit scope of LocalMachine to ensure the setting is written to the expected file. # Skip the tests on Unix platforms because *-ExecutionPolicy cmdlets don't work by design. - It "Verifies PowerShell reads from the custom -settingsFile" -skip:(!$IsWindows) { + It "Verifies PowerShell reads from the custom -settingsFile" -Skip:(!$IsWindows) { $actualValue = & $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command {(Get-ExecutionPolicy -Scope LocalMachine).ToString()} $actualValue | Should -Be $DefaultExecutionPolicy } - It "Verifies PowerShell writes to the custom -settingsFile" -skip:(!$IsWindows) { + It "Verifies PowerShell writes to the custom -settingsFile" -Skip:(!$IsWindows) { $expectedValue = 'AllSigned' # Update the execution policy; this should update the settings file. @@ -371,7 +371,7 @@ export $envVarName='$guid' $actualValue | Should -Be $expectedValue } - It "Verify PowerShell removes a setting from the custom -settingsFile" -skip:(!$IsWindows) { + It "Verify PowerShell removes a setting from the custom -settingsFile" -Skip:(!$IsWindows) { # Remove the LocalMachine execution policy; this should update the settings file. & $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command {Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope LocalMachine } @@ -385,8 +385,8 @@ export $envVarName='$guid' $p = [PSCustomObject]@{X=10;Y=20} It "xml input" { - $p | & $powershell -noprofile { $input | Foreach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30 - $p | & $powershell -noprofile -inputFormat xml { $input | Foreach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30 + $p | & $powershell -noprofile { $input | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30 + $p | & $powershell -noprofile -inputFormat xml { $input | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30 } It "text input" { @@ -395,8 +395,8 @@ export $envVarName='$guid' } It "xml output" { - & $powershell -noprofile { [PSCustomObject]@{X=10;Y=20} } | Foreach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } | Should -Be 30 - & $powershell -noprofile -outputFormat xml { [PSCustomObject]@{X=10;Y=20} } | Foreach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } | Should -Be 30 + & $powershell -noprofile { [PSCustomObject]@{X=10;Y=20} } | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } | Should -Be 30 + & $powershell -noprofile -outputFormat xml { [PSCustomObject]@{X=10;Y=20} } | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } | Should -Be 30 } It "text output" { @@ -638,17 +638,17 @@ namespace StackTest { $env:XDG_CONFIG_HOME = $XDG_CONFIG_HOME } - It "Should start if Data, Config, and Cache location is not accessible" -skip:($IsWindows) { + It "Should start if Data, Config, and Cache location is not accessible" -Skip:($IsWindows) { $env:XDG_CACHE_HOME = "/dev/cpu" $env:XDG_DATA_HOME = "/dev/cpu" $env:XDG_CONFIG_HOME = "/dev/cpu" - $output = & $powershell -noprofile -Command { (get-command).count } + $output = & $powershell -noprofile -Command { (Get-Command).count } [int]$output | Should -BeGreaterThan 0 } } Context "HOME environment variable" { - It "Should start if HOME is not defined" -skip:($IsWindows) { + It "Should start if HOME is not defined" -Skip:($IsWindows) { bash -c "unset HOME;$powershell -c '1+1'" | Should -BeExactly 2 } } @@ -769,7 +769,7 @@ namespace StackTest { Context "ApartmentState WPF tests" -Tag Slow { It "WPF requires STA and will work" -Skip:(!$IsWindows -or [System.Management.Automation.Platform]::IsNanoServer) { - add-type -AssemblyName presentationframework + Add-Type -AssemblyName presentationframework $xaml = [xml]@" " -testcases $testcases { + It "pwsh can startup in a directory named " -TestCases $testcases { param ( $dirname ) try { Push-Location -LiteralPath "${TESTDRIVE}/${dirname}" @@ -1009,3 +1009,10 @@ Describe 'Pwsh startup and PATH' -Tag CI { $path | Should -BeExactly ($PSHOME + [System.IO.Path]::PathSeparator) } } + +Describe 'Console host name' -Tag CI { + It 'Name is pwsh' -Pending { + # waiting on https://github.com/dotnet/runtime/issues/33673 + (Get-Process -Id $PID).Name | Should -BeExactly 'pwsh' + } +} diff --git a/test/powershell/Host/HostUtilities.Tests.ps1 b/test/powershell/Host/HostUtilities.Tests.ps1 index 278c5e1110f..6c791b5c446 100644 --- a/test/powershell/Host/HostUtilities.Tests.ps1 +++ b/test/powershell/Host/HostUtilities.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "InvokeOnRunspace method argument error handling" -tags "Feature" { diff --git a/test/powershell/Host/Logging.Tests.ps1 b/test/powershell/Host/Logging.Tests.ps1 index 56a60f47986..5159d46551f 100644 --- a/test/powershell/Host/Logging.Tests.ps1 +++ b/test/powershell/Host/Logging.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. using namespace System.Text @@ -204,7 +204,7 @@ $PID $items | Should -Not -Be $null $items.Count | Should -BeGreaterThan 2 - $createdEvents = $items | where-object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} + $createdEvents = $items | Where-Object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} $createdEvents.Count | Should -BeGreaterOrEqual 3 # Verify we log that we are executing a file @@ -233,7 +233,7 @@ $PID $items | Should -Not -Be $null $items.Count | Should -BeGreaterThan 2 - $createdEvents = $items | where-object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} + $createdEvents = $items | Where-Object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} $createdEvents.Count | Should -BeGreaterOrEqual 3 # Verify we log that we are executing a file @@ -353,7 +353,7 @@ $PID $items | Should -Not -Be $null $items.Count | Should -BeGreaterThan 2 - $createdEvents = $items | where-object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} + $createdEvents = $items | Where-Object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} $createdEvents.Count | Should -BeGreaterOrEqual 3 # Verify we log that we are executing a file @@ -391,7 +391,7 @@ $PID $items | Should -Not -Be $null $items.Count | Should -BeGreaterThan 2 - $createdEvents = $items | where-object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} + $createdEvents = $items | Where-Object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} $createdEvents.Count | Should -BeGreaterOrEqual 3 # Verify we log that we are executing a file diff --git a/test/powershell/Host/PSVersionTable.Tests.ps1 b/test/powershell/Host/PSVersionTable.Tests.ps1 index 858d5e3b6cb..2ef9fb30a23 100644 --- a/test/powershell/Host/PSVersionTable.Tests.ps1 +++ b/test/powershell/Host/PSVersionTable.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "PSVersionTable" -Tags "CI" { @@ -23,7 +23,7 @@ Describe "PSVersionTable" -Tags "CI" { $unexpectectGitCommitIdPattern = $fullVersionPattern } - $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0" + $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1" $powerShellCompatibleVersions = $PSVersionTable.PSCompatibleVersions | ForEach-Object {$_.ToString(2).SubString(0,3)} } diff --git a/test/powershell/Host/Read-Host.Tests.ps1 b/test/powershell/Host/Read-Host.Tests.ps1 index 09809659701..dc225362ed0 100644 --- a/test/powershell/Host/Read-Host.Tests.ps1 +++ b/test/powershell/Host/Read-Host.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Read-Host" -Tags "Slow","Feature" { Context "[Console]::ReadKey() implementation on non-Windows" { diff --git a/test/powershell/Host/ScreenReader.Tests.ps1 b/test/powershell/Host/ScreenReader.Tests.ps1 index 7a2b3464680..35f86459861 100644 --- a/test/powershell/Host/ScreenReader.Tests.ps1 +++ b/test/powershell/Host/ScreenReader.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Validate start of console host" -Tag CI { diff --git a/test/powershell/Host/Startup.Tests.ps1 b/test/powershell/Host/Startup.Tests.ps1 index 87704901f42..05b2534bc9a 100644 --- a/test/powershell/Host/Startup.Tests.ps1 +++ b/test/powershell/Host/Startup.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Validate start of console host" -Tag CI { @@ -13,7 +13,6 @@ Describe "Validate start of console host" -Tag CI { 'netstandard.dll' 'Newtonsoft.Json.dll' 'pwsh.dll' - 'System.Buffers.dll' 'System.Collections.Concurrent.dll' 'System.Collections.dll' 'System.Collections.NonGeneric.dll' @@ -23,7 +22,6 @@ Describe "Validate start of console host" -Tag CI { 'System.ComponentModel.TypeConverter.dll' 'System.Console.dll' 'System.Data.Common.dll' - 'System.Diagnostics.Debug.dll' 'System.Diagnostics.FileVersionInfo.dll' 'System.Diagnostics.Process.dll' 'System.Diagnostics.TraceSource.dll' @@ -46,9 +44,7 @@ Describe "Validate start of console host" -Tag CI { 'System.Reflection.Emit.ILGeneration.dll' 'System.Reflection.Emit.Lightweight.dll' 'System.Reflection.Primitives.dll' - 'System.Resources.ResourceManager.dll' 'System.Runtime.dll' - 'System.Runtime.Extensions.dll' 'System.Runtime.InteropServices.dll' 'System.Runtime.InteropServices.RuntimeInformation.dll' 'System.Runtime.Loader.dll' @@ -62,7 +58,6 @@ Describe "Validate start of console host" -Tag CI { 'System.Text.Encoding.Extensions.dll' 'System.Text.RegularExpressions.dll' 'System.Threading.dll' - 'System.Threading.Tasks.dll' 'System.Threading.Tasks.Parallel.dll' 'System.Threading.Thread.dll' 'System.Threading.ThreadPool.dll' @@ -76,7 +71,6 @@ Describe "Validate start of console host" -Tag CI { 'System.Management.dll' 'System.Security.Claims.dll' 'System.Security.Cryptography.Primitives.dll' - 'System.Security.Principal.dll' 'System.Threading.Overlapped.dll' ) } @@ -103,7 +97,7 @@ Describe "Validate start of console host" -Tag CI { } It "No new assemblies are loaded" { - if ( (Get-PlatformInfo) -eq "alpine" ) { + if ( (Get-PlatformInfo).Platform -eq "alpine" ) { Set-ItResult -Pending -Because "Missing MI library causes list to be different" return } @@ -111,8 +105,8 @@ Describe "Validate start of console host" -Tag CI { $diffs = Compare-Object -ReferenceObject $allowedAssemblies -DifferenceObject $loadedAssemblies if ($null -ne $diffs) { - $assembliesAllowedButNotLoaded = $diffs | Where-Object SideIndicator -eq "<=" | ForEach-Object InputObject - $assembliesLoadedButNotAllowed = $diffs | Where-Object SideIndicator -eq "=>" | ForEach-Object InputObject + $assembliesAllowedButNotLoaded = $diffs | Where-Object SideIndicator -EQ "<=" | ForEach-Object InputObject + $assembliesLoadedButNotAllowed = $diffs | Where-Object SideIndicator -EQ "=>" | ForEach-Object InputObject if ($assembliesAllowedButNotLoaded) { Write-Host ("Assemblies that are expected but not loaded: {0}" -f ($assembliesAllowedButNotLoaded -join ", ")) diff --git a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 index 89b91b6cfba..78be093a5bb 100644 --- a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Tab completion bug fix" -Tags "CI" { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index d75510eb1ef..b8b1cc607a5 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "TabCompletion" -Tags CI { BeforeAll { @@ -34,12 +34,12 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString(' } - It 'Should complete dotnet method with null conditional operator' -skip:$nullConditionalFeatureDisabled { + It 'Should complete dotnet method with null conditional operator' -Skip:$nullConditionalFeatureDisabled { $res = TabExpansion2 -inputScript '(1)?.ToSt' -cursorColumn '(1)?.ToSt'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString(' } - It 'Should complete dotnet method with null conditional operator without first letter' -skip:$nullConditionalFeatureDisabled { + It 'Should complete dotnet method with null conditional operator without first letter' -Skip:$nullConditionalFeatureDisabled { $res = TabExpansion2 -inputScript '(1)?.' -cursorColumn '(1)?.'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CompareTo(' } @@ -147,18 +147,18 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches.Count | Should -BeGreaterThan 0 } - It 'Should complete keyword' -skip { + It 'Should complete keyword' -Skip { $res = TabExpansion2 -inputScript 'using nam' -cursorColumn 'using nam'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'namespace' } - It 'Should first suggest -Full and then -Functionality when using Get-Help -Fu' -skip { + It 'Should first suggest -Full and then -Functionality when using Get-Help -Fu' -Skip { $res = TabExpansion2 -inputScript 'Get-Help -Fu' -cursorColumn 'Get-Help -Fu'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Full' $res.CompletionMatches[1].CompletionText | Should -BeExactly '-Functionality' } - It 'Should first suggest -Full and then -Functionality when using help -Fu' -skip { + It 'Should first suggest -Full and then -Functionality when using help -Fu' -Skip { $res = TabExpansion2 -inputScript 'help -Fu' -cursorColumn 'help -Fu'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Full' $res.CompletionMatches[1].CompletionText | Should -BeExactly '-Functionality' @@ -349,7 +349,7 @@ Describe "TabCompletion" -Tags CI { } } $line = "$nativeCommand --f" - $res = TaBexpansion2 -inputScript $line -cursorColumn $line.Length + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches.CompletionText | Should -BeExactly "--flag" } @@ -365,7 +365,7 @@ Describe "TabCompletion" -Tags CI { } } $line = "$nativeCommand -o" - $res = TaBexpansion2 -inputScript $line -cursorColumn $line.Length + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches.CompletionText | Should -BeExactly "-option" } @@ -380,8 +380,8 @@ Describe "TabCompletion" -Tags CI { Context "Script name completion" { BeforeAll { - setup -f 'install-powershell.ps1' -content "" - setup -f 'remove-powershell.ps1' -content "" + Setup -f 'install-powershell.ps1' -Content "" + Setup -f 'remove-powershell.ps1' -Content "" $scriptWithWildcardCases = @( @{ @@ -415,7 +415,7 @@ Describe "TabCompletion" -Tags CI { Pop-Location } - it "Input should successfully complete" -TestCases $scriptWithWildcardCases { + It "Input should successfully complete" -TestCases $scriptWithWildcardCases { param($command, $expectedCommand) $res = TabExpansion2 -inputScript $command -cursorColumn $command.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 @@ -699,7 +699,7 @@ Describe "TabCompletion" -Tags CI { ## if $PSHOME contains a space tabcompletion adds ' around the path @{ inputStr = 'cd $PSHOME\Modu'; expected = if($PSHOME.Contains(' ')) { "'$(Join-Path $PSHOME 'Modules')'" } else { Join-Path $PSHOME 'Modules' }; setup = $null } @{ inputStr = 'cd "$PSHOME\Modu"'; expected = "`"$(Join-Path $PSHOME 'Modules')`""; setup = $null } - @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" } else { Join-Path $PSHOME 'System.Management.Automation.dll'; setup = $null }} + @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" } else { Join-Path $PSHOME 'System.Management.Automation.dll'; Setup = $null }} @{ inputStr = '"$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null } @{ inputStr = '& "$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null } ## tab completion AST-based tests @@ -1249,7 +1249,7 @@ dir -Recurse ` $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 - $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected + $res.CompletionMatches[0].CompletionText | Should -Be $expected } } diff --git a/test/powershell/Installer/WindowsInstaller.Tests.ps1 b/test/powershell/Installer/WindowsInstaller.Tests.ps1 index fbf7fffc0a8..d1ce05e8f23 100644 --- a/test/powershell/Installer/WindowsInstaller.Tests.ps1 +++ b/test/powershell/Installer/WindowsInstaller.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Windows Installer" -Tags "Scenario" { @@ -13,7 +13,7 @@ Describe "Windows Installer" -Tags "Scenario" { ) } - It "WiX (Windows Installer XML) file contains pre-requisites link $preRequisitesLink" -skip:$skipTest { + It "WiX (Windows Installer XML) file contains pre-requisites link $preRequisitesLink" -Skip:$skipTest { $wixProductFile = Join-Path -Path $PSScriptRoot -ChildPath "..\..\..\assets\Product.wxs" (Get-Content $wixProductFile -Raw).Contains($preRequisitesLink) | Should -BeTrue } @@ -21,7 +21,7 @@ Describe "Windows Installer" -Tags "Scenario" { ## Running 'Invoke-WebRequest' with WMF download URLs has been failing intermittently, ## because sometimes the URLs lead to a 'this download is no longer available' page. ## We use a retry logic here. Retry for 5 times with 1 second interval. - It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -skip:$skipTest { + It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -Skip:$skipTest { param ($Url) foreach ($i in 1..5) { diff --git a/test/powershell/Language/Classes/MSFT_778492.psm1 b/test/powershell/Language/Classes/MSFT_778492.psm1 index 52a0efb47a5..e17710f0e8e 100644 --- a/test/powershell/Language/Classes/MSFT_778492.psm1 +++ b/test/powershell/Language/Classes/MSFT_778492.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. $foo = 'MSFT_778492 script scope' diff --git a/test/powershell/Language/Classes/ProtectedAccess.Tests.ps1 b/test/powershell/Language/Classes/ProtectedAccess.Tests.ps1 index 4b37e6a1a4a..d9dc808b0d7 100644 --- a/test/powershell/Language/Classes/ProtectedAccess.Tests.ps1 +++ b/test/powershell/Language/Classes/ProtectedAccess.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Add-Type -WarningAction Ignore @' diff --git a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 index e0ba18ae26d..3df42931855 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Attributes.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Attributes Test' -Tags "CI" { diff --git a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 index 3641323018d..9bef836e19b 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Positive Parse Properties Tests' -Tags "CI" { @@ -105,7 +105,7 @@ Describe 'Positive Parse Properties Tests' -Tags "CI" { class C12c { [void] f() { [System.Management.Automation.Host.Rectangle]$foo = [System.Management.Automation.Host.Rectangle]::new(0, 0, 0, 0) } } } - context "Positive ParseMethods return type Test" { + Context "Positive ParseMethods return type Test" { # Method with return type of self class C9 { [C9] f() { return [C9]::new() } } $c9 = [C9]::new().f() @@ -710,7 +710,7 @@ visibleX visibleY # Get-Member should not include hidden members by default $member = $instance | Get-Member hiddenZ - it "Get-Member should not find hidden member w/o -Force" { $member | Should -BeNullOrEmpty } + It "Get-Member should not find hidden member w/o -Force" { $member | Should -BeNullOrEmpty } # Get-Member should include hidden members with -Force $member = $instance | Get-Member hiddenZ -Force @@ -742,10 +742,10 @@ Describe 'Scoped Types Test' -Tags "CI" { { class C1 { [string] GetContext() { return "f2 scope" } } - return (new-object C1).GetContext() + return (New-Object C1).GetContext() } - It "New-Object at test scope" { (new-object C1).GetContext() | Should -BeExactly "Test scope" } + It "New-Object at test scope" { (New-Object C1).GetContext() | Should -BeExactly "Test scope" } It "[C1]::new() at test scope" { [C1]::new().GetContext() | Should -BeExactly "Test scope" } It "[C1]::new() in nested scope" { (f1) | Should -BeExactly "f1 scope" } @@ -804,7 +804,7 @@ Describe 'Type building' -Tags "CI" { Describe 'RuntimeType created for TypeDefinitionAst' -Tags "CI" { - It 'can make cast to the right RuntimeType in two different contexts' -pending { + It 'can make cast to the right RuntimeType in two different contexts' -Pending { $ssfe = [System.Management.Automation.Runspaces.SessionStateFunctionEntry]::new("foo", @' class Base diff --git a/test/powershell/Language/Classes/Scripting.Classes.Break.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Break.Tests.ps1 index ead2ed5ee20..20aab127abc 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Break.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Break.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Break statements with classes' -Tags "CI" { diff --git a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 index 3c10419afa4..d4b6e77a290 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Exceptions.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Exceptions flow for classes' -Tags "CI" { diff --git a/test/powershell/Language/Classes/Scripting.Classes.MiscOps.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.MiscOps.Tests.ps1 index 0b7be62ebeb..11880bf7dce 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.MiscOps.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.MiscOps.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Misc Test' -Tags "CI" { @@ -63,10 +63,10 @@ Describe 'Misc Test' -Tags "CI" { $NewRunspaceFunctionDefinitions = @" ## Define 'Get-TestText' in the new Runspace function Get-TestText { return '$ExpectedTextFromUnboundInstance' } - + ## Define the function to create an instance of the given type using the default constructor function New-UnboundInstance([Type]`$type) { `$type::new() } - + ## Define the function to call 'Foo()' on the given C1 instance, and return the result function Run-Foo(`$C1Instance) { `$C1Instance.Foo() } "@ diff --git a/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 index 0bd882013b8..c2e376f10cf 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.Modules.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'PSModuleInfo.GetExportedTypeDefinitions()' -Tags "CI" { It "doesn't throw for any module" { diff --git a/test/powershell/Language/Classes/Scripting.Classes.RunPath.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.RunPath.Tests.ps1 index 85c78a74948..e6545d0ed28 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.RunPath.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.RunPath.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Script with a class definition run path" -Tags "CI" { diff --git a/test/powershell/Language/Classes/Scripting.Classes.StaticMethod.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.StaticMethod.Tests.ps1 index 687877c06a2..e99a96a504a 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.StaticMethod.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.StaticMethod.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Additional static method tests" -Tags "CI" { @@ -32,7 +32,7 @@ class Foo { static [string] $Name static Foo() { [Foo]::Name = Get-Name } - + static [string] GetName() { return (Get-AnotherName) @@ -80,7 +80,7 @@ class Foo } It "Static constructor should run in the triggering Runspace if the class has been defined in that Runspace" { - + ## The static constructor is triggered by accessing '[Foo]::Name' which happens in the current Runspace. ## The class 'Foo' has been defined in the current Runspace, so it uses the current Runspace to run the ## static constructor. @@ -107,7 +107,7 @@ class Foo ## Define the functions that [Foo] depends on in PS2 Runspace. RunScriptInPS -PowerShell $ps2 -Script "function Get-Name { 'PS2 Runspace - Name' }" -IgnoreResult RunScriptInPS -PowerShell $ps2 -Script "function Get-AnotherName { 'PS2 Runspace - AnotherName' }" -IgnoreResult - + ## Define the function to call the static method 'GetName' on the passed-in type RunScriptInPS -PowerShell $ps2 -Script 'function Call-GetName([type] $type) { $type::GetName() }' -IgnoreResult diff --git a/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 b/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 index 70089cb5f8e..97f69982e21 100644 --- a/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.Classes.NestedModules.tests.ps1 @@ -1,43 +1,42 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe 'NestedModules' -Tags "CI" { - - function New-TestModule { - param( - [string]$Name, - [string]$Content, - [string[]]$NestedContents - ) - new-item -type directory -Force "TestDrive:\$Name" > $null - $manifestParams = @{ - Path = "TestDrive:\$Name\$Name.psd1" - } +Describe 'NestedModules' -Tags "CI" { + BeforeAll { + function New-TestModule { + param( + [string]$Name, + [string]$Content, + [string[]]$NestedContents + ) + + New-Item -type directory -Force "TestDrive:\$Name" > $null + $manifestParams = @{ + Path = "TestDrive:\$Name\$Name.psd1" + } - if ($Content) { - Set-Content -Path "${TestDrive}\$Name\$Name.psm1" -Value $Content - $manifestParams['RootModule'] = "$Name.psm1" - } + if ($Content) { + Set-Content -Path "${TestDrive}\$Name\$Name.psm1" -Value $Content + $manifestParams['RootModule'] = "$Name.psm1" + } - if ($NestedContents) { - $manifestParams['NestedModules'] = 1..$NestedContents.Count | ForEach-Object { - $null = new-item -type directory TestDrive:\$Name\Nested$_ - $null = Set-Content -Path "${TestDrive}\$Name\Nested$_\Nested$_.psm1" -Value $NestedContents[$_ - 1] - "Nested$_" + if ($NestedContents) { + $manifestParams['NestedModules'] = 1..$NestedContents.Count | ForEach-Object { + $null = New-Item -type directory TestDrive:\$Name\Nested$_ + $null = Set-Content -Path "${TestDrive}\$Name\Nested$_\Nested$_.psm1" -Value $NestedContents[$_ - 1] + "Nested$_" + } } - } - New-ModuleManifest @manifestParams + New-ModuleManifest @manifestParams - $resolvedTestDrivePath = Split-Path ((get-childitem TestDrive:\)[0].FullName) - if (-not ($env:PSModulePath -like "*$resolvedTestDrivePath*")) { - $env:PSModulePath += "$([System.IO.Path]::PathSeparator)$resolvedTestDrivePath" + $resolvedTestDrivePath = Split-Path ((Get-ChildItem TestDrive:\)[0].FullName) + if (-not ($env:PSModulePath -like "*$resolvedTestDrivePath*")) { + $env:PSModulePath += "$([System.IO.Path]::PathSeparator)$resolvedTestDrivePath" + } } - } - $originalPSModulePath = $env:PSModulePath - - try { + $originalPSModulePath = $env:PSModulePath # Create modules in TestDrive:\ New-TestModule -Name NoRoot -NestedContents @( @@ -54,72 +53,74 @@ Describe 'NestedModules' -Tags "CI" { 'class A { [string] foo() { return "A"} }', 'class B { [string] foo() { return "B"} }' ) -Content 'class C { [string] foo() { return "C"} }' + } + + AfterAll { + $env:PSModulePath = $originalPSModulePath + Get-Module @('ABC', 'NoRoot', 'WithRoot') | Remove-Module + } - It 'Get-Module is able to find types' { - $module = Get-Module NoRoot -ListAvailable - $module.GetExportedTypeDefinitions().Count | Should -Be 1 - $module = Get-Module WithRoot -ListAvailable - $module.GetExportedTypeDefinitions().Count | Should -Be 1 + It 'Get-Module is able to find types' { + $module = Get-Module NoRoot -ListAvailable + $module.GetExportedTypeDefinitions().Count | Should -Be 1 - $module = Get-Module ABC -ListAvailable - $module.GetExportedTypeDefinitions().Count | Should -Be 3 - } + $module = Get-Module WithRoot -ListAvailable + $module.GetExportedTypeDefinitions().Count | Should -Be 1 - It 'Import-Module pick the right type' { - $module = Import-Module ABC -PassThru - $module.GetExportedTypeDefinitions().Count | Should -Be 3 - $module = Import-Module ABC -PassThru -Force - $module.GetExportedTypeDefinitions().Count | Should -Be 3 - - $module = Import-Module NoRoot -PassThru - $module.GetExportedTypeDefinitions().Count | Should -Be 1 - $module = Import-Module NoRoot -PassThru -Force - $module.GetExportedTypeDefinitions().Count | Should -Be 1 - [scriptblock]::Create(@' + $module = Get-Module ABC -ListAvailable + $module.GetExportedTypeDefinitions().Count | Should -Be 3 + } + + It 'Import-Module pick the right type' { + $module = Import-Module ABC -PassThru + $module.GetExportedTypeDefinitions().Count | Should -Be 3 + $module = Import-Module ABC -PassThru -Force + $module.GetExportedTypeDefinitions().Count | Should -Be 3 + + $module = Import-Module NoRoot -PassThru + $module.GetExportedTypeDefinitions().Count | Should -Be 1 + $module = Import-Module NoRoot -PassThru -Force + $module.GetExportedTypeDefinitions().Count | Should -Be 1 + [scriptblock]::Create(@' using module NoRoot [A]::new().foo() '@ ).Invoke() | Should -Be A2 - $module = Import-Module WithRoot -PassThru - $module.GetExportedTypeDefinitions().Count | Should -Be 1 - $module = Import-Module WithRoot -PassThru -Force - $module.GetExportedTypeDefinitions().Count | Should -Be 1 - [scriptblock]::Create(@' + $module = Import-Module WithRoot -PassThru + $module.GetExportedTypeDefinitions().Count | Should -Be 1 + $module = Import-Module WithRoot -PassThru -Force + $module.GetExportedTypeDefinitions().Count | Should -Be 1 + [scriptblock]::Create(@' using module WithRoot [A]::new().foo() '@ ).Invoke() | Should -Be A0 - } - - Context 'execute type creation in the module context' { - - # let's define types to make it more fun - class A { [string] foo() { return "local"} } - class B { [string] foo() { return "local"} } - class C { [string] foo() { return "local"} } - - # We need to think about it: should it work or not. - # Currently, types are resolved in compile-time to the 'local' versions - # So at runtime we don't call the module versions. - It 'Can execute type creation in the module context with new()' -pending { - & (Get-Module ABC) { [C]::new().foo() } | Should -Be C - & (Get-Module NoRoot) { [A]::new().foo() } | Should -Be A2 - & (Get-Module WithRoot) { [A]::new().foo() } | Should -Be A0 - & (Get-Module ABC) { [A]::new().foo() } | Should -Be A - } + } - It 'Can execute type creation in the module context with New-Object' { - & (Get-Module ABC) { (New-Object C).foo() } | Should -Be C - & (Get-Module NoRoot) { (New-Object A).foo() } | Should -Be A2 - & (Get-Module WithRoot) { (New-Object A).foo() } | Should -Be A0 - & (Get-Module ABC) { (New-Object A).foo() } | Should -Be A - } + Context 'execute type creation in the module context' { + + # let's define types to make it more fun + class A { [string] foo() { return "local"} } + class B { [string] foo() { return "local"} } + class C { [string] foo() { return "local"} } + + # We need to think about it: should it work or not. + # Currently, types are resolved in compile-time to the 'local' versions + # So at runtime we don't call the module versions. + It 'Can execute type creation in the module context with new()' -Pending { + & (Get-Module ABC) { [C]::new().foo() } | Should -Be C + & (Get-Module NoRoot) { [A]::new().foo() } | Should -Be A2 + & (Get-Module WithRoot) { [A]::new().foo() } | Should -Be A0 + & (Get-Module ABC) { [A]::new().foo() } | Should -Be A } - } finally { - $env:PSModulePath = $originalPSModulePath - Get-Module @('ABC', 'NoRoot', 'WithRoot') | Remove-Module + It 'Can execute type creation in the module context with New-Object' { + & (Get-Module ABC) { (New-Object C).foo() } | Should -Be C + & (Get-Module NoRoot) { (New-Object A).foo() } | Should -Be A2 + & (Get-Module WithRoot) { (New-Object A).foo() } | Should -Be A0 + & (Get-Module ABC) { (New-Object A).foo() } | Should -Be A + } } } diff --git a/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 b/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 index 073ab06a67c..cf304d5918e 100644 --- a/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Classes inheritance syntax' -Tags "CI" { @@ -103,7 +103,7 @@ Describe 'Classes inheritance syntax' -Tags "CI" { [void]ExitNestedPrompt(){ throw "Unsupported" } [void]NotifyBeginApplication() { } [void]NotifyEndApplication() { } - [string]get_Name() { return $this.myName; write-host "MyName" } + [string]get_Name() { return $this.myName; Write-Host "MyName" } [version]get_Version() { return $this.myVersion } [System.Globalization.CultureInfo]get_CurrentCulture() { return $this.myCurrentCulture } [System.Globalization.CultureInfo]get_CurrentUICulture() { return $this.myCurrentUICulture } diff --git a/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 b/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 index 88b32b8c8e0..fb3778463da 100644 --- a/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'using module' -Tags "CI" { BeforeAll { @@ -14,15 +14,15 @@ Describe 'using module' -Tags "CI" { ) if ($manifest) { - new-item -type directory -Force "${TestDrive}\$ModulePathPrefix\$Name\$Version" > $null + New-Item -type directory -Force "${TestDrive}\$ModulePathPrefix\$Name\$Version" > $null Set-Content -Path "${TestDrive}\$ModulePathPrefix\$Name\$Version\$Name.psm1" -Value $Content New-ModuleManifest -RootModule "$Name.psm1" -Path "${TestDrive}\$ModulePathPrefix\$Name\$Version\$Name.psd1" -ModuleVersion $Version } else { - new-item -type directory -Force "${TestDrive}\$ModulePathPrefix\$Name" > $null + New-Item -type directory -Force "${TestDrive}\$ModulePathPrefix\$Name" > $null Set-Content -Path "${TestDrive}\$ModulePathPrefix\$Name\$Name.psm1" -Value $Content } - $resolvedTestDrivePath = Split-Path ((get-childitem "${TestDrive}\$ModulePathPrefix")[0].FullName) + $resolvedTestDrivePath = Split-Path ((Get-ChildItem "${TestDrive}\$ModulePathPrefix")[0].FullName) if (-not ($env:PSModulePath -like "*$resolvedTestDrivePath*")) { $env:PSModulePath += "$([System.IO.Path]::PathSeparator)$resolvedTestDrivePath" } @@ -339,7 +339,7 @@ using module Foo } } - Context 'Side by side' { + Context 'Side by side' { BeforeAll { # Add side-by-side module $newVersion = '3.4.5' @@ -416,7 +416,7 @@ function foo() } '@ # resolve name to absolute path - $scriptToProcessPath = (get-childitem $scriptToProcessPath).FullName + $scriptToProcessPath = (Get-ChildItem $scriptToProcessPath).FullName $iss = [System.Management.Automation.Runspaces.initialsessionstate]::CreateDefault() $iss.StartupScripts.Add($scriptToProcessPath) @@ -442,7 +442,7 @@ function foo() New-TestModule -Name FooForPaths -Content 'class Foo { [string] GetModuleName() { return "FooForPaths" } }' $env:PSModulePath = $originalPSModulePath - new-item -type directory -Force TestDrive:\FooRelativeConsumer + New-Item -type directory -Force TestDrive:\FooRelativeConsumer Set-Content -Path "${TestDrive}\FooRelativeConsumer\FooRelativeConsumer.ps1" -Value @' using module ..\modules\FooForPaths class Bar : Foo {} @@ -471,7 +471,7 @@ class Bar : Foo {} } It "can be accessed by absolute path" { - $resolvedTestDrivePath = Split-Path ((get-childitem TestDrive:\modules)[0].FullName) + $resolvedTestDrivePath = Split-Path ((Get-ChildItem TestDrive:\modules)[0].FullName) $s = @" using module $resolvedTestDrivePath\FooForPaths [Foo]::new() @@ -483,7 +483,7 @@ using module $resolvedTestDrivePath\FooForPaths } It "can be accessed by absolute path with file extension" { - $resolvedTestDrivePath = Split-Path ((get-childitem TestDrive:\modules)[0].FullName) + $resolvedTestDrivePath = Split-Path ((Get-ChildItem TestDrive:\modules)[0].FullName) $barObject = [scriptblock]::Create(@" using module $resolvedTestDrivePath\FooForPaths\FooForPaths.psm1 [Foo]::new() @@ -523,6 +523,19 @@ using module FooForPaths Pop-Location } } + + It 'can be accessed by relative path with .' -TestCases @( + @{ Separator = '\' }, + @{ Separator = '/' } + ) { + param([string]$Separator) + $name = 'relative-slash-paths' + 'function Get-TestString { "Worked" }' | Set-Content "TestDrive:\modules\$name.psm1" + + "using module .$Separator$name.psm1; Get-TestString" | Set-Content "TestDrive:\modules\$name.ps1" + + & "TestDrive:\modules\$name.ps1" | Should -BeExactly "Worked" + } } Context "module has non-terminating error handled with 'SilentlyContinue'" { @@ -547,4 +560,3 @@ using module $testFile } } } - diff --git a/test/powershell/Language/Classes/scripting.enums.tests.ps1 b/test/powershell/Language/Classes/scripting.enums.tests.ps1 index a3a86863a0a..f11f294a0a5 100644 --- a/test/powershell/Language/Classes/scripting.enums.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.enums.tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'enums' -Tags "CI" { diff --git a/test/powershell/Language/CompletionTestSupport.psm1 b/test/powershell/Language/CompletionTestSupport.psm1 index 3490830c481..a5942d4a259 100644 --- a/test/powershell/Language/CompletionTestSupport.psm1 +++ b/test/powershell/Language/CompletionTestSupport.psm1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. class CompletionResult diff --git a/test/powershell/Language/Interop/DotNet/DotNetAPI.Tests.ps1 b/test/powershell/Language/Interop/DotNet/DotNetAPI.Tests.ps1 index 07d1c9995fe..65b9e61a6a7 100644 --- a/test/powershell/Language/Interop/DotNet/DotNetAPI.Tests.ps1 +++ b/test/powershell/Language/Interop/DotNet/DotNetAPI.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "DotNetAPI" -Tags "CI" { diff --git a/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 b/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 index c7d63a13522..02d49c4435c 100644 --- a/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 +++ b/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Handle ByRef-like types gracefully" -Tags "CI" { diff --git a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 index 2c0847dee63..76069143327 100644 --- a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 @@ -1,6 +1,6 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Describe "ComparisonOperator" -tag "CI" { +Describe "ComparisonOperator" -Tag "CI" { It "Should be for " -TestCases @( @{lhs = 1; operator = "-lt"; rhs = 2; result = $true}, @@ -84,7 +84,7 @@ Describe "ComparisonOperator" -tag "CI" { } } -Describe "Bytewise Operator" -tag "CI" { +Describe "Bytewise Operator" -Tag "CI" { It "Test -bor on enum with [byte] as underlying type" { $result = [System.Security.AccessControl.AceFlags]::ObjectInherit -bxor ` diff --git a/test/powershell/Language/Operators/NullConditional.Tests.ps1 b/test/powershell/Language/Operators/NullConditional.Tests.ps1 index f78455af6f0..5c2c65e4ad9 100644 --- a/test/powershell/Language/Operators/NullConditional.Tests.ps1 +++ b/test/powershell/Language/Operators/NullConditional.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'NullCoalesceOperations' -Tags 'CI' { @@ -172,6 +172,18 @@ Describe 'NullCoalesceOperations' -Tags 'CI' { It 'Lhs is $?' { {$???$false} | Should -BeTrue } + + It 'Should only evaluate LHS once when it IS null' { + $testState = [pscustomobject]@{ Value = 0 } + (& { [void]$testState.Value++ }) ?? 'Nothing' | Should -BeExactly 'Nothing' + $testState.Value | Should -Be 1 + } + + It 'Should only evaluate LHS once when it is NOT null' { + $testState = [pscustomobject]@{ Value = 0 } + (& { 'Test'; [void]$testState.Value++ }) ?? 'Nothing' | Should -BeExactly 'Test' + $testState.Value | Should -Be 1 + } } Context 'Null Coalesce ?? operator precedence' { @@ -296,7 +308,6 @@ Describe 'NullConditionalMemberAccess' -Tag 'CI' { ${array}?.length | Should -Be 3 ${hash}?.a | Should -Be 1 - (Get-Process -Id $PID)?.Name | Should -BeLike "pwsh*" (Get-Item $TestDrive)?.EnumerateFiles()?.Name | Should -BeExactly 'testfile.txt' [int32]::MaxValue?.ToString() | Should -BeExactly '2147483647' @@ -360,8 +371,8 @@ Describe 'NullConditionalMemberAccess' -Tag 'CI' { It 'Use ?. on a dynamic property name' { $testContent = @' - $propName = 'Name' - (Get-Process -Id $PID)?.$propName | Should -BeLike 'pwsh*' + $propName = 'SI' + (Get-Process -Id $PID)?.$propName | Should -Be (Get-Process -id $PID).SessionId ${doesNotExist}?.$propName() | Should -BeNullOrEmpty '@ diff --git a/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 b/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 index dfac35d1bb9..e2e54c32170 100644 --- a/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Experimental Feature: && and || operators - Feature-Enabled" -Tag CI { @@ -341,6 +341,6 @@ function Test-FullyTerminatingError It "Recognises invalid assignment" { { Invoke-Expression -Command '$x = $x, $y += $z = testexe -returncode 0 && testexe -returncode 1' - } | Should -Throw -ErrorID 'InvalidLeftHandSide,Microsoft.PowerShell.Commands.InvokeExpressionCommand' + } | Should -Throw -ErrorId 'InvalidLeftHandSide,Microsoft.PowerShell.Commands.InvokeExpressionCommand' } } diff --git a/test/powershell/Language/Operators/RangeOperator.Tests.ps1 b/test/powershell/Language/Operators/RangeOperator.Tests.ps1 index 12e98ac4f4c..56941827fcc 100644 --- a/test/powershell/Language/Operators/RangeOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/RangeOperator.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Range Operator" -Tags CI { Context "Range integer operations" { diff --git a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 index a818725a871..59d7039898a 100644 --- a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Replace Operator" -Tags CI { diff --git a/test/powershell/Language/Operators/SplitOperator.Tests.ps1 b/test/powershell/Language/Operators/SplitOperator.Tests.ps1 index 68550ea3c48..1ebbbff4fa2 100644 --- a/test/powershell/Language/Operators/SplitOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/SplitOperator.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Split Operator" -Tags CI { Context "Binary split operator" { diff --git a/test/powershell/Language/Operators/TernaryOperator.Tests.ps1 b/test/powershell/Language/Operators/TernaryOperator.Tests.ps1 index 9ab4846d6bb..32928474144 100644 --- a/test/powershell/Language/Operators/TernaryOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/TernaryOperator.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "Using of ternary operator" -Tags CI { @@ -22,7 +22,7 @@ Describe "Using of ternary operator" -Tags CI { @{ Script = { @{name = 'name'}.Contains('name') ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } @{ Script = { (Test-Path Env:\NonExist) ? 'true' : 'false' }; ExpectedValue = 'false' } @{ Script = { (Test-Path Env:\PSModulePath) ? 'true' : 'false' }; ExpectedValue = 'true' } - @{ Script = { $($p = Get-Process -Id $PID; $p.Name -eq 'pwsh') ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } + @{ Script = { $($p = Get-Process -Id $PID; $p.Id -eq $PID) ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } @{ Script = { ($a = 1) ? 2 : 3 }; ExpectedValue = 2 } @{ Script = { $($a = 1) ? 2 : 3 }; ExpectedValue = 3 } @{ Script = { (Write-Warning -Message warning -WarningAction SilentlyContinue) ? 1 : 2 }; ExpectedValue = 2 } @@ -31,7 +31,7 @@ Describe "Using of ternary operator" -Tags CI { ## Condition: unary and binary expression expressions @{ Script = { -not $IsCoreCLR ? 'Desktop' : 'Core' }; ExpectedValue = 'Core' } @{ Script = { $PSEdition -eq 'Core' ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } - @{ Script = { $IsCoreCLR -and (Get-Process -Id $PID).Name -eq 'pwsh' ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } + @{ Script = { $IsCoreCLR -and (Get-Process -Id $PID).Id -eq $PID ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } @{ Script = { $IsCoreCLR -and 'pwsh' -match 'p.*h' ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } @{ Script = { 1,2,3 -contains 2 ? 'Core' : 'Desktop' }; ExpectedValue = 'Core' } @@ -40,7 +40,7 @@ Describe "Using of ternary operator" -Tags CI { @{ Script = { $IsCoreCLR ? $false ? 'nested-if-true' : $true ? 'nested-nested-if-true' : 'nested-nested-if-false' : 'if-false' }; ExpectedValue = 'nested-nested-if-true' } ## Binary operator has higher precedence order than ternary - @{ Script = { !$IsCoreCLR ? 'Core' : 'Desktop' -eq 'Core' }; ExpectedValue = !$IsCoreCLR ? 'Core' : ('Desktop' -eq 'Core') } + @{ Script = { !$IsCoreCLR ? 'Core' : 'Desktop' -EQ 'Core' }; ExpectedValue = !$IsCoreCLR ? 'Core' : ('Desktop' -eq 'Core') } @{ Script = { ($IsCoreCLR ? 'Core' : 'Desktop') -eq 'Core' }; ExpectedValue = $true } ) } @@ -57,7 +57,7 @@ Describe "Using of ternary operator" -Tags CI { } It "Ternary expression which generates a terminating error should halt appropriately" { - { (write-error -Message error -ErrorAction Stop) ? 1 : 2 } | Should -Throw -ErrorId Microsoft.PowerShell.Commands.WriteErrorException + { (Write-Error -Message error -ErrorAction Stop) ? 1 : 2 } | Should -Throw -ErrorId Microsoft.PowerShell.Commands.WriteErrorException } It "Use ternary operator in parameter default values" { diff --git a/test/powershell/Language/Parser/Ast.Tests.ps1 b/test/powershell/Language/Parser/Ast.Tests.ps1 index 53e0320f59b..2f87e5c5120 100644 --- a/test/powershell/Language/Parser/Ast.Tests.ps1 +++ b/test/powershell/Language/Parser/Ast.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. using Namespace System.Management.Automation.Language Describe "The SafeGetValue method on AST returns safe values" -Tags "CI" { diff --git a/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 b/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 index 8265178de59..cef1861f807 100644 --- a/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 +++ b/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Automatic variable $input' -Tags "CI" { diff --git a/test/powershell/Language/Parser/BNotOperator.Tests.ps1 b/test/powershell/Language/Parser/BNotOperator.Tests.ps1 index 0b5e4c1bbdc..eb6dd934e30 100644 --- a/test/powershell/Language/Parser/BNotOperator.Tests.ps1 +++ b/test/powershell/Language/Parser/BNotOperator.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. $baseTypes = @{ diff --git a/test/powershell/Language/Parser/Conversions.Tests.ps1 b/test/powershell/Language/Parser/Conversions.Tests.ps1 index b5265c5e347..f9a981060cd 100644 --- a/test/powershell/Language/Parser/Conversions.Tests.ps1 +++ b/test/powershell/Language/Parser/Conversions.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'conversion syntax' -Tags "CI" { diff --git a/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 b/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 index 42785fc555c..3c9edd43915 100644 --- a/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 +++ b/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. <# Much of this script belongs in a module, but we don't support importing classes yet. @@ -108,7 +108,7 @@ function Test-Completions { $skip = $false if ( $expected.CompletionText -Match "System.Management.Automation.PerformanceData|System.Management.Automation.Security" ) { $skip = $true } - It ($expected.CompletionText) -skip:$skip { + It ($expected.CompletionText) -Skip:$skip { $expected.Found | Should -BeTrue } } @@ -435,7 +435,7 @@ Describe "ArgumentCompletionsAttribute tests" -Tags "CI" { param($attributeName, $cmdletName) $line = "$cmdletName -Alpha val" - $res = TaBexpansion2 -inputScript $line -cursorColumn $line.Length + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length $res.CompletionMatches.Count | Should -Be 3 $res.CompletionMatches.CompletionText -join " " | Should -BeExactly "value1 value2 value3" { TestArgumentCompletionsAttribute -Alpha unExpectedValue } | Should -Not -Throw @@ -445,7 +445,7 @@ Describe "ArgumentCompletionsAttribute tests" -Tags "CI" { param($attributeName, $cmdletName) $line = "$cmdletName -Param1 val" - $res = TaBexpansion2 -inputScript $line -cursorColumn $line.Length + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length $res.CompletionMatches.Count | Should -Be 3 $res.CompletionMatches.CompletionText -join " " | Should -BeExactly "value1 value2 value3" { TestArgumentCompletionsAttribute -Param1 unExpectedValue } | Should -Not -Throw diff --git a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 index 949cc6a15a0..b5a80b23155 100644 --- a/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 +++ b/test/powershell/Language/Parser/LanguageAndParser.TestFollowup.Tests.ps1 @@ -1,6 +1,6 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -$powershellexe = (get-process -id $PID).mainmodule.filename +$powershellexe = (Get-Process -Id $PID).mainmodule.filename Describe "Clone array" -Tags "CI" { It "Cast in target expr" { @@ -27,7 +27,7 @@ Describe "Set fields through PSMemberInfo" -Tags "CI" { ([AStruct]@{s = "abc" }).s | Should -BeExactly "abc" } It "via new-object" { - (new-object AStruct -prop @{s="abc"}).s | Should -BeExactly "abc" + (New-Object AStruct -prop @{s="abc"}).s | Should -BeExactly "abc" } It "via PSObject" { $x = [AStruct]::new() diff --git a/test/powershell/Language/Parser/LineContinuance.Tests.ps1 b/test/powershell/Language/Parser/LineContinuance.Tests.ps1 index 2bb5395119e..1bdf18525a3 100644 --- a/test/powershell/Language/Parser/LineContinuance.Tests.ps1 +++ b/test/powershell/Language/Parser/LineContinuance.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Line Continuance' -Tags 'CI' { diff --git a/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 b/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 index 69a6cdca9c3..f28b6801389 100644 --- a/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 +++ b/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. if ( $IsCoreCLR ) { return diff --git a/test/powershell/Language/Parser/ParameterBinding.Tests.ps1 b/test/powershell/Language/Parser/ParameterBinding.Tests.ps1 index ca6a9b2082e..7fd26912ead 100644 --- a/test/powershell/Language/Parser/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Parser/ParameterBinding.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe 'Argument transformation attribute on optional argument with explicit $null' -Tags "CI" { @@ -79,23 +79,23 @@ Describe 'Argument transformation attribute on optional argument with explicit $ It "Script function takes uint64" { Invoke-ScriptFunctionTakesUInt64 | Should -Be 42 } - it "csharp cmdlet takes object" { + It "csharp cmdlet takes object" { Invoke-CSharpCmdletTakesObject | Should -Be "passed in null" } - it "csharp cmdlet takes uint64" { + It "csharp cmdlet takes uint64" { Invoke-CSharpCmdletTakesUInt64 | Should -Be 0 } - it "script function takes object when parameter is null" { + It "script function takes object when parameter is null" { Invoke-ScriptFunctionTakesObject -Address $null | Should -Be 42 } - it "script function takes unit64 when parameter is null" { + It "script function takes unit64 when parameter is null" { Invoke-ScriptFunctionTakesUInt64 -Address $null | Should -Be 42 } - it "script csharp cmdlet takes object when parameter is null" { + It "script csharp cmdlet takes object when parameter is null" { Invoke-CSharpCmdletTakesObject -Address $null | Should -Be 42 } - it "script csharp cmdlet takes uint64 when parameter is null" { + It "script csharp cmdlet takes uint64 when parameter is null" { Invoke-CSharpCmdletTakesUInt64 -Address $null | Should -Be 42 } } @@ -425,3 +425,44 @@ Describe "Custom type conversion in parameter binding" -Tags 'Feature' { } } } + +Describe 'Roundtrippable Conversions for Bare-string Numeric Literals passed to [string] Parameters' -Tags CI { + + BeforeAll { + $TestValues = @( + @{ Argument = "34uy" } + @{ Argument = "48y" } + @{ Argument = "8s" } + @{ Argument = "49us" } + @{ Argument = "26" } + @{ Argument = "28u" } + @{ Argument = "24l" } + @{ Argument = "32ul" } + @{ Argument = "20d" } + @{ Argument = "6n" } + ) + + function Test-SimpleStringValue([string] $Value) { $Value } + function Test-AdvancedStringValue { + [CmdletBinding()] + param( + [string] + $Value + ) + + $Value + } + } + + It 'should correctly convert back to string in simple functions' -TestCases $TestValues { + param($Argument) + + Invoke-Expression "Test-SimpleStringValue -Value $Argument" | Should -BeExactly $Argument + } + + It 'should correctly convert back to string in advanced functions' -TestCases $TestValues { + param($Argument) + + Invoke-Expression "Test-AdvancedStringValue -Value $Argument" | Should -BeExactly $Argument + } +} diff --git a/test/powershell/Language/Parser/Parser.Tests.ps1 b/test/powershell/Language/Parser/Parser.Tests.ps1 index 5105f9e9e03..b3163ba2f27 100644 --- a/test/powershell/Language/Parser/Parser.Tests.ps1 +++ b/test/powershell/Language/Parser/Parser.Tests.ps1 @@ -1,4 +1,4 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. Describe "ParserTests (admin\monad\tests\monad\src\engine\core\ParserTests.cs)" -Tags "CI" { @@ -293,8 +293,8 @@ foo``u{2195}abc } It "Test that escaping any character with no special meaning just returns that char. (line 602)" { - $result = ExecuteCommand '"fo`obar"' - $result | Should -BeExactly "foobar" + $result = ExecuteCommand '"fo`odbar"' + $result | Should -BeExactly "foodbar" } Context "Test that we support all of the C# escape sequences. We use the ` instead of \. (line 613)" { @@ -703,7 +703,7 @@ foo``u{2195}abc if ( $IsLinux -or $IsMacOS ) { # because we execute on *nix based on executable bit, and the file name doesn't matter # so we can use the same filename as for windows, just make sure it's executable with chmod - "#!/bin/sh`necho ""Hello World""" | out-file -encoding ASCII $shellfile + "#!/bin/sh`necho ""Hello World""" | Out-File -Encoding ASCII $shellfile /bin/chmod +x $shellfile } else { @@ -931,6 +931,7 @@ foo``u{2195}abc @{ Script = "0x0y"; ExpectedValue = "0"; ExpectedType = [sbyte] } @{ Script = "0x41y"; ExpectedValue = "65"; ExpectedType = [sbyte] } @{ Script = "-0x41y"; ExpectedValue = "-65"; ExpectedType = [sbyte] } + @{ Script = "0xFFy"; ExpectedValue = "-1"; ExpectedType = [sbyte] } #Binary @{ Script = "0b0y"; ExpectedValue = "0"; ExpectedType = [sbyte] } @{ Script = "0b10y"; ExpectedValue = "2"; ExpectedType = [sbyte] } @@ -957,6 +958,7 @@ foo``u{2195}abc @{ Script = "0x0s"; ExpectedValue = "0"; ExpectedType = [short] } @{ Script = "0x41s"; ExpectedValue = "65"; ExpectedType = [short] } @{ Script = "-0x41s"; ExpectedValue = "-65"; ExpectedType = [short] } + @{ Script = "0xFFFFs"; ExpectedValue = "-1"; ExpectedType = [short] } #Binary @{ Script = "0b0s"; ExpectedValue = "0"; ExpectedType = [short] } @{ Script = "0b10s"; ExpectedValue = "2"; ExpectedType = [short] } @@ -985,6 +987,7 @@ foo``u{2195}abc @{ Script = "0x0l"; ExpectedValue = "0"; ExpectedType = [long] } @{ Script = "0x41l"; ExpectedValue = "65"; ExpectedType = [long] } @{ Script = "-0x41l"; ExpectedValue = "-65"; ExpectedType = [long] } + @{ Script = "0xFFFFFFFFFFFFFFFFl"; ExpectedValue = "-1"; ExpectedType = [long] } #Binary @{ Script = "0b0l"; ExpectedValue = "0"; ExpectedType = [long] } @{ Script = "0b10l"; ExpectedValue = "2"; ExpectedType = [long] } @@ -1078,6 +1081,7 @@ foo``u{2195}abc #Hexadecimal @{ Script = "0x0uy"; ExpectedValue = "0"; ExpectedType = [byte] } @{ Script = "0x41uy"; ExpectedValue = "65"; ExpectedType = [byte] } + @{ Script = "0xFFuy"; ExpectedValue = [byte]::MaxValue; ExpectedType = [byte] } #Binary @{ Script = "0b0uy"; ExpectedValue = "0"; ExpectedType = [byte] } @{ Script = "0b10uy"; ExpectedValue = "2"; ExpectedType = [byte] } @@ -1098,6 +1102,8 @@ foo``u{2195}abc #Hexadecimal @{ Script = "0x0us"; ExpectedValue = "0"; ExpectedType = [ushort] } @{ Script = "0x41us"; ExpectedValue = "65"; ExpectedType = [ushort] } + @{ Script = "0x41us"; ExpectedValue = "65"; ExpectedType = [ushort] } + @{ Script = "0xFFFFus"; ExpectedValue = [ushort]::MaxValue; ExpectedType = [ushort] } #Binary @{ Script = "0b0us"; ExpectedValue = "0"; ExpectedType = [ushort] } @{ Script = "0b10us"; ExpectedValue = "2"; ExpectedType = [ushort] } @@ -1119,6 +1125,7 @@ foo``u{2195}abc #Hexadecimal @{ Script = "0x0ul"; ExpectedValue = "0"; ExpectedType = [ulong] } @{ Script = "0x41ul"; ExpectedValue = "65"; ExpectedType = [ulong] } + @{ Script = "0xFFFFFFFFFFFFFFFFul"; ExpectedValue = [ulong]::MaxValue; ExpectedType = [ulong] } #Binary @{ Script = "0b0ul"; ExpectedValue = "0"; ExpectedType = [ulong] } @{ Script = "0b10ul"; ExpectedValue = "2"; ExpectedType = [ulong] } diff --git a/test/powershell/Language/Parser/Parsing.Tests.ps1 b/test/powershell/Language/Parser/Parsing.Tests.ps1 index 8b79d994744..9f213ecf14c 100644 --- a/test/powershell/Language/Parser/Parsing.Tests.ps1 +++ b/test/powershell/Language/Parser/Parsing.Tests.ps1 @@ -1,6 +1,6 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -set-strictmode -v 2 +Set-StrictMode -v 2 Describe 'for statement parsing' -Tags "CI" { ShouldBeParseError 'for' MissingOpenParenthesisAfterKeyword 4 -CheckColumnNumber @@ -479,3 +479,165 @@ Describe "ParserError type tests" -Tag CI { } } } + +Describe "Keywords 'default', 'hidden', 'in', 'static' Token parsing" -Tags CI { + BeforeAll { + $testCases_basic = @( + @{ + Script = 'switch (1) {default {0} 1 {1}}' + TokensToCheck = @{ + 5 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Default + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::Keyword + } + } + } + @{ + Script = 'switch (1) {"default" {0} 1 {1}}' + TokensToCheck = @{ + 5 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::StringExpandable + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::None + } + } + } + @{ + Script = 'switch (1) {adefault {0} 1 {1}}' + TokensToCheck = @{ + 5 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Identifier + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::None + } + } + } + @{ + Script = 'foreach ($i in 1..2) {$i}' + TokensToCheck = @{ + 3 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::In + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::Keyword + } + } + } + @{ + Script = 'class test {hidden $a; static aMethod () {return $this.a} }' + TokensToCheck = @{ + 3 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Hidden + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::Keyword + } + 6 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Static + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::Keyword + } + } + } + @{ + Script = 'echo default hidden in static' + TokensToCheck = @{ + 1 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Generic + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::None + } + 2 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Generic + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::None + } + 3 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Generic + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::None + } + 4 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Generic + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::None + } + } + } + @{ + Script = 'default' + TokensToCheck = @{ + 0 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Default + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword -bor [System.Management.Automation.Language.TokenFlags]::CommandName + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::CommandName + } + } + } + @{ + Script = 'hidden' + TokensToCheck = @{ + 0 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Hidden + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword -bor [System.Management.Automation.Language.TokenFlags]::CommandName + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::CommandName + } + } + } + @{ + Script = 'in' + TokensToCheck = @{ + 0 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::In + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword -bor [System.Management.Automation.Language.TokenFlags]::CommandName + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::CommandName + } + } + } + @{ + Script = 'static' + TokensToCheck = @{ + 0 = @{ + TokenKind = [System.Management.Automation.Language.TokenKind]::Static + TokenFlags_Mask = [System.Management.Automation.Language.TokenFlags]::Keyword -bor [System.Management.Automation.Language.TokenFlags]::CommandName + TokenFlags_Value = [System.Management.Automation.Language.TokenFlags]::CommandName + } + } + } + ) + } + + AfterAll { + } + + It "Keywords 'default', 'hidden', 'in', 'static' in {