diff --git a/.appveyor.yml b/.appveyor.yml index 31efd819..5057e312 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -7,7 +7,7 @@ branches: - dev - /^(.*\/)?ci-.*$/ build_script: - - ps: .\build.ps1 + - ps: .\run.ps1 build clone_depth: 1 environment: global: diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..2641e32c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,10 @@ +root = true +indent_style = space +trim_trailing_whitespace = true +insert_final_newline = true + +[*.{xml,csproj,props,targets,config}] +indent_size = 2 + +[*.cs] +indent_size = 4 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b10be142..00000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: csharp -sudo: false -dist: trusty -env: - global: - - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true - - DOTNET_CLI_TELEMETRY_OPTOUT: 1 -mono: none -os: - - linux - - osx -osx_image: xcode8.2 -addons: - apt: - packages: - - libunwind8 -branches: - only: - - master - - release - - dev - - /^(.*\/)?ci-.*$/ -before_install: - - if test "$TRAVIS_OS_NAME" == "osx"; then brew update; brew install openssl; ln -s /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib /usr/local/lib/; ln -s /usr/local/opt/openssl/lib/libssl.1.0.0.dylib /usr/local/lib/; fi -script: - - ./build.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 64ff041d..00000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,4 +0,0 @@ -Contributing -====== - -Information on contributing to this repo is in the [Contributing Guide](https://github.com/aspnet/Home/blob/dev/CONTRIBUTING.md) in the Home repo. diff --git a/CommandLineUtils.sln b/CommandLineUtils.sln new file mode 100644 index 00000000..f44d0205 --- /dev/null +++ b/CommandLineUtils.sln @@ -0,0 +1,56 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{95D4B35E-0A21-4D64-8BAF-27DD6C019FC5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "McMaster.Extensions.CommandLineUtils", "src\CommandLineUtils\McMaster.Extensions.CommandLineUtils.csproj", "{CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{C4842A1B-019E-40FF-A396-CF5AFDE8FA54}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "McMaster.Extensions.CommandLineUtils.Tests", "test\CommandLineUtils.Tests\McMaster.Extensions.CommandLineUtils.Tests.csproj", "{1258544C-1FDE-4810-9A1B-189A925E9B45}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Debug|x64.ActiveCfg = Debug|x64 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Debug|x64.Build.0 = Debug|x64 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Debug|x86.ActiveCfg = Debug|x86 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Debug|x86.Build.0 = Debug|x86 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Release|Any CPU.Build.0 = Release|Any CPU + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Release|x64.ActiveCfg = Release|x64 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Release|x64.Build.0 = Release|x64 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Release|x86.ActiveCfg = Release|x86 + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E}.Release|x86.Build.0 = Release|x86 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Debug|x64.ActiveCfg = Debug|x64 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Debug|x64.Build.0 = Debug|x64 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Debug|x86.ActiveCfg = Debug|x86 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Debug|x86.Build.0 = Debug|x86 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Release|Any CPU.Build.0 = Release|Any CPU + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Release|x64.ActiveCfg = Release|x64 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Release|x64.Build.0 = Release|x64 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Release|x86.ActiveCfg = Release|x86 + {1258544C-1FDE-4810-9A1B-189A925E9B45}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {CBCFAFF3-A3B1-4C41-B2D1-092BF7307A4E} = {95D4B35E-0A21-4D64-8BAF-27DD6C019FC5} + {1258544C-1FDE-4810-9A1B-189A925E9B45} = {C4842A1B-019E-40FF-A396-CF5AFDE8FA54} + EndGlobalSection +EndGlobal diff --git a/Common.sln b/Common.sln deleted file mode 100644 index a60f05bf..00000000 --- a/Common.sln +++ /dev/null @@ -1,105 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26814.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{FEAA3936-5906-4383-B750-F07FE1B156C5}" - ProjectSection(SolutionItems) = preProject - src\Directory.Build.props = src\Directory.Build.props - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{6878D8F1-6DCE-4677-AA1A-4D14BA6D2D60}" - ProjectSection(SolutionItems) = preProject - test\Directory.Build.props = test\Directory.Build.props - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Internal.Test", "test\Microsoft.Extensions.Internal.Test\Microsoft.Extensions.Internal.Test.csproj", "{D81EAC23-B515-49FB-B04B-285A9C1C6583}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Primitives", "src\Microsoft.Extensions.Primitives\Microsoft.Extensions.Primitives.csproj", "{711B5F84-1EDC-49A7-9643-766CE93A0466}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.Primitives.Tests", "test\Microsoft.Extensions.Primitives.Tests\Microsoft.Extensions.Primitives.Tests.csproj", "{61F72E92-B3AE-4A10-B838-44F80AED40AE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.ObjectPool", "src\Microsoft.Extensions.ObjectPool\Microsoft.Extensions.ObjectPool.csproj", "{C87DA599-4C1F-4B91-9C77-A10E79CD8701}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.ObjectPool.Test", "test\Microsoft.Extensions.ObjectPool.Test\Microsoft.Extensions.ObjectPool.Test.csproj", "{DA1D70F4-717A-4440-B388-B5BEE670C14D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.CommandLineUtils.Tests", "test\Microsoft.Extensions.CommandLineUtils.Tests\Microsoft.Extensions.CommandLineUtils.Tests.csproj", "{7E6564C3-04E3-418C-B96A-463FE2906F09}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "testassets", "testassets", "{8668B1D5-9C54-49CA-8446-18040B4C7D15}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ThrowingLibrary", "testassets\ThrowingLibrary\ThrowingLibrary.csproj", "{E1586801-D345-43C7-BC4B-9D4A83101B6C}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{3639F4F0-86E4-4EA1-9A1C-F9FE0337016B}" - ProjectSection(SolutionItems) = preProject - .appveyor.yml = .appveyor.yml - .gitattributes = .gitattributes - .gitignore = .gitignore - .travis.yml = .travis.yml - build.cmd = build.cmd - build.ps1 = build.ps1 - build.sh = build.sh - CONTRIBUTING.md = CONTRIBUTING.md - Directory.Build.props = Directory.Build.props - Directory.Build.targets = Directory.Build.targets - LICENSE.txt = LICENSE.txt - NuGet.config = NuGet.config - NuGetPackageVerifier.json = NuGetPackageVerifier.json - README.md = README.md - version.xml = version.xml - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{D2D23857-741F-4E7B-A8E1-492CC8F38FB0}" - ProjectSection(SolutionItems) = preProject - build\repo.props = build\repo.props - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D81EAC23-B515-49FB-B04B-285A9C1C6583}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D81EAC23-B515-49FB-B04B-285A9C1C6583}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D81EAC23-B515-49FB-B04B-285A9C1C6583}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D81EAC23-B515-49FB-B04B-285A9C1C6583}.Release|Any CPU.Build.0 = Release|Any CPU - {711B5F84-1EDC-49A7-9643-766CE93A0466}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {711B5F84-1EDC-49A7-9643-766CE93A0466}.Debug|Any CPU.Build.0 = Debug|Any CPU - {711B5F84-1EDC-49A7-9643-766CE93A0466}.Release|Any CPU.ActiveCfg = Release|Any CPU - {711B5F84-1EDC-49A7-9643-766CE93A0466}.Release|Any CPU.Build.0 = Release|Any CPU - {61F72E92-B3AE-4A10-B838-44F80AED40AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {61F72E92-B3AE-4A10-B838-44F80AED40AE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {61F72E92-B3AE-4A10-B838-44F80AED40AE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {61F72E92-B3AE-4A10-B838-44F80AED40AE}.Release|Any CPU.Build.0 = Release|Any CPU - {C87DA599-4C1F-4B91-9C77-A10E79CD8701}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C87DA599-4C1F-4B91-9C77-A10E79CD8701}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C87DA599-4C1F-4B91-9C77-A10E79CD8701}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C87DA599-4C1F-4B91-9C77-A10E79CD8701}.Release|Any CPU.Build.0 = Release|Any CPU - {DA1D70F4-717A-4440-B388-B5BEE670C14D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DA1D70F4-717A-4440-B388-B5BEE670C14D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DA1D70F4-717A-4440-B388-B5BEE670C14D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DA1D70F4-717A-4440-B388-B5BEE670C14D}.Release|Any CPU.Build.0 = Release|Any CPU - {7E6564C3-04E3-418C-B96A-463FE2906F09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7E6564C3-04E3-418C-B96A-463FE2906F09}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7E6564C3-04E3-418C-B96A-463FE2906F09}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7E6564C3-04E3-418C-B96A-463FE2906F09}.Release|Any CPU.Build.0 = Release|Any CPU - {E1586801-D345-43C7-BC4B-9D4A83101B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E1586801-D345-43C7-BC4B-9D4A83101B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E1586801-D345-43C7-BC4B-9D4A83101B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E1586801-D345-43C7-BC4B-9D4A83101B6C}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {D81EAC23-B515-49FB-B04B-285A9C1C6583} = {6878D8F1-6DCE-4677-AA1A-4D14BA6D2D60} - {711B5F84-1EDC-49A7-9643-766CE93A0466} = {FEAA3936-5906-4383-B750-F07FE1B156C5} - {61F72E92-B3AE-4A10-B838-44F80AED40AE} = {6878D8F1-6DCE-4677-AA1A-4D14BA6D2D60} - {C87DA599-4C1F-4B91-9C77-A10E79CD8701} = {FEAA3936-5906-4383-B750-F07FE1B156C5} - {DA1D70F4-717A-4440-B388-B5BEE670C14D} = {6878D8F1-6DCE-4677-AA1A-4D14BA6D2D60} - {7E6564C3-04E3-418C-B96A-463FE2906F09} = {6878D8F1-6DCE-4677-AA1A-4D14BA6D2D60} - {E1586801-D345-43C7-BC4B-9D4A83101B6C} = {8668B1D5-9C54-49CA-8446-18040B4C7D15} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {371030CF-B541-4BA9-9F54-3C7563415CF1} - EndGlobalSection -EndGlobal diff --git a/Directory.Build.props b/Directory.Build.props index fd608eea..6a3953d2 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,15 +1,20 @@ - - Microsoft .NET Extensions - https://github.com/aspnet/Common + CommandLineUtils + https://github.com/natemcmaster/CommandLineUtils git - $(MSBuildThisFileDirectory)build\Key.snk + + $(MSBuildThisFileDirectory)build\StrongName.snk true true - $(VersionSuffix)-$(BuildNumber) + true + + 2.0.0 + alpha + $(APPVEYOR_BUILD_NUMBER) + $(VersionSuffix)-$(BuildNumber) diff --git a/Directory.Build.targets b/Directory.Build.targets index 9989b104..8c119d54 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -1,14 +1,2 @@ - - - - <_BootstrapperFile Condition=" $([MSBuild]::IsOSUnixLike()) ">build.sh - <_BootstrapperFile Condition="! $([MSBuild]::IsOSUnixLike()) ">build.cmd - <_BootstrapperError> - Package references have not been pinned. Run './$(_BootstrapperFile) /t:Pin'. - Also, you can run './$(_BootstrapperFile) /t:Restore' which will pin *and* restore packages. '$(_BootstrapperFile)' can be found in '$(MSBuildThisFileDirectory)'. - - - - - + diff --git a/NuGet.config b/NuGet.config index 20060c93..7604d005 100644 --- a/NuGet.config +++ b/NuGet.config @@ -2,7 +2,6 @@ - diff --git a/NuGetPackageVerifier.json b/NuGetPackageVerifier.json deleted file mode 100644 index 774b3daa..00000000 --- a/NuGetPackageVerifier.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "adx-nonshipping": { - "rules": [], - "packages": { - "Microsoft.Extensions.ClosedGenericMatcher.Sources": {}, - "Microsoft.Extensions.CommandLineUtils.Sources": {}, - "Microsoft.Extensions.CopyOnWriteDictionary.Sources": {}, - "Microsoft.Extensions.HashCodeCombiner.Sources": {}, - "Microsoft.Extensions.ObjectMethodExecutor.Sources": {}, - "Microsoft.Extensions.Process.Sources": {}, - "Microsoft.Extensions.PropertyActivator.Sources": {}, - "Microsoft.Extensions.PropertyHelper.Sources": {}, - "Microsoft.Extensions.RazorViews.Sources": {}, - "Microsoft.Extensions.SecurityHelper.Sources": {}, - "Microsoft.Extensions.StackTrace.Sources": {}, - "Microsoft.Extensions.TypeNameHelper.Sources": {}, - "Microsoft.Extensions.WebEncoders.Sources": {} - } - }, - "Default": { - "rules": [ - "DefaultCompositeRule" - ] - } -} diff --git a/README.md b/README.md index eda3cbf0..ab076984 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ Common -=== -AppVeyor: [![AppVeyor](https://ci.appveyor.com/api/projects/status/snawy2a2vt0vd7dv/branch/dev?svg=true)](https://ci.appveyor.com/project/aspnetci/Common/branch/dev) +====== -Travis: [![Travis](https://travis-ci.org/aspnet/Common.svg?branch=dev)](https://travis-ci.org/aspnet/Common) +AppVeyor: [![AppVeyor](https://ci.appveyor.com/api/projects/status/snawy2a2vt0vd7dv/branch/dev?svg=true)](https://ci.appveyor.com/project/aspnetci/Common/branch/dev) The Common repository includes projects containing commonly used primitives and utility types. diff --git a/build.ps1 b/build.ps1 index d5eb4d5c..333a0c35 100644 --- a/build.ps1 +++ b/build.ps1 @@ -1,177 +1,23 @@ -#!/usr/bin/env powershell -#requires -version 4 - -<# -.SYNOPSIS -Build this repository - -.DESCRIPTION -Downloads korebuild if required. Then builds the repository. - -.PARAMETER Path -The folder to build. Defaults to the folder containing this script. - -.PARAMETER Channel -The channel of KoreBuild to download. Overrides the value from the config file. - -.PARAMETER DotNetHome -The directory where .NET Core tools will be stored. - -.PARAMETER ToolsSource -The base url where build tools can be downloaded. Overrides the value from the config file. - -.PARAMETER Update -Updates KoreBuild to the latest version even if a lock file is present. - -.PARAMETER ConfigFile -The path to the configuration file that stores values. Defaults to version.xml. - -.PARAMETER MSBuildArgs -Arguments to be passed to MSBuild - -.NOTES -This function will create a file $PSScriptRoot/korebuild-lock.txt. This lock file can be committed to source, but does not have to be. -When the lockfile is not present, KoreBuild will create one using latest available version from $Channel. - -The $ConfigFile is expected to be an XML file. It is optional, and the configuration values in it are optional as well. - -.EXAMPLE -Example config file: -```xml - - - - dev - https://aspnetcore.blob.core.windows.net/buildtools - - -``` -#> -[CmdletBinding(PositionalBinding = $false)] param( - [string]$Path = $PSScriptRoot, - [Alias('c')] - [string]$Channel, - [Alias('d')] - [string]$DotNetHome, - [Alias('s')] - [string]$ToolsSource, - [Alias('u')] - [switch]$Update, - [string]$ConfigFile = (Join-Path $PSScriptRoot 'version.xml'), - [Parameter(ValueFromRemainingArguments = $true)] - [string[]]$MSBuildArgs + [ValidateSet('Debug', 'Release')] + $Configuration = 'Debug' ) -Set-StrictMode -Version 2 +Set-StrictMode -Version 1 $ErrorActionPreference = 'Stop' -# -# Functions -# - -function Get-KoreBuild { - - $lockFile = Join-Path $Path 'korebuild-lock.txt' - - if (!(Test-Path $lockFile) -or $Update) { - Get-RemoteFile "$ToolsSource/korebuild/channels/$Channel/latest.txt" $lockFile - } - - $version = Get-Content $lockFile | Where-Object { $_ -like 'version:*' } | Select-Object -first 1 - if (!$version) { - Write-Error "Failed to parse version from $lockFile. Expected a line that begins with 'version:'" - } - $version = $version.TrimStart('version:').Trim() - $korebuildPath = Join-Paths $DotNetHome ('buildtools', 'korebuild', $version) - - if (!(Test-Path $korebuildPath)) { - Write-Host -ForegroundColor Magenta "Downloading KoreBuild $version" - New-Item -ItemType Directory -Path $korebuildPath | Out-Null - $remotePath = "$ToolsSource/korebuild/artifacts/$version/korebuild.$version.zip" - - try { - $tmpfile = Join-Path ([IO.Path]::GetTempPath()) "KoreBuild-$([guid]::NewGuid()).zip" - Get-RemoteFile $remotePath $tmpfile - if (Get-Command -Name 'Expand-Archive' -ErrorAction Ignore) { - # Use built-in commands where possible as they are cross-plat compatible - Expand-Archive -Path $tmpfile -DestinationPath $korebuildPath - } - else { - # Fallback to old approach for old installations of PowerShell - Add-Type -AssemblyName System.IO.Compression.FileSystem - [System.IO.Compression.ZipFile]::ExtractToDirectory($tmpfile, $korebuildPath) - } - } - catch { - Remove-Item -Recurse -Force $korebuildPath -ErrorAction Ignore - throw - } - finally { - Remove-Item $tmpfile -ErrorAction Ignore - } - } - - return $korebuildPath -} - -function Join-Paths([string]$path, [string[]]$childPaths) { - $childPaths | ForEach-Object { $path = Join-Path $path $_ } - return $path -} - -function Get-RemoteFile([string]$RemotePath, [string]$LocalPath) { - if ($RemotePath -notlike 'http*') { - Copy-Item $RemotePath $LocalPath - return +function exec([string]$_cmd) { + Write-Host -ForegroundColor DarkGray ">>> $_cmd $args" + & $_cmd @args + if ($LASTEXITCODE -ne 0) { + Write-Error "Command exited with code $LASTEXITCODE" } - - $retries = 10 - while ($retries -gt 0) { - $retries -= 1 - try { - Invoke-WebRequest -UseBasicParsing -Uri $RemotePath -OutFile $LocalPath - return - } - catch { - Write-Verbose "Request failed. $retries retries remaining" - } - } - - Write-Error "Download failed: '$RemotePath'." } -# -# Main -# +$artifacts = "$PSScriptRoot/artifacts/" -# Load configuration or set defaults +Remove-Item -Recurse $artifacts -ErrorAction Ignore -if (Test-Path $ConfigFile) { - [xml] $config = Get-Content $ConfigFile - if (!($Channel)) { [string] $Channel = Select-Xml -Xml $config -XPath '/Project/PropertyGroup/KoreBuildChannel' } - if (!($ToolsSource)) { [string] $ToolsSource = Select-Xml -Xml $config -XPath '/Project/PropertyGroup/KoreBuildToolsSource' } -} - -if (!$DotNetHome) { - $DotNetHome = if ($env:DOTNET_HOME) { $env:DOTNET_HOME } ` - elseif ($env:USERPROFILE) { Join-Path $env:USERPROFILE '.dotnet'} ` - elseif ($env:HOME) {Join-Path $env:HOME '.dotnet'}` - else { Join-Path $PSScriptRoot '.dotnet'} -} - -if (!$Channel) { $Channel = 'dev' } -if (!$ToolsSource) { $ToolsSource = 'https://aspnetcore.blob.core.windows.net/buildtools' } - -# Execute - -$korebuildPath = Get-KoreBuild -Import-Module -Force -Scope Local (Join-Path $korebuildPath 'KoreBuild.psd1') - -try { - Install-Tools $ToolsSource $DotNetHome - Invoke-RepositoryBuild $Path @MSBuildArgs -} -finally { - Remove-Module 'KoreBuild' -ErrorAction Ignore -} +exec dotnet restore /p:BuildNumber=t000 +exec dotnet pack -c $Configuration -o $artifacts +exec dotnet test -c $Configuration --no-build "$PSScriptRoot/test/CommandLineUtils.Tests/McMaster.Extensions.CommandLineUtils.Tests.csproj" diff --git a/build.sh b/build.sh deleted file mode 100755 index 11cdbe55..00000000 --- a/build.sh +++ /dev/null @@ -1,199 +0,0 @@ -#!/usr/bin/env bash - -set -euo pipefail - -# -# variables -# - -RESET="\033[0m" -RED="\033[0;31m" -MAGENTA="\033[0;95m" -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet" -config_file="$DIR/version.xml" -verbose=false -update=false -repo_path="$DIR" -channel='' -tools_source='' - -# -# Functions -# -__usage() { - echo "Usage: $(basename "${BASH_SOURCE[0]}") [options] [[--] ...]" - echo "" - echo "Arguments:" - echo " ... Arguments passed to MSBuild. Variable number of arguments allowed." - echo "" - echo "Options:" - echo " --verbose Show verbose output." - echo " -c|--channel The channel of KoreBuild to download. Overrides the value from the config file.." - echo " --config-file TThe path to the configuration file that stores values. Defaults to version.xml." - echo " -d|--dotnet-home The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet." - echo " --path The directory to build. Defaults to the directory containing the script." - echo " -s|--tools-source The base url where build tools can be downloaded. Overrides the value from the config file." - echo " -u|--update Update to the latest KoreBuild even if the lock file is present." - echo "" - echo "Description:" - echo " This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be." - echo " When the lockfile is not present, KoreBuild will create one using latest available version from \$channel." - - if [[ "${1:-}" != '--no-exit' ]]; then - exit 2 - fi -} - -get_korebuild() { - local version - local lock_file="$repo_path/korebuild-lock.txt" - if [ ! -f "$lock_file" ] || [ "$update" = true ]; then - __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" - fi - version="$(grep 'version:*' -m 1 "$lock_file")" - if [[ "$version" == '' ]]; then - __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'" - return 1 - fi - version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" - local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version" - - { - if [ ! -d "$korebuild_path" ]; then - mkdir -p "$korebuild_path" - local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip" - tmpfile="$(mktemp)" - echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}" - if __get_remote_file "$remote_path" "$tmpfile"; then - unzip -q -d "$korebuild_path" "$tmpfile" - fi - rm "$tmpfile" || true - fi - - source "$korebuild_path/KoreBuild.sh" - } || { - if [ -d "$korebuild_path" ]; then - echo "Cleaning up after failed installation" - rm -rf "$korebuild_path" || true - fi - return 1 - } -} - -__error() { - echo -e "${RED}$*${RESET}" 1>&2 -} - -__machine_has() { - hash "$1" > /dev/null 2>&1 - return $? -} - -__get_remote_file() { - local remote_path=$1 - local local_path=$2 - - if [[ "$remote_path" != 'http'* ]]; then - cp "$remote_path" "$local_path" - return 0 - fi - - local failed=false - if __machine_has wget; then - wget --tries 10 --quiet -O "$local_path" "$remote_path" || failed=true - else - failed=true - fi - - if [ "$failed" = true ] && __machine_has curl; then - failed=false - curl --retry 10 -sSL -f --create-dirs -o "$local_path" "$remote_path" || failed=true - fi - - if [ "$failed" = true ]; then - __error "Download failed: $remote_path" 1>&2 - return 1 - fi -} - -__read_dom () { local IFS=\> ; read -r -d \< ENTITY CONTENT ;} - -# -# main -# - -while [[ $# -gt 0 ]]; do - case $1 in - -\?|-h|--help) - __usage --no-exit - exit 0 - ;; - -c|--channel|-Channel) - shift - channel="${1:-}" - [ -z "$channel" ] && __usage - ;; - --config-file|-ConfigFile) - shift - config_file="${1:-}" - [ -z "$config_file" ] && __usage - ;; - -d|--dotnet-home|-DotNetHome) - shift - DOTNET_HOME="${1:-}" - [ -z "$DOTNET_HOME" ] && __usage - ;; - --path|-Path) - shift - repo_path="${1:-}" - [ -z "$repo_path" ] && __usage - ;; - -s|--tools-source|-ToolsSource) - shift - tools_source="${1:-}" - [ -z "$tools_source" ] && __usage - ;; - -u|--update|-Update) - update=true - ;; - --verbose|-Verbose) - verbose=true - ;; - --) - shift - break - ;; - *) - break - ;; - esac - shift -done - -if ! __machine_has unzip; then - __error 'Missing required command: unzip' - exit 1 -fi - -if ! __machine_has curl && ! __machine_has wget; then - __error 'Missing required command. Either wget or curl is required.' - exit 1 -fi - -if [ -f "$config_file" ]; then - comment=false - while __read_dom; do - if [ "$comment" = true ]; then [[ $CONTENT == *'-->'* ]] && comment=false ; continue; fi - if [[ $ENTITY == '!--'* ]]; then comment=true; continue; fi - if [ -z "$channel" ] && [[ $ENTITY == "KoreBuildChannel" ]]; then channel=$CONTENT; fi - if [ -z "$tools_source" ] && [[ $ENTITY == "KoreBuildToolsSource" ]]; then tools_source=$CONTENT; fi - done < "$config_file" -fi - -[ -z "$channel" ] && channel='dev' -[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools' - -get_korebuild -install_tools "$tools_source" "$DOTNET_HOME" -invoke_repository_build "$repo_path" "$@" diff --git a/build/Key.snk b/build/Key.snk deleted file mode 100644 index e10e4889..00000000 Binary files a/build/Key.snk and /dev/null differ diff --git a/build/StrongName.snk b/build/StrongName.snk new file mode 100644 index 00000000..315f8a5f Binary files /dev/null and b/build/StrongName.snk differ diff --git a/build/repo.props b/build/repo.props deleted file mode 100644 index c5d91e8a..00000000 --- a/build/repo.props +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/shared/Microsoft.Extensions.ClosedGenericMatcher.Sources/ClosedGenericMatcher.cs b/shared/Microsoft.Extensions.ClosedGenericMatcher.Sources/ClosedGenericMatcher.cs deleted file mode 100644 index f234c2ed..00000000 --- a/shared/Microsoft.Extensions.ClosedGenericMatcher.Sources/ClosedGenericMatcher.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Reflection; - -namespace Microsoft.Extensions.Internal -{ - /// - /// Helper related to generic interface definitions and implementing classes. - /// - internal static class ClosedGenericMatcher - { - /// - /// Determine whether is or implements a closed generic - /// created from . - /// - /// The of interest. - /// The open generic to match. Usually an interface. - /// - /// The closed generic created from that - /// is or implements. null if the two s have no such - /// relationship. - /// - /// - /// This method will return if is - /// typeof(KeyValuePair{,}), and is - /// typeof(KeyValuePair{string, object}). - /// - public static Type ExtractGenericInterface(Type queryType, Type interfaceType) - { - if (queryType == null) - { - throw new ArgumentNullException(nameof(queryType)); - } - - if (interfaceType == null) - { - throw new ArgumentNullException(nameof(interfaceType)); - } - - if (IsGenericInstantiation(queryType, interfaceType)) - { - // queryType matches (i.e. is a closed generic type created from) the open generic type. - return queryType; - } - - // Otherwise check all interfaces the type implements for a match. - // - If multiple different generic instantiations exists, we want the most derived one. - // - If that doesn't break the tie, then we sort alphabetically so that it's deterministic. - // - // We do this by looking at interfaces on the type, and recursing to the base type - // if we don't find any matches. - return GetGenericInstantiation(queryType, interfaceType); - } - - private static bool IsGenericInstantiation(Type candidate, Type interfaceType) - { - return - candidate.GetTypeInfo().IsGenericType && - candidate.GetGenericTypeDefinition() == interfaceType; - } - - private static Type GetGenericInstantiation(Type queryType, Type interfaceType) - { - Type bestMatch = null; - var interfaces = queryType.GetInterfaces(); - foreach (var @interface in interfaces) - { - if (IsGenericInstantiation(@interface, interfaceType)) - { - if (bestMatch == null) - { - bestMatch = @interface; - } - else if (StringComparer.Ordinal.Compare(@interface.FullName, bestMatch.FullName) < 0) - { - bestMatch = @interface; - } - else - { - // There are two matches at this level of the class hierarchy, but @interface is after - // bestMatch in the sort order. - } - } - } - - if (bestMatch != null) - { - return bestMatch; - } - - // BaseType will be null for object and interfaces, which means we've reached 'bottom'. - var baseType = queryType?.GetTypeInfo().BaseType; - if (baseType == null) - { - return null; - } - else - { - return GetGenericInstantiation(baseType, interfaceType); - } - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.CopyOnWriteDictionary.Sources/CopyOnWriteDictionary.cs b/shared/Microsoft.Extensions.CopyOnWriteDictionary.Sources/CopyOnWriteDictionary.cs deleted file mode 100644 index 1408059a..00000000 --- a/shared/Microsoft.Extensions.CopyOnWriteDictionary.Sources/CopyOnWriteDictionary.cs +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Microsoft.Extensions.Internal -{ - internal class CopyOnWriteDictionary : IDictionary - { - private readonly IDictionary _sourceDictionary; - private readonly IEqualityComparer _comparer; - private IDictionary _innerDictionary; - - public CopyOnWriteDictionary( - IDictionary sourceDictionary, - IEqualityComparer comparer) - { - if (sourceDictionary == null) - { - throw new ArgumentNullException(nameof(sourceDictionary)); - } - - if (comparer == null) - { - throw new ArgumentNullException(nameof(comparer)); - } - - _sourceDictionary = sourceDictionary; - _comparer = comparer; - } - - private IDictionary ReadDictionary - { - get - { - return _innerDictionary ?? _sourceDictionary; - } - } - - private IDictionary WriteDictionary - { - get - { - if (_innerDictionary == null) - { - _innerDictionary = new Dictionary(_sourceDictionary, - _comparer); - } - - return _innerDictionary; - } - } - - public virtual ICollection Keys - { - get - { - return ReadDictionary.Keys; - } - } - - public virtual ICollection Values - { - get - { - return ReadDictionary.Values; - } - } - - public virtual int Count - { - get - { - return ReadDictionary.Count; - } - } - - public virtual bool IsReadOnly - { - get - { - return false; - } - } - - public virtual TValue this[TKey key] - { - get - { - return ReadDictionary[key]; - } - set - { - WriteDictionary[key] = value; - } - } - - public virtual bool ContainsKey(TKey key) - { - return ReadDictionary.ContainsKey(key); - } - - public virtual void Add(TKey key, TValue value) - { - WriteDictionary.Add(key, value); - } - - public virtual bool Remove(TKey key) - { - return WriteDictionary.Remove(key); - } - - public virtual bool TryGetValue(TKey key, out TValue value) - { - return ReadDictionary.TryGetValue(key, out value); - } - - public virtual void Add(KeyValuePair item) - { - WriteDictionary.Add(item); - } - - public virtual void Clear() - { - WriteDictionary.Clear(); - } - - public virtual bool Contains(KeyValuePair item) - { - return ReadDictionary.Contains(item); - } - - public virtual void CopyTo(KeyValuePair[] array, int arrayIndex) - { - ReadDictionary.CopyTo(array, arrayIndex); - } - - public bool Remove(KeyValuePair item) - { - return WriteDictionary.Remove(item); - } - - public virtual IEnumerator> GetEnumerator() - { - return ReadDictionary.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.CopyOnWriteDictionary.Sources/CopyOnWriteDictionaryHolder.cs b/shared/Microsoft.Extensions.CopyOnWriteDictionary.Sources/CopyOnWriteDictionaryHolder.cs deleted file mode 100644 index 7cd935e9..00000000 --- a/shared/Microsoft.Extensions.CopyOnWriteDictionary.Sources/CopyOnWriteDictionaryHolder.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace Microsoft.Extensions.Internal -{ - internal struct CopyOnWriteDictionaryHolder - { - private readonly Dictionary _source; - private Dictionary _copy; - - public CopyOnWriteDictionaryHolder(Dictionary source) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - _source = source; - _copy = null; - } - - public CopyOnWriteDictionaryHolder(CopyOnWriteDictionaryHolder source) - { - _source = source._copy ?? source._source; - _copy = null; - } - - public bool HasBeenCopied => _copy != null; - - public Dictionary ReadDictionary - { - get - { - if (_copy != null) - { - return _copy; - } - else if (_source != null) - { - return _source; - } - else - { - // Default-Constructor case - _copy = new Dictionary(); - return _copy; - } - } - } - - public Dictionary WriteDictionary - { - get - { - if (_copy == null && _source == null) - { - // Default-Constructor case - _copy = new Dictionary(); - } - else if (_copy == null) - { - _copy = new Dictionary(_source, _source.Comparer); - } - - return _copy; - } - } - - public Dictionary.KeyCollection Keys - { - get - { - return ReadDictionary.Keys; - } - } - - public Dictionary.ValueCollection Values - { - get - { - return ReadDictionary.Values; - } - } - - public int Count - { - get - { - return ReadDictionary.Count; - } - } - - public bool IsReadOnly - { - get - { - return false; - } - } - - public TValue this[TKey key] - { - get - { - return ReadDictionary[key]; - } - set - { - WriteDictionary[key] = value; - } - } - - public bool ContainsKey(TKey key) - { - return ReadDictionary.ContainsKey(key); - } - - public void Add(TKey key, TValue value) - { - WriteDictionary.Add(key, value); - } - - public bool Remove(TKey key) - { - return WriteDictionary.Remove(key); - } - - public bool TryGetValue(TKey key, out TValue value) - { - return ReadDictionary.TryGetValue(key, out value); - } - - public void Add(KeyValuePair item) - { - ((ICollection>)WriteDictionary).Add(item); - } - - public void Clear() - { - WriteDictionary.Clear(); - } - - public bool Contains(KeyValuePair item) - { - return ((ICollection>)ReadDictionary).Contains(item); - } - - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - ((ICollection>)ReadDictionary).CopyTo(array, arrayIndex); - } - - public bool Remove(KeyValuePair item) - { - return ((ICollection>)WriteDictionary).Remove(item); - } - - public Dictionary.Enumerator GetEnumerator() - { - return ReadDictionary.GetEnumerator(); - } - } -} diff --git a/shared/Microsoft.Extensions.HashCodeCombiner.Sources/HashCodeCombiner.cs b/shared/Microsoft.Extensions.HashCodeCombiner.Sources/HashCodeCombiner.cs deleted file mode 100644 index 4df8b46b..00000000 --- a/shared/Microsoft.Extensions.HashCodeCombiner.Sources/HashCodeCombiner.cs +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections; -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace Microsoft.Extensions.Internal -{ - internal struct HashCodeCombiner - { - private long _combinedHash64; - - public int CombinedHash - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get { return _combinedHash64.GetHashCode(); } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private HashCodeCombiner(long seed) - { - _combinedHash64 = seed; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(IEnumerable e) - { - if (e == null) - { - Add(0); - } - else - { - var count = 0; - foreach (object o in e) - { - Add(o); - count++; - } - Add(count); - } - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static implicit operator int(HashCodeCombiner self) - { - return self.CombinedHash; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(int i) - { - _combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(string s) - { - var hashCode = (s != null) ? s.GetHashCode() : 0; - Add(hashCode); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(object o) - { - var hashCode = (o != null) ? o.GetHashCode() : 0; - Add(hashCode); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public void Add(TValue value, IEqualityComparer comparer) - { - var hashCode = value != null ? comparer.GetHashCode(value) : 0; - Add(hashCode); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static HashCodeCombiner Start() - { - return new HashCodeCombiner(0x1505L); - } - } -} diff --git a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/AwaitableInfo.cs b/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/AwaitableInfo.cs deleted file mode 100644 index 431b83a6..00000000 --- a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/AwaitableInfo.cs +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Microsoft.Extensions.Internal -{ - internal struct AwaitableInfo - { - public Type AwaiterType { get; } - public PropertyInfo AwaiterIsCompletedProperty { get; } - public MethodInfo AwaiterGetResultMethod { get; } - public MethodInfo AwaiterOnCompletedMethod { get; } - public MethodInfo AwaiterUnsafeOnCompletedMethod { get; } - public Type ResultType { get; } - public MethodInfo GetAwaiterMethod { get; } - - public AwaitableInfo( - Type awaiterType, - PropertyInfo awaiterIsCompletedProperty, - MethodInfo awaiterGetResultMethod, - MethodInfo awaiterOnCompletedMethod, - MethodInfo awaiterUnsafeOnCompletedMethod, - Type resultType, - MethodInfo getAwaiterMethod) - { - AwaiterType = awaiterType; - AwaiterIsCompletedProperty = awaiterIsCompletedProperty; - AwaiterGetResultMethod = awaiterGetResultMethod; - AwaiterOnCompletedMethod = awaiterOnCompletedMethod; - AwaiterUnsafeOnCompletedMethod = awaiterUnsafeOnCompletedMethod; - ResultType = resultType; - GetAwaiterMethod = getAwaiterMethod; - } - - public static bool IsTypeAwaitable(Type type, out AwaitableInfo awaitableInfo) - { - // Based on Roslyn code: http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Shared/Extensions/ISymbolExtensions.cs,db4d48ba694b9347 - - // Awaitable must have method matching "object GetAwaiter()" - var getAwaiterMethod = type.GetRuntimeMethods().FirstOrDefault(m => - m.Name.Equals("GetAwaiter", StringComparison.OrdinalIgnoreCase) - && m.GetParameters().Length == 0 - && m.ReturnType != null); - if (getAwaiterMethod == null) - { - awaitableInfo = default(AwaitableInfo); - return false; - } - - var awaiterType = getAwaiterMethod.ReturnType; - - // Awaiter must have property matching "bool IsCompleted { get; }" - var isCompletedProperty = awaiterType.GetRuntimeProperties().FirstOrDefault(p => - p.Name.Equals("IsCompleted", StringComparison.OrdinalIgnoreCase) - && p.PropertyType == typeof(bool) - && p.GetMethod != null); - if (isCompletedProperty == null) - { - awaitableInfo = default(AwaitableInfo); - return false; - } - - // Awaiter must implement INotifyCompletion - var awaiterInterfaces = awaiterType.GetInterfaces(); - var implementsINotifyCompletion = awaiterInterfaces.Any(t => t == typeof(INotifyCompletion)); - if (!implementsINotifyCompletion) - { - awaitableInfo = default(AwaitableInfo); - return false; - } - - // INotifyCompletion supplies a method matching "void OnCompleted(Action action)" - var iNotifyCompletionMap = awaiterType - .GetTypeInfo() - .GetRuntimeInterfaceMap(typeof(INotifyCompletion)); - var onCompletedMethod = iNotifyCompletionMap.InterfaceMethods.Single(m => - m.Name.Equals("OnCompleted", StringComparison.OrdinalIgnoreCase) - && m.ReturnType == typeof(void) - && m.GetParameters().Length == 1 - && m.GetParameters()[0].ParameterType == typeof(Action)); - - // Awaiter optionally implements ICriticalNotifyCompletion - var implementsICriticalNotifyCompletion = awaiterInterfaces.Any(t => t == typeof(ICriticalNotifyCompletion)); - MethodInfo unsafeOnCompletedMethod; - if (implementsICriticalNotifyCompletion) - { - // ICriticalNotifyCompletion supplies a method matching "void UnsafeOnCompleted(Action action)" - var iCriticalNotifyCompletionMap = awaiterType - .GetTypeInfo() - .GetRuntimeInterfaceMap(typeof(ICriticalNotifyCompletion)); - unsafeOnCompletedMethod = iCriticalNotifyCompletionMap.InterfaceMethods.Single(m => - m.Name.Equals("UnsafeOnCompleted", StringComparison.OrdinalIgnoreCase) - && m.ReturnType == typeof(void) - && m.GetParameters().Length == 1 - && m.GetParameters()[0].ParameterType == typeof(Action)); - } - else - { - unsafeOnCompletedMethod = null; - } - - // Awaiter must have method matching "void GetResult" or "T GetResult()" - var getResultMethod = awaiterType.GetRuntimeMethods().FirstOrDefault(m => - m.Name.Equals("GetResult") - && m.GetParameters().Length == 0); - if (getResultMethod == null) - { - awaitableInfo = default(AwaitableInfo); - return false; - } - - awaitableInfo = new AwaitableInfo( - awaiterType, - isCompletedProperty, - getResultMethod, - onCompletedMethod, - unsafeOnCompletedMethod, - getResultMethod.ReturnType, - getAwaiterMethod); - return true; - } - } -} diff --git a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/CoercedAwaitableInfo.cs b/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/CoercedAwaitableInfo.cs deleted file mode 100644 index 4e48ef09..00000000 --- a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/CoercedAwaitableInfo.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq.Expressions; - -namespace Microsoft.Extensions.Internal -{ - internal struct CoercedAwaitableInfo - { - public AwaitableInfo AwaitableInfo { get; } - public Expression CoercerExpression { get; } - public Type CoercerResultType { get; } - public bool RequiresCoercion => CoercerExpression != null; - - public CoercedAwaitableInfo(AwaitableInfo awaitableInfo) - { - AwaitableInfo = awaitableInfo; - CoercerExpression = null; - CoercerResultType = null; - } - - public CoercedAwaitableInfo(Expression coercerExpression, Type coercerResultType, AwaitableInfo coercedAwaitableInfo) - { - CoercerExpression = coercerExpression; - CoercerResultType = coercerResultType; - AwaitableInfo = coercedAwaitableInfo; - } - - public static bool IsTypeAwaitable(Type type, out CoercedAwaitableInfo info) - { - if (AwaitableInfo.IsTypeAwaitable(type, out var directlyAwaitableInfo)) - { - info = new CoercedAwaitableInfo(directlyAwaitableInfo); - return true; - } - - // It's not directly awaitable, but maybe we can coerce it. - // Currently we support coercing FSharpAsync. - if (ObjectMethodExecutorFSharpSupport.TryBuildCoercerFromFSharpAsyncToAwaitable(type, - out var coercerExpression, - out var coercerResultType)) - { - if (AwaitableInfo.IsTypeAwaitable(coercerResultType, out var coercedAwaitableInfo)) - { - info = new CoercedAwaitableInfo(coercerExpression, coercerResultType, coercedAwaitableInfo); - return true; - } - } - - info = default(CoercedAwaitableInfo); - return false; - } - } -} diff --git a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutor.cs b/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutor.cs deleted file mode 100644 index f8e5b70f..00000000 --- a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutor.cs +++ /dev/null @@ -1,340 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq.Expressions; -using System.Reflection; - -namespace Microsoft.Extensions.Internal -{ - internal class ObjectMethodExecutor - { - private readonly object[] _parameterDefaultValues; - private readonly MethodExecutorAsync _executorAsync; - private readonly MethodExecutor _executor; - - private static readonly ConstructorInfo _objectMethodExecutorAwaitableConstructor = - typeof(ObjectMethodExecutorAwaitable).GetConstructor(new[] { - typeof(object), // customAwaitable - typeof(Func), // getAwaiterMethod - typeof(Func), // isCompletedMethod - typeof(Func), // getResultMethod - typeof(Action), // onCompletedMethod - typeof(Action) // unsafeOnCompletedMethod - }); - - private ObjectMethodExecutor(MethodInfo methodInfo, TypeInfo targetTypeInfo, object[] parameterDefaultValues) - { - if (methodInfo == null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } - - MethodInfo = methodInfo; - MethodParameters = methodInfo.GetParameters(); - TargetTypeInfo = targetTypeInfo; - MethodReturnType = methodInfo.ReturnType; - - var isAwaitable = CoercedAwaitableInfo.IsTypeAwaitable(MethodReturnType, out var coercedAwaitableInfo); - - IsMethodAsync = isAwaitable; - AsyncResultType = isAwaitable ? coercedAwaitableInfo.AwaitableInfo.ResultType : null; - - // Upstream code may prefer to use the sync-executor even for async methods, because if it knows - // that the result is a specific Task where T is known, then it can directly cast to that type - // and await it without the extra heap allocations involved in the _executorAsync code path. - _executor = GetExecutor(methodInfo, targetTypeInfo); - - if (IsMethodAsync) - { - _executorAsync = GetExecutorAsync(methodInfo, targetTypeInfo, coercedAwaitableInfo); - } - - _parameterDefaultValues = parameterDefaultValues; - } - - private delegate ObjectMethodExecutorAwaitable MethodExecutorAsync(object target, object[] parameters); - - private delegate object MethodExecutor(object target, object[] parameters); - - private delegate void VoidMethodExecutor(object target, object[] parameters); - - public MethodInfo MethodInfo { get; } - - public ParameterInfo[] MethodParameters { get; } - - public TypeInfo TargetTypeInfo { get; } - - public Type AsyncResultType { get; } - - // This field is made internal set because it is set in unit tests. - public Type MethodReturnType { get; internal set; } - - public bool IsMethodAsync { get; } - - public static ObjectMethodExecutor Create(MethodInfo methodInfo, TypeInfo targetTypeInfo) - { - return new ObjectMethodExecutor(methodInfo, targetTypeInfo, null); - } - - public static ObjectMethodExecutor Create(MethodInfo methodInfo, TypeInfo targetTypeInfo, object[] parameterDefaultValues) - { - if (parameterDefaultValues == null) - { - throw new ArgumentNullException(nameof(parameterDefaultValues)); - } - - return new ObjectMethodExecutor(methodInfo, targetTypeInfo, parameterDefaultValues); - } - - /// - /// Executes the configured method on . This can be used whether or not - /// the configured method is asynchronous. - /// - /// - /// Even if the target method is asynchronous, it's desirable to invoke it using Execute rather than - /// ExecuteAsync if you know at compile time what the return type is, because then you can directly - /// "await" that value (via a cast), and then the generated code will be able to reference the - /// resulting awaitable as a value-typed variable. If you use ExecuteAsync instead, the generated - /// code will have to treat the resulting awaitable as a boxed object, because it doesn't know at - /// compile time what type it would be. - /// - /// The object whose method is to be executed. - /// Parameters to pass to the method. - /// The method return value. - public object Execute(object target, object[] parameters) - { - return _executor(target, parameters); - } - - /// - /// Executes the configured method on . This can only be used if the configured - /// method is asynchronous. - /// - /// - /// If you don't know at compile time the type of the method's returned awaitable, you can use ExecuteAsync, - /// which supplies an awaitable-of-object. This always works, but can incur several extra heap allocations - /// as compared with using Execute and then using "await" on the result value typecasted to the known - /// awaitable type. The possible extra heap allocations are for: - /// - /// 1. The custom awaitable (though usually there's a heap allocation for this anyway, since normally - /// it's a reference type, and you normally create a new instance per call). - /// 2. The custom awaiter (whether or not it's a value type, since if it's not, you need a new instance - /// of it, and if it is, it will have to be boxed so the calling code can reference it as an object). - /// 3. The async result value, if it's a value type (it has to be boxed as an object, since the calling - /// code doesn't know what type it's going to be). - /// - /// The object whose method is to be executed. - /// Parameters to pass to the method. - /// An object that you can "await" to get the method return value. - public ObjectMethodExecutorAwaitable ExecuteAsync(object target, object[] parameters) - { - return _executorAsync(target, parameters); - } - - public object GetDefaultValueForParameter(int index) - { - if (_parameterDefaultValues == null) - { - throw new InvalidOperationException($"Cannot call {nameof(GetDefaultValueForParameter)}, because no parameter default values were supplied."); - } - - if (index < 0 || index > MethodParameters.Length - 1) - { - throw new ArgumentOutOfRangeException(nameof(index)); - } - - return _parameterDefaultValues[index]; - } - - private static MethodExecutor GetExecutor(MethodInfo methodInfo, TypeInfo targetTypeInfo) - { - // Parameters to executor - var targetParameter = Expression.Parameter(typeof(object), "target"); - var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); - - // Build parameter list - var parameters = new List(); - var paramInfos = methodInfo.GetParameters(); - for (int i = 0; i < paramInfos.Length; i++) - { - var paramInfo = paramInfos[i]; - var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); - var valueCast = Expression.Convert(valueObj, paramInfo.ParameterType); - - // valueCast is "(Ti) parameters[i]" - parameters.Add(valueCast); - } - - // Call method - var instanceCast = Expression.Convert(targetParameter, targetTypeInfo.AsType()); - var methodCall = Expression.Call(instanceCast, methodInfo, parameters); - - // methodCall is "((Ttarget) target) method((T0) parameters[0], (T1) parameters[1], ...)" - // Create function - if (methodCall.Type == typeof(void)) - { - var lambda = Expression.Lambda(methodCall, targetParameter, parametersParameter); - var voidExecutor = lambda.Compile(); - return WrapVoidMethod(voidExecutor); - } - else - { - // must coerce methodCall to match ActionExecutor signature - var castMethodCall = Expression.Convert(methodCall, typeof(object)); - var lambda = Expression.Lambda(castMethodCall, targetParameter, parametersParameter); - return lambda.Compile(); - } - } - - private static MethodExecutor WrapVoidMethod(VoidMethodExecutor executor) - { - return delegate (object target, object[] parameters) - { - executor(target, parameters); - return null; - }; - } - - private static MethodExecutorAsync GetExecutorAsync( - MethodInfo methodInfo, - TypeInfo targetTypeInfo, - CoercedAwaitableInfo coercedAwaitableInfo) - { - // Parameters to executor - var targetParameter = Expression.Parameter(typeof(object), "target"); - var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); - - // Build parameter list - var parameters = new List(); - var paramInfos = methodInfo.GetParameters(); - for (int i = 0; i < paramInfos.Length; i++) - { - var paramInfo = paramInfos[i]; - var valueObj = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); - var valueCast = Expression.Convert(valueObj, paramInfo.ParameterType); - - // valueCast is "(Ti) parameters[i]" - parameters.Add(valueCast); - } - - // Call method - var instanceCast = Expression.Convert(targetParameter, targetTypeInfo.AsType()); - var methodCall = Expression.Call(instanceCast, methodInfo, parameters); - - // Using the method return value, construct an ObjectMethodExecutorAwaitable based on - // the info we have about its implementation of the awaitable pattern. Note that all - // the funcs/actions we construct here are precompiled, so that only one instance of - // each is preserved throughout the lifetime of the ObjectMethodExecutor. - - // var getAwaiterFunc = (object awaitable) => - // (object)((CustomAwaitableType)awaitable).GetAwaiter(); - var customAwaitableParam = Expression.Parameter(typeof(object), "awaitable"); - var awaitableInfo = coercedAwaitableInfo.AwaitableInfo; - var postCoercionMethodReturnType = coercedAwaitableInfo.CoercerResultType ?? methodInfo.ReturnType; - var getAwaiterFunc = Expression.Lambda>( - Expression.Convert( - Expression.Call( - Expression.Convert(customAwaitableParam, postCoercionMethodReturnType), - awaitableInfo.GetAwaiterMethod), - typeof(object)), - customAwaitableParam).Compile(); - - // var isCompletedFunc = (object awaiter) => - // ((CustomAwaiterType)awaiter).IsCompleted; - var isCompletedParam = Expression.Parameter(typeof(object), "awaiter"); - var isCompletedFunc = Expression.Lambda>( - Expression.MakeMemberAccess( - Expression.Convert(isCompletedParam, awaitableInfo.AwaiterType), - awaitableInfo.AwaiterIsCompletedProperty), - isCompletedParam).Compile(); - - var getResultParam = Expression.Parameter(typeof(object), "awaiter"); - Func getResultFunc; - if (awaitableInfo.ResultType == typeof(void)) - { - // var getResultFunc = (object awaiter) => - // { - // ((CustomAwaiterType)awaiter).GetResult(); // We need to invoke this to surface any exceptions - // return (object)null; - // }; - getResultFunc = Expression.Lambda>( - Expression.Block( - Expression.Call( - Expression.Convert(getResultParam, awaitableInfo.AwaiterType), - awaitableInfo.AwaiterGetResultMethod), - Expression.Constant(null) - ), - getResultParam).Compile(); - } - else - { - // var getResultFunc = (object awaiter) => - // (object)((CustomAwaiterType)awaiter).GetResult(); - getResultFunc = Expression.Lambda>( - Expression.Convert( - Expression.Call( - Expression.Convert(getResultParam, awaitableInfo.AwaiterType), - awaitableInfo.AwaiterGetResultMethod), - typeof(object)), - getResultParam).Compile(); - } - - // var onCompletedFunc = (object awaiter, Action continuation) => { - // ((CustomAwaiterType)awaiter).OnCompleted(continuation); - // }; - var onCompletedParam1 = Expression.Parameter(typeof(object), "awaiter"); - var onCompletedParam2 = Expression.Parameter(typeof(Action), "continuation"); - var onCompletedFunc = Expression.Lambda>( - Expression.Call( - Expression.Convert(onCompletedParam1, awaitableInfo.AwaiterType), - awaitableInfo.AwaiterOnCompletedMethod, - onCompletedParam2), - onCompletedParam1, - onCompletedParam2).Compile(); - - Action unsafeOnCompletedFunc = null; - if (awaitableInfo.AwaiterUnsafeOnCompletedMethod != null) - { - // var unsafeOnCompletedFunc = (object awaiter, Action continuation) => { - // ((CustomAwaiterType)awaiter).UnsafeOnCompleted(continuation); - // }; - var unsafeOnCompletedParam1 = Expression.Parameter(typeof(object), "awaiter"); - var unsafeOnCompletedParam2 = Expression.Parameter(typeof(Action), "continuation"); - unsafeOnCompletedFunc = Expression.Lambda>( - Expression.Call( - Expression.Convert(unsafeOnCompletedParam1, awaitableInfo.AwaiterType), - awaitableInfo.AwaiterUnsafeOnCompletedMethod, - unsafeOnCompletedParam2), - unsafeOnCompletedParam1, - unsafeOnCompletedParam2).Compile(); - } - - // If we need to pass the method call result through a coercer function to get an - // awaitable, then do so. - var coercedMethodCall = coercedAwaitableInfo.RequiresCoercion - ? Expression.Invoke(coercedAwaitableInfo.CoercerExpression, methodCall) - : (Expression)methodCall; - - // return new ObjectMethodExecutorAwaitable( - // (object)coercedMethodCall, - // getAwaiterFunc, - // isCompletedFunc, - // getResultFunc, - // onCompletedFunc, - // unsafeOnCompletedFunc); - var returnValueExpression = Expression.New( - _objectMethodExecutorAwaitableConstructor, - Expression.Convert(coercedMethodCall, typeof(object)), - Expression.Constant(getAwaiterFunc), - Expression.Constant(isCompletedFunc), - Expression.Constant(getResultFunc), - Expression.Constant(onCompletedFunc), - Expression.Constant(unsafeOnCompletedFunc, typeof(Action))); - - var lambda = Expression.Lambda(returnValueExpression, targetParameter, parametersParameter); - return lambda.Compile(); - } - } -} diff --git a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutorAwaitable.cs b/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutorAwaitable.cs deleted file mode 100644 index 7509b86b..00000000 --- a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutorAwaitable.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.CompilerServices; - -namespace Microsoft.Extensions.Internal -{ - /// - /// Provides a common awaitable structure that can - /// return, regardless of whether the underlying value is a System.Task, an FSharpAsync, or an - /// application-defined custom awaitable. - /// - internal struct ObjectMethodExecutorAwaitable - { - private readonly object _customAwaitable; - private readonly Func _getAwaiterMethod; - private readonly Func _isCompletedMethod; - private readonly Func _getResultMethod; - private readonly Action _onCompletedMethod; - private readonly Action _unsafeOnCompletedMethod; - - // Perf note: since we're requiring the customAwaitable to be supplied here as an object, - // this will trigger a further allocation if it was a value type (i.e., to box it). We can't - // fix this by making the customAwaitable type generic, because the calling code typically - // does not know the type of the awaitable/awaiter at compile-time anyway. - // - // However, we could fix it by not passing the customAwaitable here at all, and instead - // passing a func that maps directly from the target object (e.g., controller instance), - // target method (e.g., action method info), and params array to the custom awaiter in the - // GetAwaiter() method below. In effect, by delaying the actual method call until the - // upstream code calls GetAwaiter on this ObjectMethodExecutorAwaitable instance. - // This optimization is not currently implemented because: - // [1] It would make no difference when the awaitable was an object type, which is - // by far the most common scenario (e.g., System.Task). - // [2] It would be complex - we'd need some kind of object pool to track all the parameter - // arrays until we needed to use them in GetAwaiter(). - // We can reconsider this in the future if there's a need to optimize for ValueTask - // or other value-typed awaitables. - - public ObjectMethodExecutorAwaitable( - object customAwaitable, - Func getAwaiterMethod, - Func isCompletedMethod, - Func getResultMethod, - Action onCompletedMethod, - Action unsafeOnCompletedMethod) - { - _customAwaitable = customAwaitable; - _getAwaiterMethod = getAwaiterMethod; - _isCompletedMethod = isCompletedMethod; - _getResultMethod = getResultMethod; - _onCompletedMethod = onCompletedMethod; - _unsafeOnCompletedMethod = unsafeOnCompletedMethod; - } - - public Awaiter GetAwaiter() - { - var customAwaiter = _getAwaiterMethod(_customAwaitable); - return new Awaiter(customAwaiter, _isCompletedMethod, _getResultMethod, _onCompletedMethod, _unsafeOnCompletedMethod); - } - - public struct Awaiter : ICriticalNotifyCompletion - { - private readonly object _customAwaiter; - private readonly Func _isCompletedMethod; - private readonly Func _getResultMethod; - private readonly Action _onCompletedMethod; - private readonly Action _unsafeOnCompletedMethod; - - public Awaiter( - object customAwaiter, - Func isCompletedMethod, - Func getResultMethod, - Action onCompletedMethod, - Action unsafeOnCompletedMethod) - { - _customAwaiter = customAwaiter; - _isCompletedMethod = isCompletedMethod; - _getResultMethod = getResultMethod; - _onCompletedMethod = onCompletedMethod; - _unsafeOnCompletedMethod = unsafeOnCompletedMethod; - } - - public bool IsCompleted => _isCompletedMethod(_customAwaiter); - - public object GetResult() => _getResultMethod(_customAwaiter); - - public void OnCompleted(Action continuation) - { - _onCompletedMethod(_customAwaiter, continuation); - } - - public void UnsafeOnCompleted(Action continuation) - { - // If the underlying awaitable implements ICriticalNotifyCompletion, use its UnsafeOnCompleted. - // If not, fall back on using its OnCompleted. - // - // Why this is safe: - // - Implementing ICriticalNotifyCompletion is a way of saying the caller can choose whether it - // needs the execution context to be preserved (which it signals by calling OnCompleted), or - // that it doesn't (which it signals by calling UnsafeOnCompleted). Obviously it's faster *not* - // to preserve and restore the context, so we prefer that where possible. - // - If a caller doesn't need the execution context to be preserved and hence calls UnsafeOnCompleted, - // there's no harm in preserving it anyway - it's just a bit of wasted cost. That's what will happen - // if a caller sees that the proxy implements ICriticalNotifyCompletion but the proxy chooses to - // pass the call on to the underlying awaitable's OnCompleted method. - - var underlyingMethodToUse = _unsafeOnCompletedMethod ?? _onCompletedMethod; - underlyingMethodToUse(_customAwaiter, continuation); - } - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutorFSharpSupport.cs b/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutorFSharpSupport.cs deleted file mode 100644 index 2198c0ce..00000000 --- a/shared/Microsoft.Extensions.ObjectMethodExecutor.Sources/ObjectMethodExecutorFSharpSupport.cs +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Threading; -using System.Threading.Tasks; - -namespace Microsoft.Extensions.Internal -{ - /// - /// Helper for detecting whether a given type is FSharpAsync`1, and if so, supplying - /// an for mapping instances of that type to a C# awaitable. - /// - /// - /// The main design goal here is to avoid taking a compile-time dependency on - /// FSharp.Core.dll, because non-F# applications wouldn't use it. So all the references - /// to FSharp types have to be constructed dynamically at runtime. - /// - internal static class ObjectMethodExecutorFSharpSupport - { - private static object _fsharpValuesCacheLock = new object(); - private static Assembly _fsharpCoreAssembly; - private static MethodInfo _fsharpAsyncStartAsTaskGenericMethod; - private static PropertyInfo _fsharpOptionOfTaskCreationOptionsNoneProperty; - private static PropertyInfo _fsharpOptionOfCancellationTokenNoneProperty; - - public static bool TryBuildCoercerFromFSharpAsyncToAwaitable( - Type possibleFSharpAsyncType, - out Expression coerceToAwaitableExpression, - out Type awaitableType) - { - var methodReturnGenericType = possibleFSharpAsyncType.IsGenericType - ? possibleFSharpAsyncType.GetGenericTypeDefinition() - : null; - - if (!IsFSharpAsyncOpenGenericType(methodReturnGenericType)) - { - coerceToAwaitableExpression = null; - awaitableType = null; - return false; - } - - var awaiterResultType = possibleFSharpAsyncType.GetGenericArguments().Single(); - awaitableType = typeof(Task<>).MakeGenericType(awaiterResultType); - - // coerceToAwaitableExpression = (object fsharpAsync) => - // { - // return (object)FSharpAsync.StartAsTask( - // (Microsoft.FSharp.Control.FSharpAsync)fsharpAsync, - // FSharpOption.None, - // FSharpOption.None); - // }; - var startAsTaskClosedMethod = _fsharpAsyncStartAsTaskGenericMethod - .MakeGenericMethod(awaiterResultType); - var coerceToAwaitableParam = Expression.Parameter(typeof(object)); - coerceToAwaitableExpression = Expression.Lambda( - Expression.Convert( - Expression.Call( - startAsTaskClosedMethod, - Expression.Convert(coerceToAwaitableParam, possibleFSharpAsyncType), - Expression.MakeMemberAccess(null, _fsharpOptionOfTaskCreationOptionsNoneProperty), - Expression.MakeMemberAccess(null, _fsharpOptionOfCancellationTokenNoneProperty)), - typeof(object)), - coerceToAwaitableParam); - - return true; - } - - private static bool IsFSharpAsyncOpenGenericType(Type possibleFSharpAsyncGenericType) - { - var typeFullName = possibleFSharpAsyncGenericType?.FullName; - if (!string.Equals(typeFullName, "Microsoft.FSharp.Control.FSharpAsync`1", StringComparison.Ordinal)) - { - return false; - } - - lock (_fsharpValuesCacheLock) - { - if (_fsharpCoreAssembly != null) - { - // Since we've already found the real FSharpAsync.Core assembly, we just have - // to check that the supplied FSharpAsync`1 type is the one from that assembly. - return possibleFSharpAsyncGenericType.Assembly == _fsharpCoreAssembly; - } - else - { - // We'll keep trying to find the FSharp types/values each time any type called - // FSharpAsync`1 is supplied. - return TryPopulateFSharpValueCaches(possibleFSharpAsyncGenericType); - } - } - } - - private static bool TryPopulateFSharpValueCaches(Type possibleFSharpAsyncGenericType) - { - var assembly = possibleFSharpAsyncGenericType.Assembly; - var fsharpOptionType = assembly.GetType("Microsoft.FSharp.Core.FSharpOption`1"); - var fsharpAsyncType = assembly.GetType("Microsoft.FSharp.Control.FSharpAsync"); - - if (fsharpOptionType == null || fsharpAsyncType == null) - { - return false; - } - - // Get a reference to FSharpOption.None - var fsharpOptionOfTaskCreationOptionsType = fsharpOptionType - .MakeGenericType(typeof(TaskCreationOptions)); - _fsharpOptionOfTaskCreationOptionsNoneProperty = fsharpOptionOfTaskCreationOptionsType - .GetTypeInfo() - .GetRuntimeProperty("None"); - - // Get a reference to FSharpOption.None - var fsharpOptionOfCancellationTokenType = fsharpOptionType - .MakeGenericType(typeof(CancellationToken)); - _fsharpOptionOfCancellationTokenNoneProperty = fsharpOptionOfCancellationTokenType - .GetTypeInfo() - .GetRuntimeProperty("None"); - - // Get a reference to FSharpAsync.StartAsTask<> - var fsharpAsyncMethods = fsharpAsyncType - .GetRuntimeMethods() - .Where(m => m.Name.Equals("StartAsTask", StringComparison.Ordinal)); - foreach (var candidateMethodInfo in fsharpAsyncMethods) - { - var parameters = candidateMethodInfo.GetParameters(); - if (parameters.Length == 3 - && TypesHaveSameIdentity(parameters[0].ParameterType, possibleFSharpAsyncGenericType) - && parameters[1].ParameterType == fsharpOptionOfTaskCreationOptionsType - && parameters[2].ParameterType == fsharpOptionOfCancellationTokenType) - { - // This really does look like the correct method (and hence assembly). - _fsharpAsyncStartAsTaskGenericMethod = candidateMethodInfo; - _fsharpCoreAssembly = assembly; - break; - } - } - - return _fsharpCoreAssembly != null; - } - - private static bool TypesHaveSameIdentity(Type type1, Type type2) - { - return type1.Assembly == type2.Assembly - && string.Equals(type1.Namespace, type2.Namespace, StringComparison.Ordinal) - && string.Equals(type1.Name, type2.Name, StringComparison.Ordinal); - } - } -} diff --git a/shared/Microsoft.Extensions.Process.Sources/ProcessHelper.cs b/shared/Microsoft.Extensions.Process.Sources/ProcessHelper.cs deleted file mode 100644 index cf42a7e3..00000000 --- a/shared/Microsoft.Extensions.Process.Sources/ProcessHelper.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; - -namespace Microsoft.Extensions.Internal -{ - internal static class ProcessExtensions - { - private static readonly bool _isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); - private static readonly TimeSpan _defaultTimeout = TimeSpan.FromSeconds(30); - - public static void KillTree(this Process process) - { - process.KillTree(_defaultTimeout); - } - - public static void KillTree(this Process process, TimeSpan timeout) - { - string stdout; - if (_isWindows) - { - RunProcessAndWaitForExit( - "taskkill", - $"/T /F /PID {process.Id}", - timeout, - out stdout); - } - else - { - var children = new HashSet(); - GetAllChildIdsUnix(process.Id, children, timeout); - foreach (var childId in children) - { - KillProcessUnix(childId, timeout); - } - KillProcessUnix(process.Id, timeout); - } - } - - private static void GetAllChildIdsUnix(int parentId, ISet children, TimeSpan timeout) - { - string stdout; - var exitCode = RunProcessAndWaitForExit( - "pgrep", - $"-P {parentId}", - timeout, - out stdout); - - if (exitCode == 0 && !string.IsNullOrEmpty(stdout)) - { - using (var reader = new StringReader(stdout)) - { - while (true) - { - var text = reader.ReadLine(); - if (text == null) - { - return; - } - - int id; - if (int.TryParse(text, out id)) - { - children.Add(id); - // Recursively get the children - GetAllChildIdsUnix(id, children, timeout); - } - } - } - } - } - - private static void KillProcessUnix(int processId, TimeSpan timeout) - { - string stdout; - RunProcessAndWaitForExit( - "kill", - $"-TERM {processId}", - timeout, - out stdout); - } - - private static int RunProcessAndWaitForExit(string fileName, string arguments, TimeSpan timeout, out string stdout) - { - var startInfo = new ProcessStartInfo - { - FileName = fileName, - Arguments = arguments, - RedirectStandardOutput = true, - UseShellExecute = false - }; - - var process = Process.Start(startInfo); - - stdout = null; - if (process.WaitForExit((int)timeout.TotalMilliseconds)) - { - stdout = process.StandardOutput.ReadToEnd(); - } - else - { - process.Kill(); - } - - return process.ExitCode; - } - } -} diff --git a/shared/Microsoft.Extensions.PropertyActivator.Sources/PropertyActivator.cs b/shared/Microsoft.Extensions.PropertyActivator.Sources/PropertyActivator.cs deleted file mode 100644 index 925f6a76..00000000 --- a/shared/Microsoft.Extensions.PropertyActivator.Sources/PropertyActivator.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Reflection; - -namespace Microsoft.Extensions.Internal -{ - internal class PropertyActivator - { - private readonly Func _valueAccessor; - private readonly Action _fastPropertySetter; - - public PropertyActivator( - PropertyInfo propertyInfo, - Func valueAccessor) - { - if (propertyInfo == null) - { - throw new ArgumentNullException(nameof(propertyInfo)); - } - - if (valueAccessor == null) - { - throw new ArgumentNullException(nameof(valueAccessor)); - } - - PropertyInfo = propertyInfo; - _valueAccessor = valueAccessor; - _fastPropertySetter = PropertyHelper.MakeFastPropertySetter(propertyInfo); - } - - public PropertyInfo PropertyInfo { get; private set; } - - public object Activate(object instance, TContext context) - { - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } - - var value = _valueAccessor(context); - _fastPropertySetter(instance, value); - return value; - } - - public static PropertyActivator[] GetPropertiesToActivate( - Type type, - Type activateAttributeType, - Func> createActivateInfo) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (activateAttributeType == null) - { - throw new ArgumentNullException(nameof(activateAttributeType)); - } - - if (createActivateInfo == null) - { - throw new ArgumentNullException(nameof(createActivateInfo)); - } - - return GetPropertiesToActivate(type, activateAttributeType, createActivateInfo, includeNonPublic: false); - } - - public static PropertyActivator[] GetPropertiesToActivate( - Type type, - Type activateAttributeType, - Func> createActivateInfo, - bool includeNonPublic) - { - if (type == null) - { - throw new ArgumentNullException(nameof(type)); - } - - if (activateAttributeType == null) - { - throw new ArgumentNullException(nameof(activateAttributeType)); - } - - if (createActivateInfo == null) - { - throw new ArgumentNullException(nameof(createActivateInfo)); - } - - var properties = type.GetRuntimeProperties() - .Where((property) => - { - return - property.IsDefined(activateAttributeType) && - property.GetIndexParameters().Length == 0 && - property.SetMethod != null && - !property.SetMethod.IsStatic; - }); - - if (!includeNonPublic) - { - properties = properties.Where(property => property.SetMethod.IsPublic); - } - - return properties.Select(createActivateInfo).ToArray(); - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.PropertyHelper.Sources/PropertyHelper.cs b/shared/Microsoft.Extensions.PropertyHelper.Sources/PropertyHelper.cs deleted file mode 100644 index 27ba5661..00000000 --- a/shared/Microsoft.Extensions.PropertyHelper.Sources/PropertyHelper.cs +++ /dev/null @@ -1,526 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; - -namespace Microsoft.Extensions.Internal -{ - internal class PropertyHelper - { - // Delegate type for a by-ref property getter - private delegate TValue ByRefFunc(ref TDeclaringType arg); - - private static readonly MethodInfo CallPropertyGetterOpenGenericMethod = - typeof(PropertyHelper).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertyGetter)); - - private static readonly MethodInfo CallPropertyGetterByReferenceOpenGenericMethod = - typeof(PropertyHelper).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertyGetterByReference)); - - private static readonly MethodInfo CallNullSafePropertyGetterOpenGenericMethod = - typeof(PropertyHelper).GetTypeInfo().GetDeclaredMethod(nameof(CallNullSafePropertyGetter)); - - private static readonly MethodInfo CallNullSafePropertyGetterByReferenceOpenGenericMethod = - typeof(PropertyHelper).GetTypeInfo().GetDeclaredMethod(nameof(CallNullSafePropertyGetterByReference)); - - private static readonly MethodInfo CallPropertySetterOpenGenericMethod = - typeof(PropertyHelper).GetTypeInfo().GetDeclaredMethod(nameof(CallPropertySetter)); - - // Using an array rather than IEnumerable, as target will be called on the hot path numerous times. - private static readonly ConcurrentDictionary PropertiesCache = - new ConcurrentDictionary(); - - private static readonly ConcurrentDictionary VisiblePropertiesCache = - new ConcurrentDictionary(); - - private Action _valueSetter; - private Func _valueGetter; - - /// - /// Initializes a fast . - /// This constructor does not cache the helper. For caching, use . - /// - public PropertyHelper(PropertyInfo property) - { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } - - Property = property; - Name = property.Name; - } - - /// - /// Gets the backing . - /// - public PropertyInfo Property { get; } - - /// - /// Gets (or sets in derived types) the property name. - /// - public virtual string Name { get; protected set; } - - /// - /// Gets the property value getter. - /// - public Func ValueGetter - { - get - { - if (_valueGetter == null) - { - _valueGetter = MakeFastPropertyGetter(Property); - } - - return _valueGetter; - } - } - - /// - /// Gets the property value setter. - /// - public Action ValueSetter - { - get - { - if (_valueSetter == null) - { - _valueSetter = MakeFastPropertySetter(Property); - } - - return _valueSetter; - } - } - - /// - /// Returns the property value for the specified . - /// - /// The object whose property value will be returned. - /// The property value. - public object GetValue(object instance) - { - return ValueGetter(instance); - } - - /// - /// Sets the property value for the specified . - /// - /// The object whose property value will be set. - /// The property value. - public void SetValue(object instance, object value) - { - ValueSetter(instance, value); - } - - /// - /// Creates and caches fast property helpers that expose getters for every public get property on the - /// underlying type. - /// - /// The type info to extract property accessors for. - /// A cached array of all public properties of the specified type. - /// - public static PropertyHelper[] GetProperties(TypeInfo typeInfo) - { - return GetProperties(typeInfo.AsType()); - } - - /// - /// Creates and caches fast property helpers that expose getters for every public get property on the - /// specified type. - /// - /// The type to extract property accessors for. - /// A cached array of all public properties of the specified type. - /// - public static PropertyHelper[] GetProperties(Type type) - { - return GetProperties(type, CreateInstance, PropertiesCache); - } - - /// - /// - /// Creates and caches fast property helpers that expose getters for every non-hidden get property - /// on the specified type. - /// - /// - /// excludes properties defined on base types that have been - /// hidden by definitions using the new keyword. - /// - /// - /// The type info to extract property accessors for. - /// - /// A cached array of all public properties of the specified type. - /// - public static PropertyHelper[] GetVisibleProperties(TypeInfo typeInfo) - { - return GetVisibleProperties(typeInfo.AsType(), CreateInstance, PropertiesCache, VisiblePropertiesCache); - } - - /// - /// - /// Creates and caches fast property helpers that expose getters for every non-hidden get property - /// on the specified type. - /// - /// - /// excludes properties defined on base types that have been - /// hidden by definitions using the new keyword. - /// - /// - /// The type to extract property accessors for. - /// - /// A cached array of all public properties of the specified type. - /// - public static PropertyHelper[] GetVisibleProperties(Type type) - { - return GetVisibleProperties(type, CreateInstance, PropertiesCache, VisiblePropertiesCache); - } - - /// - /// Creates a single fast property getter. The result is not cached. - /// - /// propertyInfo to extract the getter for. - /// a fast getter. - /// - /// This method is more memory efficient than a dynamically compiled lambda, and about the - /// same speed. - /// - public static Func MakeFastPropertyGetter(PropertyInfo propertyInfo) - { - Debug.Assert(propertyInfo != null); - - return MakeFastPropertyGetter( - propertyInfo, - CallPropertyGetterOpenGenericMethod, - CallPropertyGetterByReferenceOpenGenericMethod); - } - - /// - /// Creates a single fast property getter which is safe for a null input object. The result is not cached. - /// - /// propertyInfo to extract the getter for. - /// a fast getter. - /// - /// This method is more memory efficient than a dynamically compiled lambda, and about the - /// same speed. - /// - public static Func MakeNullSafeFastPropertyGetter(PropertyInfo propertyInfo) - { - Debug.Assert(propertyInfo != null); - - return MakeFastPropertyGetter( - propertyInfo, - CallNullSafePropertyGetterOpenGenericMethod, - CallNullSafePropertyGetterByReferenceOpenGenericMethod); - } - - private static Func MakeFastPropertyGetter( - PropertyInfo propertyInfo, - MethodInfo propertyGetterWrapperMethod, - MethodInfo propertyGetterByRefWrapperMethod) - { - Debug.Assert(propertyInfo != null); - - // Must be a generic method with a Func<,> parameter - Debug.Assert(propertyGetterWrapperMethod != null); - Debug.Assert(propertyGetterWrapperMethod.IsGenericMethodDefinition); - Debug.Assert(propertyGetterWrapperMethod.GetParameters().Length == 2); - - // Must be a generic method with a ByRefFunc<,> parameter - Debug.Assert(propertyGetterByRefWrapperMethod != null); - Debug.Assert(propertyGetterByRefWrapperMethod.IsGenericMethodDefinition); - Debug.Assert(propertyGetterByRefWrapperMethod.GetParameters().Length == 2); - - var getMethod = propertyInfo.GetMethod; - Debug.Assert(getMethod != null); - Debug.Assert(!getMethod.IsStatic); - Debug.Assert(getMethod.GetParameters().Length == 0); - - // Instance methods in the CLR can be turned into static methods where the first parameter - // is open over "target". This parameter is always passed by reference, so we have a code - // path for value types and a code path for reference types. - if (getMethod.DeclaringType.GetTypeInfo().IsValueType) - { - // Create a delegate (ref TDeclaringType) -> TValue - return MakeFastPropertyGetter( - typeof(ByRefFunc<,>), - getMethod, - propertyGetterByRefWrapperMethod); - } - else - { - // Create a delegate TDeclaringType -> TValue - return MakeFastPropertyGetter( - typeof(Func<,>), - getMethod, - propertyGetterWrapperMethod); - } - } - - private static Func MakeFastPropertyGetter( - Type openGenericDelegateType, - MethodInfo propertyGetMethod, - MethodInfo openGenericWrapperMethod) - { - var typeInput = propertyGetMethod.DeclaringType; - var typeOutput = propertyGetMethod.ReturnType; - - var delegateType = openGenericDelegateType.MakeGenericType(typeInput, typeOutput); - var propertyGetterDelegate = propertyGetMethod.CreateDelegate(delegateType); - - var wrapperDelegateMethod = openGenericWrapperMethod.MakeGenericMethod(typeInput, typeOutput); - var accessorDelegate = wrapperDelegateMethod.CreateDelegate( - typeof(Func), - propertyGetterDelegate); - - return (Func)accessorDelegate; - } - - /// - /// Creates a single fast property setter for reference types. The result is not cached. - /// - /// propertyInfo to extract the setter for. - /// a fast getter. - /// - /// This method is more memory efficient than a dynamically compiled lambda, and about the - /// same speed. This only works for reference types. - /// - public static Action MakeFastPropertySetter(PropertyInfo propertyInfo) - { - Debug.Assert(propertyInfo != null); - Debug.Assert(!propertyInfo.DeclaringType.GetTypeInfo().IsValueType); - - var setMethod = propertyInfo.SetMethod; - Debug.Assert(setMethod != null); - Debug.Assert(!setMethod.IsStatic); - Debug.Assert(setMethod.ReturnType == typeof(void)); - var parameters = setMethod.GetParameters(); - Debug.Assert(parameters.Length == 1); - - // Instance methods in the CLR can be turned into static methods where the first parameter - // is open over "target". This parameter is always passed by reference, so we have a code - // path for value types and a code path for reference types. - var typeInput = setMethod.DeclaringType; - var parameterType = parameters[0].ParameterType; - - // Create a delegate TDeclaringType -> { TDeclaringType.Property = TValue; } - var propertySetterAsAction = - setMethod.CreateDelegate(typeof(Action<,>).MakeGenericType(typeInput, parameterType)); - var callPropertySetterClosedGenericMethod = - CallPropertySetterOpenGenericMethod.MakeGenericMethod(typeInput, parameterType); - var callPropertySetterDelegate = - callPropertySetterClosedGenericMethod.CreateDelegate( - typeof(Action), propertySetterAsAction); - - return (Action)callPropertySetterDelegate; - } - - /// - /// Given an object, adds each instance property with a public get method as a key and its - /// associated value to a dictionary. - /// - /// If the object is already an instance, then a copy - /// is returned. - /// - /// - /// The implementation of PropertyHelper will cache the property accessors per-type. This is - /// faster when the same type is used multiple times with ObjectToDictionary. - /// - public static IDictionary ObjectToDictionary(object value) - { - var dictionary = value as IDictionary; - if (dictionary != null) - { - return new Dictionary(dictionary, StringComparer.OrdinalIgnoreCase); - } - - dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); - - if (value != null) - { - foreach (var helper in GetProperties(value.GetType())) - { - dictionary[helper.Name] = helper.GetValue(value); - } - } - - return dictionary; - } - - private static PropertyHelper CreateInstance(PropertyInfo property) - { - return new PropertyHelper(property); - } - - // Called via reflection - private static object CallPropertyGetter( - Func getter, - object target) - { - return getter((TDeclaringType)target); - } - - // Called via reflection - private static object CallPropertyGetterByReference( - ByRefFunc getter, - object target) - { - var unboxed = (TDeclaringType)target; - return getter(ref unboxed); - } - - // Called via reflection - private static object CallNullSafePropertyGetter( - Func getter, - object target) - { - if (target == null) - { - return null; - } - - return getter((TDeclaringType)target); - } - - // Called via reflection - private static object CallNullSafePropertyGetterByReference( - ByRefFunc getter, - object target) - { - if (target == null) - { - return null; - } - - var unboxed = (TDeclaringType)target; - return getter(ref unboxed); - } - - private static void CallPropertySetter( - Action setter, - object target, - object value) - { - setter((TDeclaringType)target, (TValue)value); - } - - protected static PropertyHelper[] GetVisibleProperties( - Type type, - Func createPropertyHelper, - ConcurrentDictionary allPropertiesCache, - ConcurrentDictionary visiblePropertiesCache) - { - PropertyHelper[] result; - if (visiblePropertiesCache.TryGetValue(type, out result)) - { - return result; - } - - // The simple and common case, this is normal POCO object - no need to allocate. - var allPropertiesDefinedOnType = true; - var allProperties = GetProperties(type, createPropertyHelper, allPropertiesCache); - foreach (var propertyHelper in allProperties) - { - if (propertyHelper.Property.DeclaringType != type) - { - allPropertiesDefinedOnType = false; - break; - } - } - - if (allPropertiesDefinedOnType) - { - result = allProperties; - visiblePropertiesCache.TryAdd(type, result); - return result; - } - - // There's some inherited properties here, so we need to check for hiding via 'new'. - var filteredProperties = new List(allProperties.Length); - foreach (var propertyHelper in allProperties) - { - var declaringType = propertyHelper.Property.DeclaringType; - if (declaringType == type) - { - filteredProperties.Add(propertyHelper); - continue; - } - - // If this property was declared on a base type then look for the definition closest to the - // the type to see if we should include it. - var ignoreProperty = false; - - // Walk up the hierarchy until we find the type that actually declares this - // PropertyInfo. - var currentTypeInfo = type.GetTypeInfo(); - var declaringTypeInfo = declaringType.GetTypeInfo(); - while (currentTypeInfo != null && currentTypeInfo != declaringTypeInfo) - { - // We've found a 'more proximal' public definition - var declaredProperty = currentTypeInfo.GetDeclaredProperty(propertyHelper.Name); - if (declaredProperty != null) - { - ignoreProperty = true; - break; - } - - currentTypeInfo = currentTypeInfo.BaseType?.GetTypeInfo(); - } - - if (!ignoreProperty) - { - filteredProperties.Add(propertyHelper); - } - } - - result = filteredProperties.ToArray(); - visiblePropertiesCache.TryAdd(type, result); - return result; - } - - protected static PropertyHelper[] GetProperties( - Type type, - Func createPropertyHelper, - ConcurrentDictionary cache) - { - // Unwrap nullable types. This means Nullable.Value and Nullable.HasValue will not be - // part of the sequence of properties returned by this method. - type = Nullable.GetUnderlyingType(type) ?? type; - - PropertyHelper[] helpers; - if (!cache.TryGetValue(type, out helpers)) - { - // We avoid loading indexed properties using the Where statement. - var properties = type.GetRuntimeProperties().Where(IsInterestingProperty); - - var typeInfo = type.GetTypeInfo(); - if (typeInfo.IsInterface) - { - // Reflection does not return information about inherited properties on the interface itself. - properties = properties.Concat(typeInfo.ImplementedInterfaces.SelectMany( - interfaceType => interfaceType.GetRuntimeProperties().Where(IsInterestingProperty))); - } - - helpers = properties.Select(p => createPropertyHelper(p)).ToArray(); - cache.TryAdd(type, helpers); - } - - return helpers; - } - - // Indexed properties are not useful (or valid) for grabbing properties off an object. - private static bool IsInterestingProperty(PropertyInfo property) - { - // For improving application startup time, do not use GetIndexParameters() api early in this check as it - // creates a copy of parameter array and also we would like to check for the presence of a get method - // and short circuit asap. - return property.GetMethod != null && - property.GetMethod.IsPublic && - !property.GetMethod.IsStatic && - property.GetMethod.GetParameters().Length == 0; - } - } -} diff --git a/shared/Microsoft.Extensions.RazorViews.Sources/AttributeValue.cs b/shared/Microsoft.Extensions.RazorViews.Sources/AttributeValue.cs deleted file mode 100644 index 7a066a70..00000000 --- a/shared/Microsoft.Extensions.RazorViews.Sources/AttributeValue.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.Extensions.RazorViews -{ - internal class AttributeValue - { - public AttributeValue(string prefix, object value, bool literal) - { - Prefix = prefix; - Value = value; - Literal = literal; - } - - public string Prefix { get; } - - public object Value { get; } - - public bool Literal { get; } - - public static AttributeValue FromTuple(Tuple value) - { - return new AttributeValue(value.Item1, value.Item2, value.Item3); - } - - public static AttributeValue FromTuple(Tuple value) - { - return new AttributeValue(value.Item1, value.Item2, value.Item3); - } - - public static implicit operator AttributeValue(Tuple value) - { - return FromTuple(value); - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.RazorViews.Sources/BaseView.cs b/shared/Microsoft.Extensions.RazorViews.Sources/BaseView.cs deleted file mode 100644 index d93a6fc2..00000000 --- a/shared/Microsoft.Extensions.RazorViews.Sources/BaseView.cs +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.Encodings.Web; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; - -namespace Microsoft.Extensions.RazorViews -{ - /// - /// Infrastructure - /// - internal abstract class BaseView - { - private static readonly Encoding UTF8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); - - /// - /// The request context - /// - protected HttpContext Context { get; private set; } - - /// - /// The request - /// - protected HttpRequest Request { get; private set; } - - /// - /// The response - /// - protected HttpResponse Response { get; private set; } - - /// - /// The output stream - /// - protected StreamWriter Output { get; private set; } - - /// - /// Html encoder used to encode content. - /// - protected HtmlEncoder HtmlEncoder { get; set; } = HtmlEncoder.Default; - - /// - /// Url encoder used to encode content. - /// - protected UrlEncoder UrlEncoder { get; set; } = UrlEncoder.Default; - - /// - /// JavaScript encoder used to encode content. - /// - protected JavaScriptEncoder JavaScriptEncoder { get; set; } = JavaScriptEncoder.Default; - - /// - /// Execute an individual request - /// - /// - public async Task ExecuteAsync(HttpContext context) - { - Context = context; - Request = Context.Request; - Response = Context.Response; - Output = new StreamWriter(Response.Body, UTF8NoBOM, 4096, leaveOpen: true); - await ExecuteAsync(); - Output.Dispose(); - } - - /// - /// Execute an individual request - /// - public abstract Task ExecuteAsync(); - - /// - /// Write the given value directly to the output - /// - /// - protected void WriteLiteral(string value) - { - WriteLiteralTo(Output, value); - } - - /// - /// Write the given value directly to the output - /// - /// - protected void WriteLiteral(object value) - { - WriteLiteralTo(Output, value); - } - - private List AttributeValues { get; set; } - - protected void WriteAttributeValue(string thingy, int startPostion, object value, int endValue, int dealyo, bool yesno) - { - if (AttributeValues == null) - { - AttributeValues = new List(); - } - - AttributeValues.Add(value.ToString()); - } - - private string AttributeEnding { get; set; } - - protected void BeginWriteAttribute(string name, string begining, int startPosition, string ending, int endPosition, int thingy) - { - Debug.Assert(string.IsNullOrEmpty(AttributeEnding)); - - Output.Write(begining); - AttributeEnding = ending; - } - - protected void EndWriteAttribute() - { - Debug.Assert(!string.IsNullOrEmpty(AttributeEnding)); - - var attributes = string.Join(" ", AttributeValues); - Output.Write(attributes); - AttributeValues = null; - - Output.Write(AttributeEnding); - AttributeEnding = null; - } - - /// - /// Writes the given attribute to the given writer - /// - /// The instance to write to. - /// The name of the attribute to write - /// The value of the prefix - /// The value of the suffix - /// The s to write. - protected void WriteAttributeTo( - TextWriter writer, - string name, - string leader, - string trailer, - params AttributeValue[] values) - { - if (writer == null) - { - throw new ArgumentNullException(nameof(writer)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (leader == null) - { - throw new ArgumentNullException(nameof(leader)); - } - - if (trailer == null) - { - throw new ArgumentNullException(nameof(trailer)); - } - - - WriteLiteralTo(writer, leader); - foreach (var value in values) - { - WriteLiteralTo(writer, value.Prefix); - - // The special cases here are that the value we're writing might already be a string, or that the - // value might be a bool. If the value is the bool 'true' we want to write the attribute name - // instead of the string 'true'. If the value is the bool 'false' we don't want to write anything. - // Otherwise the value is another object (perhaps an HtmlString) and we'll ask it to format itself. - string stringValue; - if (value.Value is bool) - { - if ((bool)value.Value) - { - stringValue = name; - } - else - { - continue; - } - } - else - { - stringValue = value.Value as string; - } - - // Call the WriteTo(string) overload when possible - if (value.Literal && stringValue != null) - { - WriteLiteralTo(writer, stringValue); - } - else if (value.Literal) - { - WriteLiteralTo(writer, value.Value); - } - else if (stringValue != null) - { - WriteTo(writer, stringValue); - } - else - { - WriteTo(writer, value.Value); - } - } - WriteLiteralTo(writer, trailer); - } - - /// - /// Convert to string and html encode - /// - /// - protected void Write(object value) - { - WriteTo(Output, value); - } - - /// - /// Html encode and write - /// - /// - protected void Write(string value) - { - WriteTo(Output, value); - } - - /// - /// is invoked - /// - /// The to invoke - protected void Write(HelperResult result) - { - WriteTo(Output, result); - } - - /// - /// Writes the specified to . - /// - /// The instance to write to. - /// The to write. - /// - /// is invoked for types. - /// For all other types, the encoded result of is written to the - /// . - /// - protected void WriteTo(TextWriter writer, object value) - { - if (value != null) - { - var helperResult = value as HelperResult; - if (helperResult != null) - { - helperResult.WriteTo(writer); - } - else - { - WriteTo(writer, Convert.ToString(value, CultureInfo.InvariantCulture)); - } - } - } - - /// - /// Writes the specified with HTML encoding to . - /// - /// The instance to write to. - /// The to write. - protected void WriteTo(TextWriter writer, string value) - { - WriteLiteralTo(writer, HtmlEncoder.Encode(value)); - } - - /// - /// Writes the specified without HTML encoding to the . - /// - /// The instance to write to. - /// The to write. - protected void WriteLiteralTo(TextWriter writer, object value) - { - WriteLiteralTo(writer, Convert.ToString(value, CultureInfo.InvariantCulture)); - } - - /// - /// Writes the specified without HTML encoding to . - /// - /// The instance to write to. - /// The to write. - protected void WriteLiteralTo(TextWriter writer, string value) - { - if (!string.IsNullOrEmpty(value)) - { - writer.Write(value); - } - } - - protected string HtmlEncodeAndReplaceLineBreaks(string input) - { - if (string.IsNullOrEmpty(input)) - { - return string.Empty; - } - - // Split on line breaks before passing it through the encoder. - return string.Join("
" + Environment.NewLine, - input.Split(new[] { "\r\n" }, StringSplitOptions.None) - .SelectMany(s => s.Split(new[] { '\r', '\n' }, StringSplitOptions.None)) - .Select(HtmlEncoder.Encode)); - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.RazorViews.Sources/HelperResult.cs b/shared/Microsoft.Extensions.RazorViews.Sources/HelperResult.cs deleted file mode 100644 index c79944aa..00000000 --- a/shared/Microsoft.Extensions.RazorViews.Sources/HelperResult.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; - -namespace Microsoft.Extensions.RazorViews -{ - /// - /// Represents a deferred write operation in a . - /// - internal class HelperResult - { - /// - /// Creates a new instance of . - /// - /// The delegate to invoke when is called. - public HelperResult(Action action) - { - WriteAction = action; - } - - public Action WriteAction { get; } - - /// - /// Method invoked to produce content from the . - /// - /// The instance to write to. - public void WriteTo(TextWriter writer) - { - WriteAction(writer); - } - } -} \ No newline at end of file diff --git a/shared/Microsoft.Extensions.SecurityHelper.Sources/SecurityHelper.cs b/shared/Microsoft.Extensions.SecurityHelper.Sources/SecurityHelper.cs deleted file mode 100644 index 408ef6b2..00000000 --- a/shared/Microsoft.Extensions.SecurityHelper.Sources/SecurityHelper.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using System.Security.Claims; - -namespace Microsoft.Extensions.Internal -{ - /// - /// Helper code used when implementing authentication middleware - /// - internal static class SecurityHelper - { - /// - /// Add all ClaimsIdentities from an additional ClaimPrincipal to the ClaimsPrincipal - /// Merges a new claims principal, placing all new identities first, and eliminating - /// any empty unauthenticated identities from context.User - /// - /// The containing existing . - /// The containing to be added. - public static ClaimsPrincipal MergeUserPrincipal(ClaimsPrincipal existingPrincipal, ClaimsPrincipal additionalPrincipal) - { - var newPrincipal = new ClaimsPrincipal(); - - // New principal identities go first - if (additionalPrincipal != null) - { - newPrincipal.AddIdentities(additionalPrincipal.Identities); - } - - // Then add any existing non empty or authenticated identities - if (existingPrincipal != null) - { - newPrincipal.AddIdentities(existingPrincipal.Identities.Where(i => i.IsAuthenticated || i.Claims.Any())); - } - return newPrincipal; - } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/ExceptionDetails/ExceptionDetails.cs b/shared/Microsoft.Extensions.StackTrace.Sources/ExceptionDetails/ExceptionDetails.cs deleted file mode 100644 index 88626111..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/ExceptionDetails/ExceptionDetails.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - /// - /// Contains details for individual exception messages. - /// - internal class ExceptionDetails - { - /// - /// An individual exception - /// - public Exception Error { get; set; } - - /// - /// The generated stack frames - /// - public IEnumerable StackFrames { get; set; } - - /// - /// Gets or sets the summary message. - /// - public string ErrorMessage { get; set; } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/ExceptionDetails/ExceptionDetailsProvider.cs b/shared/Microsoft.Extensions.StackTrace.Sources/ExceptionDetails/ExceptionDetailsProvider.cs deleted file mode 100644 index 2d1dd207..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/ExceptionDetails/ExceptionDetailsProvider.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using Microsoft.Extensions.FileProviders; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - internal class ExceptionDetailsProvider - { - private readonly IFileProvider _fileProvider; - private readonly int _sourceCodeLineCount; - - public ExceptionDetailsProvider(IFileProvider fileProvider, int sourceCodeLineCount) - { - _fileProvider = fileProvider; - _sourceCodeLineCount = sourceCodeLineCount; - } - - public IEnumerable GetDetails(Exception exception) - { - var exceptions = FlattenAndReverseExceptionTree(exception); - - foreach (var ex in exceptions) - { - yield return new ExceptionDetails - { - Error = ex, - StackFrames = StackTraceHelper.GetFrames(ex) - .Select(frame => GetStackFrameSourceCodeInfo( - frame.MethodDisplayInfo.ToString(), - frame.FilePath, - frame.LineNumber)) - }; - } - } - - private static IEnumerable FlattenAndReverseExceptionTree(Exception ex) - { - // ReflectionTypeLoadException is special because the details are in - // the LoaderExceptions property - var typeLoadException = ex as ReflectionTypeLoadException; - if (typeLoadException != null) - { - var typeLoadExceptions = new List(); - foreach (var loadException in typeLoadException.LoaderExceptions) - { - typeLoadExceptions.AddRange(FlattenAndReverseExceptionTree(loadException)); - } - - typeLoadExceptions.Add(ex); - return typeLoadExceptions; - } - - var list = new List(); - if (ex is AggregateException aggregateException) - { - list.Add(ex); - foreach (var innerException in aggregateException.Flatten().InnerExceptions) - { - list.Add(innerException); - } - } - - else - { - while (ex != null) - { - list.Add(ex); - ex = ex.InnerException; - } - list.Reverse(); - } - - return list; - } - - // make it internal to enable unit testing - internal StackFrameSourceCodeInfo GetStackFrameSourceCodeInfo(string method, string filePath, int lineNumber) - { - var stackFrame = new StackFrameSourceCodeInfo - { - Function = method, - File = filePath, - Line = lineNumber - }; - - if (string.IsNullOrEmpty(stackFrame.File)) - { - return stackFrame; - } - - IEnumerable lines = null; - if (File.Exists(stackFrame.File)) - { - lines = File.ReadLines(stackFrame.File); - } - else - { - // Handle relative paths and embedded files - var fileInfo = _fileProvider.GetFileInfo(stackFrame.File); - if (fileInfo.Exists) - { - // ReadLines doesn't accept a stream. Use ReadLines as its more efficient - // relative to reading lines via stream reader - if (!string.IsNullOrEmpty(fileInfo.PhysicalPath)) - { - lines = File.ReadLines(fileInfo.PhysicalPath); - } - else - { - lines = ReadLines(fileInfo); - } - } - } - - if (lines != null) - { - ReadFrameContent(stackFrame, lines, stackFrame.Line, stackFrame.Line); - } - - return stackFrame; - } - - // make it internal to enable unit testing - internal void ReadFrameContent( - StackFrameSourceCodeInfo frame, - IEnumerable allLines, - int errorStartLineNumberInFile, - int errorEndLineNumberInFile) - { - // Get the line boundaries in the file to be read and read all these lines at once into an array. - var preErrorLineNumberInFile = Math.Max(errorStartLineNumberInFile - _sourceCodeLineCount, 1); - var postErrorLineNumberInFile = errorEndLineNumberInFile + _sourceCodeLineCount; - var codeBlock = allLines - .Skip(preErrorLineNumberInFile - 1) - .Take(postErrorLineNumberInFile - preErrorLineNumberInFile + 1) - .ToArray(); - - var numOfErrorLines = (errorEndLineNumberInFile - errorStartLineNumberInFile) + 1; - var errorStartLineNumberInArray = errorStartLineNumberInFile - preErrorLineNumberInFile; - - frame.PreContextLine = preErrorLineNumberInFile; - frame.PreContextCode = codeBlock.Take(errorStartLineNumberInArray).ToArray(); - frame.ContextCode = codeBlock - .Skip(errorStartLineNumberInArray) - .Take(numOfErrorLines) - .ToArray(); - frame.PostContextCode = codeBlock - .Skip(errorStartLineNumberInArray + numOfErrorLines) - .ToArray(); - } - - private static IEnumerable ReadLines(IFileInfo fileInfo) - { - using (var reader = new StreamReader(fileInfo.CreateReadStream())) - { - string line; - while ((line = reader.ReadLine()) != null) - { - yield return line; - } - } - } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/MethodDisplayInfo.cs b/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/MethodDisplayInfo.cs deleted file mode 100644 index c64c0983..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/MethodDisplayInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - internal class MethodDisplayInfo - { - public string DeclaringTypeName { get; set; } - - public string Name { get; set; } - - public string GenericArguments { get; set; } - - public IEnumerable Parameters { get; set; } - - public override string ToString() - { - var builder = new StringBuilder(); - if (!string.IsNullOrEmpty(DeclaringTypeName)) - { - builder - .Append(DeclaringTypeName) - .Append("."); - } - - builder.Append(Name); - builder.Append(GenericArguments); - - builder.Append("("); - builder.Append(string.Join(", ", Parameters.Select(p => p.ToString()))); - builder.Append(")"); - - return builder.ToString(); - } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/ParameterDisplayInfo.cs b/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/ParameterDisplayInfo.cs deleted file mode 100644 index 1199a838..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/ParameterDisplayInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - internal class ParameterDisplayInfo - { - public string Name { get; set; } - - public string Type { get; set; } - - public string Prefix { get; set; } - - public override string ToString() - { - var builder = new StringBuilder(); - if (!string.IsNullOrEmpty(Prefix)) - { - builder - .Append(Prefix) - .Append(" "); - } - - builder.Append(Type); - builder.Append(" "); - builder.Append(Name); - - return builder.ToString(); - } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/PortablePdbReader.cs b/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/PortablePdbReader.cs deleted file mode 100644 index ff6a4947..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/PortablePdbReader.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Reflection; -using System.Reflection.Metadata; -using System.Reflection.Metadata.Ecma335; -using System.Reflection.PortableExecutable; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - internal class PortablePdbReader : IDisposable - { - private readonly Dictionary _cache = - new Dictionary(StringComparer.Ordinal); - - public void PopulateStackFrame(StackFrameInfo frameInfo, MethodBase method, int IlOffset) - { - if (method.Module.Assembly.IsDynamic) - { - return; - } - - var metadataReader = GetMetadataReader(method.Module.Assembly.Location); - - if (metadataReader == null) - { - return; - } - - var methodToken = MetadataTokens.Handle(method.MetadataToken); - - Debug.Assert(methodToken.Kind == HandleKind.MethodDefinition); - - var handle = ((MethodDefinitionHandle)methodToken).ToDebugInformationHandle(); - - if (!handle.IsNil) - { - var methodDebugInfo = metadataReader.GetMethodDebugInformation(handle); - var sequencePoints = methodDebugInfo.GetSequencePoints(); - SequencePoint? bestPointSoFar = null; - - foreach (var point in sequencePoints) - { - if (point.Offset > IlOffset) - { - break; - } - - if (point.StartLine != SequencePoint.HiddenLine) - { - bestPointSoFar = point; - } - } - - if (bestPointSoFar.HasValue) - { - frameInfo.LineNumber = bestPointSoFar.Value.StartLine; - frameInfo.FilePath = metadataReader.GetString(metadataReader.GetDocument(bestPointSoFar.Value.Document).Name); - } - } - } - - private MetadataReader GetMetadataReader(string assemblyPath) - { - MetadataReaderProvider provider = null; - if (!_cache.TryGetValue(assemblyPath, out provider)) - { - var pdbPath = GetPdbPath(assemblyPath); - - if (!string.IsNullOrEmpty(pdbPath) && File.Exists(pdbPath) && IsPortable(pdbPath)) - { - var pdbStream = File.OpenRead(pdbPath); - provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream); - } - - _cache[assemblyPath] = provider; - } - - return provider?.GetMetadataReader(); - } - - private static string GetPdbPath(string assemblyPath) - { - if (string.IsNullOrEmpty(assemblyPath)) - { - return null; - } - - if (File.Exists(assemblyPath)) - { - var peStream = File.OpenRead(assemblyPath); - - using (var peReader = new PEReader(peStream)) - { - foreach (var entry in peReader.ReadDebugDirectory()) - { - if (entry.Type == DebugDirectoryEntryType.CodeView) - { - var codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry); - var peDirectory = Path.GetDirectoryName(assemblyPath); - return Path.Combine(peDirectory, Path.GetFileName(codeViewData.Path)); - } - } - } - } - - return null; - } - - private static bool IsPortable(string pdbPath) - { - using (var pdbStream = File.OpenRead(pdbPath)) - { - return pdbStream.ReadByte() == 'B' && - pdbStream.ReadByte() == 'S' && - pdbStream.ReadByte() == 'J' && - pdbStream.ReadByte() == 'B'; - } - } - - public void Dispose() - { - foreach (var entry in _cache) - { - entry.Value?.Dispose(); - } - - _cache.Clear(); - } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackFrameInfo.cs b/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackFrameInfo.cs deleted file mode 100644 index ffd91f21..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackFrameInfo.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Diagnostics; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - internal class StackFrameInfo - { - public int LineNumber { get; set; } - - public string FilePath { get; set; } - - public StackFrame StackFrame { get; set; } - - public MethodDisplayInfo MethodDisplayInfo { get; set; } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackFrameSourceCodeInfo.cs b/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackFrameSourceCodeInfo.cs deleted file mode 100644 index 2932e083..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackFrameSourceCodeInfo.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - /// - /// Contains the source code where the exception occurred. - /// - internal class StackFrameSourceCodeInfo - { - /// - /// Function containing instruction - /// - public string Function { get; set; } - - /// - /// File containing the instruction - /// - public string File { get; set; } - - /// - /// The line number of the instruction - /// - public int Line { get; set; } - - /// - /// The line preceding the frame line - /// - public int PreContextLine { get; set; } - - /// - /// Lines of code before the actual error line(s). - /// - public IEnumerable PreContextCode { get; set; } = Enumerable.Empty(); - - /// - /// Line(s) of code responsible for the error. - /// - public IEnumerable ContextCode { get; set; } = Enumerable.Empty(); - - /// - /// Lines of code after the actual error line(s). - /// - public IEnumerable PostContextCode { get; set; } = Enumerable.Empty(); - - /// - /// Specific error details for this stack frame. - /// - public string ErrorDetails { get; set; } - } -} diff --git a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackTraceHelper.cs b/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackTraceHelper.cs deleted file mode 100644 index 95ecd2d1..00000000 --- a/shared/Microsoft.Extensions.StackTrace.Sources/StackFrame/StackTraceHelper.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Microsoft.Extensions.Internal; - -namespace Microsoft.Extensions.StackTrace.Sources -{ - internal class StackTraceHelper - { - public static IList GetFrames(Exception exception) - { - var frames = new List(); - - if (exception == null) - { - return frames; - } - - using (var portablePdbReader = new PortablePdbReader()) - { - var needFileInfo = true; - var stackTrace = new System.Diagnostics.StackTrace(exception, needFileInfo); - var stackFrames = stackTrace.GetFrames(); - - if (stackFrames == null) - { - return frames; - } - - foreach (var frame in stackFrames) - { - var method = frame.GetMethod(); - - var stackFrame = new StackFrameInfo - { - StackFrame = frame, - FilePath = frame.GetFileName(), - LineNumber = frame.GetFileLineNumber(), - MethodDisplayInfo = GetMethodDisplayString(frame.GetMethod()), - }; - - if (string.IsNullOrEmpty(stackFrame.FilePath)) - { - // .NET Framework and older versions of mono don't support portable PDBs - // so we read it manually to get file name and line information - portablePdbReader.PopulateStackFrame(stackFrame, method, frame.GetILOffset()); - } - - frames.Add(stackFrame); - } - - return frames; - } - } - - internal static MethodDisplayInfo GetMethodDisplayString(MethodBase method) - { - // Special case: no method available - if (method == null) - { - return null; - } - - var methodDisplayInfo = new MethodDisplayInfo(); - - // Type name - var type = method.DeclaringType; - if (type != null) - { - methodDisplayInfo.DeclaringTypeName = TypeNameHelper.GetTypeDisplayName(type); - } - - // Method name - methodDisplayInfo.Name = method.Name; - if (method.IsGenericMethod) - { - var genericArguments = string.Join(", ", method.GetGenericArguments() - .Select(arg => TypeNameHelper.GetTypeDisplayName(arg, fullName: false))); - methodDisplayInfo.GenericArguments += "<" + genericArguments + ">"; - } - - // Method parameters - methodDisplayInfo.Parameters = method.GetParameters().Select(parameter => - { - var parameterType = parameter.ParameterType; - - var prefix = string.Empty; - if (parameter.IsOut) - { - prefix = "out"; - } - else if (parameterType != null && parameterType.IsByRef) - { - prefix = "ref"; - } - - var parameterTypeString = "?"; - if (parameterType != null) - { - if (parameterType.IsByRef) - { - parameterType = parameterType.GetElementType(); - } - - parameterTypeString = TypeNameHelper.GetTypeDisplayName(parameterType, fullName: false); - } - - return new ParameterDisplayInfo - { - Prefix = prefix, - Name = parameter.Name, - Type = parameterTypeString, - }; - }); - - return methodDisplayInfo; - } - } -} diff --git a/shared/Microsoft.Extensions.TypeNameHelper.Sources/TypeNameHelper.cs b/shared/Microsoft.Extensions.TypeNameHelper.Sources/TypeNameHelper.cs deleted file mode 100644 index 9735f1bc..00000000 --- a/shared/Microsoft.Extensions.TypeNameHelper.Sources/TypeNameHelper.cs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Text; - -namespace Microsoft.Extensions.Internal -{ - internal class TypeNameHelper - { - private static readonly Dictionary _builtInTypeNames = new Dictionary - { - { typeof(bool), "bool" }, - { typeof(byte), "byte" }, - { typeof(char), "char" }, - { typeof(decimal), "decimal" }, - { typeof(double), "double" }, - { typeof(float), "float" }, - { typeof(int), "int" }, - { typeof(long), "long" }, - { typeof(object), "object" }, - { typeof(sbyte), "sbyte" }, - { typeof(short), "short" }, - { typeof(string), "string" }, - { typeof(uint), "uint" }, - { typeof(ulong), "ulong" }, - { typeof(ushort), "ushort" } - }; - - public static string GetTypeDisplayName(object item, bool fullName = true) - { - return item == null ? null : GetTypeDisplayName(item.GetType(), fullName); - } - - public static string GetTypeDisplayName(Type type, bool fullName = true) - { - var sb = new StringBuilder(); - ProcessTypeName(type, sb, fullName); - return sb.ToString(); - } - - private static void AppendGenericArguments(Type[] args, int startIndex, int numberOfArgsToAppend, StringBuilder sb, bool fullName) - { - var totalArgs = args.Length; - if (totalArgs >= startIndex + numberOfArgsToAppend) - { - sb.Append("<"); - for (int i = startIndex; i < startIndex + numberOfArgsToAppend; i++) - { - ProcessTypeName(args[i], sb, fullName); - if (i + 1 < startIndex + numberOfArgsToAppend) - { - sb.Append(", "); - } - } - sb.Append(">"); - } - } - - private static void ProcessTypeName(Type t, StringBuilder sb, bool fullName) - { - if (t.GetTypeInfo().IsGenericType) - { - ProcessNestedGenericTypes(t, sb, fullName); - return; - } - if (_builtInTypeNames.ContainsKey(t)) - { - sb.Append(_builtInTypeNames[t]); - } - else - { - sb.Append(fullName ? t.FullName : t.Name); - } - } - - private static void ProcessNestedGenericTypes(Type t, StringBuilder sb, bool fullName) - { - var genericFullName = t.GetGenericTypeDefinition().FullName; - var genericSimpleName = t.GetGenericTypeDefinition().Name; - var parts = genericFullName.Split('+'); - var genericArguments = t.GetTypeInfo().GenericTypeArguments; - var index = 0; - var totalParts = parts.Length; - if (totalParts == 1) - { - var part = parts[0]; - var num = part.IndexOf('`'); - if (num == -1) return; - - var name = part.Substring(0, num); - var numberOfGenericTypeArgs = int.Parse(part.Substring(num + 1)); - sb.Append(fullName ? name : genericSimpleName.Substring(0, genericSimpleName.IndexOf('`'))); - AppendGenericArguments(genericArguments, index, numberOfGenericTypeArgs, sb, fullName); - return; - } - for (var i = 0; i < totalParts; i++) - { - var part = parts[i]; - var num = part.IndexOf('`'); - if (num != -1) - { - var name = part.Substring(0, num); - var numberOfGenericTypeArgs = int.Parse(part.Substring(num + 1)); - if (fullName || i == totalParts - 1) - { - sb.Append(name); - AppendGenericArguments(genericArguments, index, numberOfGenericTypeArgs, sb, fullName); - } - if (fullName && i != totalParts - 1) - { - sb.Append("+"); - } - index += numberOfGenericTypeArgs; - } - else - { - if (fullName || i == totalParts - 1) - { - sb.Append(part); - } - if (fullName && i != totalParts - 1) - { - sb.Append("+"); - } - } - } - } - } -} diff --git a/shared/Microsoft.Extensions.WebEncoders.Sources/Properties/EncoderResources.cs b/shared/Microsoft.Extensions.WebEncoders.Sources/Properties/EncoderResources.cs deleted file mode 100644 index 74fcc625..00000000 --- a/shared/Microsoft.Extensions.WebEncoders.Sources/Properties/EncoderResources.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Globalization; - -namespace Microsoft.Extensions.WebEncoders.Sources -{ - // TODO using a resx file. project.json, unfortunately, fails to embed resx files when there are also compile items - // in the contentFiles section. Revisit once we convert repos to MSBuild - internal static class EncoderResources - { - /// - /// Invalid {0}, {1} or {2} length. - /// - internal static readonly string WebEncoders_InvalidCountOffsetOrLength = "Invalid {0}, {1} or {2} length."; - - /// - /// Invalid {0}, {1} or {2} length. - /// - internal static string FormatWebEncoders_InvalidCountOffsetOrLength(object p0, object p1, object p2) - { - return string.Format(CultureInfo.CurrentCulture, WebEncoders_InvalidCountOffsetOrLength, p0, p1, p2); - } - } -} diff --git a/shared/Microsoft.Extensions.WebEncoders.Sources/WebEncoders.cs b/shared/Microsoft.Extensions.WebEncoders.Sources/WebEncoders.cs deleted file mode 100644 index f7e8959f..00000000 --- a/shared/Microsoft.Extensions.WebEncoders.Sources/WebEncoders.cs +++ /dev/null @@ -1,384 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Globalization; -using Microsoft.Extensions.WebEncoders.Sources; - -#if WebEncoders_In_WebUtilities -namespace Microsoft.AspNetCore.WebUtilities -#else -namespace Microsoft.Extensions.Internal -#endif -{ - /// - /// Contains utility APIs to assist with common encoding and decoding operations. - /// -#if WebEncoders_In_WebUtilities - public -#else - internal -#endif - static class WebEncoders - { - private static readonly byte[] EmptyBytes = new byte[0]; - - /// - /// Decodes a base64url-encoded string. - /// - /// The base64url-encoded input to decode. - /// The base64url-decoded form of the input. - /// - /// The input must not contain any whitespace or padding characters. - /// Throws if the input is malformed. - /// - public static byte[] Base64UrlDecode(string input) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return Base64UrlDecode(input, offset: 0, count: input.Length); - } - - /// - /// Decodes a base64url-encoded substring of a given string. - /// - /// A string containing the base64url-encoded input to decode. - /// The position in at which decoding should begin. - /// The number of characters in to decode. - /// The base64url-decoded form of the input. - /// - /// The input must not contain any whitespace or padding characters. - /// Throws if the input is malformed. - /// - public static byte[] Base64UrlDecode(string input, int offset, int count) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - ValidateParameters(input.Length, nameof(input), offset, count); - - // Special-case empty input - if (count == 0) - { - return EmptyBytes; - } - - // Create array large enough for the Base64 characters, not just shorter Base64-URL-encoded form. - var buffer = new char[GetArraySizeRequiredToDecode(count)]; - - return Base64UrlDecode(input, offset, buffer, bufferOffset: 0, count: count); - } - - /// - /// Decodes a base64url-encoded into a byte[]. - /// - /// A string containing the base64url-encoded input to decode. - /// The position in at which decoding should begin. - /// - /// Scratch buffer to hold the s to decode. Array must be large enough to hold - /// and characters as well as Base64 padding - /// characters. Content is not preserved. - /// - /// - /// The offset into at which to begin writing the s to decode. - /// - /// The number of characters in to decode. - /// The base64url-decoded form of the . - /// - /// The input must not contain any whitespace or padding characters. - /// Throws if the input is malformed. - /// - public static byte[] Base64UrlDecode(string input, int offset, char[] buffer, int bufferOffset, int count) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - ValidateParameters(input.Length, nameof(input), offset, count); - if (bufferOffset < 0) - { - throw new ArgumentOutOfRangeException(nameof(bufferOffset)); - } - - if (count == 0) - { - return EmptyBytes; - } - - // Assumption: input is base64url encoded without padding and contains no whitespace. - - var paddingCharsToAdd = GetNumBase64PaddingCharsToAddForDecode(count); - var arraySizeRequired = checked(count + paddingCharsToAdd); - Debug.Assert(arraySizeRequired % 4 == 0, "Invariant: Array length must be a multiple of 4."); - - if (buffer.Length - bufferOffset < arraySizeRequired) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - EncoderResources.WebEncoders_InvalidCountOffsetOrLength, - nameof(count), - nameof(bufferOffset), - nameof(input)), - nameof(count)); - } - - // Copy input into buffer, fixing up '-' -> '+' and '_' -> '/'. - var i = bufferOffset; - for (var j = offset; i - bufferOffset < count; i++, j++) - { - var ch = input[j]; - if (ch == '-') - { - buffer[i] = '+'; - } - else if (ch == '_') - { - buffer[i] = '/'; - } - else - { - buffer[i] = ch; - } - } - - // Add the padding characters back. - for (; paddingCharsToAdd > 0; i++, paddingCharsToAdd--) - { - buffer[i] = '='; - } - - // Decode. - // If the caller provided invalid base64 chars, they'll be caught here. - return Convert.FromBase64CharArray(buffer, bufferOffset, arraySizeRequired); - } - - /// - /// Gets the minimum char[] size required for decoding of characters - /// with the method. - /// - /// The number of characters to decode. - /// - /// The minimum char[] size required for decoding of characters. - /// - public static int GetArraySizeRequiredToDecode(int count) - { - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - - if (count == 0) - { - return 0; - } - - var numPaddingCharsToAdd = GetNumBase64PaddingCharsToAddForDecode(count); - - return checked(count + numPaddingCharsToAdd); - } - - /// - /// Encodes using base64url encoding. - /// - /// The binary input to encode. - /// The base64url-encoded form of . - public static string Base64UrlEncode(byte[] input) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - return Base64UrlEncode(input, offset: 0, count: input.Length); - } - - /// - /// Encodes using base64url encoding. - /// - /// The binary input to encode. - /// The offset into at which to begin encoding. - /// The number of bytes from to encode. - /// The base64url-encoded form of . - public static string Base64UrlEncode(byte[] input, int offset, int count) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - - ValidateParameters(input.Length, nameof(input), offset, count); - - // Special-case empty input - if (count == 0) - { - return string.Empty; - } - - var buffer = new char[GetArraySizeRequiredToEncode(count)]; - var numBase64Chars = Base64UrlEncode(input, offset, buffer, outputOffset: 0, count: count); - - return new String(buffer, startIndex: 0, length: numBase64Chars); - } - - /// - /// Encodes using base64url encoding. - /// - /// The binary input to encode. - /// The offset into at which to begin encoding. - /// - /// Buffer to receive the base64url-encoded form of . Array must be large enough to - /// hold characters and the full base64-encoded form of - /// , including padding characters. - /// - /// - /// The offset into at which to begin writing the base64url-encoded form of - /// . - /// - /// The number of bytes from to encode. - /// - /// The number of characters written to , less any padding characters. - /// - public static int Base64UrlEncode(byte[] input, int offset, char[] output, int outputOffset, int count) - { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } - if (output == null) - { - throw new ArgumentNullException(nameof(output)); - } - - ValidateParameters(input.Length, nameof(input), offset, count); - if (outputOffset < 0) - { - throw new ArgumentOutOfRangeException(nameof(outputOffset)); - } - - var arraySizeRequired = GetArraySizeRequiredToEncode(count); - if (output.Length - outputOffset < arraySizeRequired) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - EncoderResources.WebEncoders_InvalidCountOffsetOrLength, - nameof(count), - nameof(outputOffset), - nameof(output)), - nameof(count)); - } - - // Special-case empty input. - if (count == 0) - { - return 0; - } - - // Use base64url encoding with no padding characters. See RFC 4648, Sec. 5. - - // Start with default Base64 encoding. - var numBase64Chars = Convert.ToBase64CharArray(input, offset, count, output, outputOffset); - - // Fix up '+' -> '-' and '/' -> '_'. Drop padding characters. - for (var i = outputOffset; i - outputOffset < numBase64Chars; i++) - { - var ch = output[i]; - if (ch == '+') - { - output[i] = '-'; - } - else if (ch == '/') - { - output[i] = '_'; - } - else if (ch == '=') - { - // We've reached a padding character; truncate the remainder. - return i - outputOffset; - } - } - - return numBase64Chars; - } - - /// - /// Get the minimum output char[] size required for encoding - /// s with the method. - /// - /// The number of characters to encode. - /// - /// The minimum output char[] size required for encoding s. - /// - public static int GetArraySizeRequiredToEncode(int count) - { - var numWholeOrPartialInputBlocks = checked(count + 2) / 3; - return checked(numWholeOrPartialInputBlocks * 4); - } - - private static int GetNumBase64PaddingCharsInString(string str) - { - // Assumption: input contains a well-formed base64 string with no whitespace. - - // base64 guaranteed have 0 - 2 padding characters. - if (str[str.Length - 1] == '=') - { - if (str[str.Length - 2] == '=') - { - return 2; - } - return 1; - } - return 0; - } - - private static int GetNumBase64PaddingCharsToAddForDecode(int inputLength) - { - switch (inputLength % 4) - { - case 0: - return 0; - case 2: - return 2; - case 3: - return 1; - default: - throw new FormatException("TODO: Malformed input."); - } - } - - private static void ValidateParameters(int bufferLength, string inputName, int offset, int count) - { - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - if (count < 0) - { - throw new ArgumentOutOfRangeException(nameof(count)); - } - if (bufferLength - offset < count) - { - throw new ArgumentException( - string.Format( - CultureInfo.CurrentCulture, - EncoderResources.WebEncoders_InvalidCountOffsetOrLength, - nameof(count), - nameof(offset), - inputName), - nameof(count)); - } - } - } -} diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandArgument.cs b/src/CommandLineUtils/CommandArgument.cs similarity index 89% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandArgument.cs rename to src/CommandLineUtils/CommandArgument.cs index 4eac9598..74fa6fdc 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandArgument.cs +++ b/src/CommandLineUtils/CommandArgument.cs @@ -4,9 +4,9 @@ using System.Collections.Generic; using System.Linq; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { - internal class CommandArgument + public class CommandArgument { public CommandArgument() { diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandLineApplication.cs b/src/CommandLineUtils/CommandLineApplication.cs similarity index 99% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandLineApplication.cs rename to src/CommandLineUtils/CommandLineApplication.cs index b7c62b5a..1f8be3fd 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandLineApplication.cs +++ b/src/CommandLineUtils/CommandLineApplication.cs @@ -9,9 +9,9 @@ using System.Text; using System.Threading.Tasks; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { - internal class CommandLineApplication + public class CommandLineApplication { // Indicates whether the parser should throw an exception when it runs into an unexpected argument. // If this field is set to false, the parser will stop parsing when it sees an unexpected argument, and all diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandOption.cs b/src/CommandLineUtils/CommandOption.cs similarity index 97% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandOption.cs rename to src/CommandLineUtils/CommandOption.cs index 4e663773..b5ddea43 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandOption.cs +++ b/src/CommandLineUtils/CommandOption.cs @@ -5,9 +5,9 @@ using System.Collections.Generic; using System.Linq; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { - internal class CommandOption + public class CommandOption { public CommandOption(string template, CommandOptionType optionType) { diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandOptionType.cs b/src/CommandLineUtils/CommandOptionType.cs similarity index 74% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandOptionType.cs rename to src/CommandLineUtils/CommandOptionType.cs index 76fdf38f..d8fe8268 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandOptionType.cs +++ b/src/CommandLineUtils/CommandOptionType.cs @@ -1,10 +1,9 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { - internal enum CommandOptionType + public enum CommandOptionType { MultipleValue, SingleValue, diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandParsingException.cs b/src/CommandLineUtils/CommandParsingException.cs similarity index 80% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandParsingException.cs rename to src/CommandLineUtils/CommandParsingException.cs index 2be62b87..37932208 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/CommandParsingException.cs +++ b/src/CommandLineUtils/CommandParsingException.cs @@ -3,9 +3,9 @@ using System; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { - internal class CommandParsingException : Exception + public class CommandParsingException : Exception { public CommandParsingException(CommandLineApplication command, string message) : base(message) diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/AnsiConsole.cs b/src/CommandLineUtils/Internal/AnsiConsole.cs similarity index 99% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/AnsiConsole.cs rename to src/CommandLineUtils/Internal/AnsiConsole.cs index 379235f2..7bea947e 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/CommandLine/AnsiConsole.cs +++ b/src/CommandLineUtils/Internal/AnsiConsole.cs @@ -4,7 +4,7 @@ using System; using System.IO; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { internal class AnsiConsole { diff --git a/src/CommandLineUtils/McMaster.Extensions.CommandLineUtils.csproj b/src/CommandLineUtils/McMaster.Extensions.CommandLineUtils.csproj new file mode 100644 index 00000000..5c9ddb89 --- /dev/null +++ b/src/CommandLineUtils/McMaster.Extensions.CommandLineUtils.csproj @@ -0,0 +1,16 @@ + + + + netstandard2.0 + true + Command-line parsing API. A drop-in replacement for Microsoft.Extensions.CommandLineUtils, plus extras. +Commonly used types: + +McMaster.Extensions.CommandLineUtils.CommandLineApplication +McMaster.Extensions.CommandLineUtils.CommandOption + + commandline;parsing + $(NoWarn);CS1591 + + + diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/Utilities/ArgumentEscaper.cs b/src/CommandLineUtils/Utilities/ArgumentEscaper.cs similarity index 94% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/Utilities/ArgumentEscaper.cs rename to src/CommandLineUtils/Utilities/ArgumentEscaper.cs index 7b696c51..45ce4a70 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/Utilities/ArgumentEscaper.cs +++ b/src/CommandLineUtils/Utilities/ArgumentEscaper.cs @@ -5,12 +5,12 @@ using System.Linq; using System.Text; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { /// /// A utility for escaping arguments for new processes. /// - internal static class ArgumentEscaper + public static class ArgumentEscaper { /// /// Undo the processing which took place to create string[] args in Main, so that the next process will @@ -19,8 +19,8 @@ internal static class ArgumentEscaper /// /// See https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/ /// - /// - /// + /// The arguments + /// A single string of escaped arguments public static string EscapeAndConcatenate(IEnumerable args) => string.Join(" ", args.Select(EscapeSingleArg)); diff --git a/shared/Microsoft.Extensions.CommandLineUtils.Sources/Utilities/DotNetMuxer.cs b/src/CommandLineUtils/Utilities/DotNetExe.cs similarity index 74% rename from shared/Microsoft.Extensions.CommandLineUtils.Sources/Utilities/DotNetMuxer.cs rename to src/CommandLineUtils/Utilities/DotNetExe.cs index ecfa0549..e12769b4 100644 --- a/shared/Microsoft.Extensions.CommandLineUtils.Sources/Utilities/DotNetMuxer.cs +++ b/src/CommandLineUtils/Utilities/DotNetExe.cs @@ -1,44 +1,42 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. -// System.AppContext.GetData is not available in these frameworks -#if !NET451 && !NET452 && !NET46 && !NET461 - using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils { /// - /// Utilities for finding the "dotnet.exe" file from the currently running .NET Core application + /// Utilities for finding the "dotnet.exe" file from the currently running .NET Core application. /// - internal static class DotNetMuxer + public static class DotNetExe { - private const string MuxerName = "dotnet"; + private const string FileName = "dotnet"; - static DotNetMuxer() + static DotNetExe() { - MuxerPath = TryFindMuxerPath(); + FullPath = TryFindDotNetExePath(); } /// - /// The full filepath to the .NET Core muxer. + /// The full filepath to the .NET Core CLI executable. /// - public static string MuxerPath { get; } + public static string FullPath { get; } /// - /// Finds the full filepath to the .NET Core muxer, + /// Finds the full filepath to the .NET Core CLI executable, /// or returns a string containing the default name of the .NET Core muxer ('dotnet'). /// /// The path or a string named 'dotnet' - public static string MuxerPathOrDefault() - => MuxerPath ?? MuxerName; + public static string FullPathOrDefault() + => FullPath ?? FileName; - private static string TryFindMuxerPath() + private static string TryFindDotNetExePath() { - var fileName = MuxerName; + var fileName = FileName; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { fileName += ".exe"; @@ -79,4 +77,3 @@ private static string TryFindMuxerPath() } } } -#endif diff --git a/src/Directory.Build.props b/src/Directory.Build.props deleted file mode 100644 index 5236edee..00000000 --- a/src/Directory.Build.props +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/src/Microsoft.Extensions.ObjectPool/DefaultObjectPool.cs b/src/Microsoft.Extensions.ObjectPool/DefaultObjectPool.cs deleted file mode 100644 index 951e4dad..00000000 --- a/src/Microsoft.Extensions.ObjectPool/DefaultObjectPool.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; - -namespace Microsoft.Extensions.ObjectPool -{ - public class DefaultObjectPool : ObjectPool where T : class - { - private readonly T[] _items; - private readonly IPooledObjectPolicy _policy; - - public DefaultObjectPool(IPooledObjectPolicy policy) - : this(policy, Environment.ProcessorCount * 2) - { - } - - public DefaultObjectPool(IPooledObjectPolicy policy, int maximumRetained) - { - if (policy == null) - { - throw new ArgumentNullException(nameof(policy)); - } - - _policy = policy; - _items = new T[maximumRetained]; - } - - public override T Get() - { - for (var i = 0; i < _items.Length; i++) - { - var item = _items[i]; - if (item != null && Interlocked.CompareExchange(ref _items[i], null, item) == item) - { - return item; - } - } - - return _policy.Create(); - } - - public override void Return(T obj) - { - if (!_policy.Return(obj)) - { - return; - } - - for (var i = 0; i < _items.Length; i++) - { - if (_items[i] == null) - { - _items[i] = obj; - return; - } - } - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/DefaultObjectPoolProvider.cs b/src/Microsoft.Extensions.ObjectPool/DefaultObjectPoolProvider.cs deleted file mode 100644 index fb3c4bfa..00000000 --- a/src/Microsoft.Extensions.ObjectPool/DefaultObjectPoolProvider.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.Extensions.ObjectPool -{ - public class DefaultObjectPoolProvider : ObjectPoolProvider - { - public int MaximumRetained { get; set; } = Environment.ProcessorCount * 2; - - public override ObjectPool Create(IPooledObjectPolicy policy) - { - return new DefaultObjectPool(policy, MaximumRetained); - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/DefaultPooledObjectPolicy.cs b/src/Microsoft.Extensions.ObjectPool/DefaultPooledObjectPolicy.cs deleted file mode 100644 index 2f206469..00000000 --- a/src/Microsoft.Extensions.ObjectPool/DefaultPooledObjectPolicy.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.Extensions.ObjectPool -{ - public class DefaultPooledObjectPolicy : IPooledObjectPolicy where T : class, new() - { - public T Create() - { - return new T(); - } - - public bool Return(T obj) - { - return true; - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/IPooledObjectPolicy.cs b/src/Microsoft.Extensions.ObjectPool/IPooledObjectPolicy.cs deleted file mode 100644 index 54611bad..00000000 --- a/src/Microsoft.Extensions.ObjectPool/IPooledObjectPolicy.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.Extensions.ObjectPool -{ - public interface IPooledObjectPolicy - { - T Create(); - - bool Return(T obj); - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/LeakTrackingObjectPool.cs b/src/Microsoft.Extensions.ObjectPool/LeakTrackingObjectPool.cs deleted file mode 100644 index 243d44d2..00000000 --- a/src/Microsoft.Extensions.ObjectPool/LeakTrackingObjectPool.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace Microsoft.Extensions.ObjectPool -{ - public class LeakTrackingObjectPool : ObjectPool where T : class - { - private readonly ConditionalWeakTable _trackers = new ConditionalWeakTable(); - private readonly ObjectPool _inner; - - public LeakTrackingObjectPool(ObjectPool inner) - { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } - - _inner = inner; - } - - public override T Get() - { - var value = _inner.Get(); - _trackers.Add(value, new Tracker()); - return value; - } - - public override void Return(T obj) - { - Tracker tracker; - if (_trackers.TryGetValue(obj, out tracker)) - { - _trackers.Remove(obj); - tracker.Dispose(); - } - - _inner.Return(obj); - } - - private class Tracker : IDisposable - { - private readonly string _stack; - private bool _disposed; - - public Tracker() - { - _stack = Environment.StackTrace; - } - - public void Dispose() - { - _disposed = true; - GC.SuppressFinalize(this); - } - - ~Tracker() - { - if (!_disposed && !Environment.HasShutdownStarted) - { - Debug.Fail($"{typeof(T).Name} was leaked. Created at: {Environment.NewLine}{_stack}"); - } - } - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/LeakTrackingObjectPoolProvider.cs b/src/Microsoft.Extensions.ObjectPool/LeakTrackingObjectPoolProvider.cs deleted file mode 100644 index 134eaf16..00000000 --- a/src/Microsoft.Extensions.ObjectPool/LeakTrackingObjectPoolProvider.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.Extensions.ObjectPool -{ - public class LeakTrackingObjectPoolProvider : ObjectPoolProvider - { - private readonly ObjectPoolProvider _inner; - - public LeakTrackingObjectPoolProvider(ObjectPoolProvider inner) - { - if (inner == null) - { - throw new ArgumentNullException(nameof(inner)); - } - - _inner = inner; - } - - public override ObjectPool Create(IPooledObjectPolicy policy) - { - var inner = _inner.Create(policy); - return new LeakTrackingObjectPool(inner); - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/Microsoft.Extensions.ObjectPool.csproj b/src/Microsoft.Extensions.ObjectPool/Microsoft.Extensions.ObjectPool.csproj deleted file mode 100755 index fd54d2bb..00000000 --- a/src/Microsoft.Extensions.ObjectPool/Microsoft.Extensions.ObjectPool.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - A simple object pool implementation. - netstandard2.0 - $(NoWarn);CS1591 - true - pooling - - - diff --git a/src/Microsoft.Extensions.ObjectPool/ObjectPool.cs b/src/Microsoft.Extensions.ObjectPool/ObjectPool.cs deleted file mode 100644 index 8cf52c91..00000000 --- a/src/Microsoft.Extensions.ObjectPool/ObjectPool.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.Extensions.ObjectPool -{ - public abstract class ObjectPool where T : class - { - public abstract T Get(); - - public abstract void Return(T obj); - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/ObjectPoolProvider.cs b/src/Microsoft.Extensions.ObjectPool/ObjectPoolProvider.cs deleted file mode 100644 index 909795dd..00000000 --- a/src/Microsoft.Extensions.ObjectPool/ObjectPoolProvider.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.Extensions.ObjectPool -{ - public abstract class ObjectPoolProvider - { - public ObjectPool Create() where T : class, new() - { - return Create(new DefaultPooledObjectPolicy()); - } - - public abstract ObjectPool Create(IPooledObjectPolicy policy) where T : class; - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/ObjectPoolProviderExtensions.cs b/src/Microsoft.Extensions.ObjectPool/ObjectPoolProviderExtensions.cs deleted file mode 100644 index b9e93598..00000000 --- a/src/Microsoft.Extensions.ObjectPool/ObjectPoolProviderExtensions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; - -namespace Microsoft.Extensions.ObjectPool -{ - public static class ObjectPoolProviderExtensions - { - public static ObjectPool CreateStringBuilderPool(this ObjectPoolProvider provider) - { - return provider.Create(new StringBuilderPooledObjectPolicy()); - } - - public static ObjectPool CreateStringBuilderPool( - this ObjectPoolProvider provider, - int initialCapacity, - int maximumRetainedCapacity) - { - var policy = new StringBuilderPooledObjectPolicy() - { - InitialCapacity = initialCapacity, - MaximumRetainedCapacity = maximumRetainedCapacity, - }; - - return provider.Create(policy); - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/StringBuilderPooledObjectPolicy.cs b/src/Microsoft.Extensions.ObjectPool/StringBuilderPooledObjectPolicy.cs deleted file mode 100644 index ae26ede2..00000000 --- a/src/Microsoft.Extensions.ObjectPool/StringBuilderPooledObjectPolicy.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; - -namespace Microsoft.Extensions.ObjectPool -{ - public class StringBuilderPooledObjectPolicy : IPooledObjectPolicy - { - public int InitialCapacity { get; set; } = 100; - - public int MaximumRetainedCapacity { get; set; } = 4 * 1024; - - public StringBuilder Create() - { - return new StringBuilder(InitialCapacity); - } - - public bool Return(StringBuilder obj) - { - if (obj.Capacity > MaximumRetainedCapacity) - { - // Too big. Discard this one. - return false; - } - - obj.Clear(); - return true; - } - } -} diff --git a/src/Microsoft.Extensions.ObjectPool/baseline.netcore.json b/src/Microsoft.Extensions.ObjectPool/baseline.netcore.json deleted file mode 100644 index b79a144c..00000000 --- a/src/Microsoft.Extensions.ObjectPool/baseline.netcore.json +++ /dev/null @@ -1,562 +0,0 @@ -{ - "AssemblyIdentity": "Microsoft.Extensions.ObjectPool, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", - "Types": [ - { - "Name": "Microsoft.Extensions.ObjectPool.DefaultObjectPool", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Get", - "Parameters": [], - "ReturnType": "T0", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "T0" - } - ], - "ReturnType": "System.Void", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "policy", - "Type": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - } - ], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "policy", - "Type": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - }, - { - "Name": "maximumRetained", - "Type": "System.Int32" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.DefaultObjectPoolProvider", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_MaximumRetained", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_MaximumRetained", - "Parameters": [ - { - "Name": "value", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Create", - "Parameters": [ - { - "Name": "policy", - "Type": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - } - ], - "ReturnType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.DefaultPooledObjectPolicy", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - ], - "Members": [ - { - "Kind": "Method", - "Name": "Create", - "Parameters": [], - "ReturnType": "T0", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "T0" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "New": true, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Create", - "Parameters": [], - "ReturnType": "T0", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "T0" - } - ], - "ReturnType": "System.Boolean", - "GenericParameter": [] - } - ], - "GenericParameters": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.LeakTrackingObjectPool", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Get", - "Parameters": [], - "ReturnType": "T0", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "T0" - } - ], - "ReturnType": "System.Void", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "inner", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPool" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.LeakTrackingObjectPoolProvider", - "Visibility": "Public", - "Kind": "Class", - "BaseType": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider", - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Create", - "Parameters": [ - { - "Name": "policy", - "Type": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - } - ], - "ReturnType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "inner", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Visibility": "Public", - "Kind": "Class", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Get", - "Parameters": [], - "ReturnType": "T0", - "Virtual": true, - "Abstract": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "T0" - } - ], - "ReturnType": "System.Void", - "Virtual": true, - "Abstract": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Protected", - "GenericParameter": [] - } - ], - "GenericParameters": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider", - "Visibility": "Public", - "Kind": "Class", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "Create", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Visibility": "Public", - "GenericParameter": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "New": true, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Kind": "Method", - "Name": "Create", - "Parameters": [ - { - "Name": "policy", - "Type": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - } - ], - "ReturnType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Virtual": true, - "Abstract": true, - "Visibility": "Public", - "GenericParameter": [ - { - "ParameterName": "T", - "ParameterPosition": 0, - "Class": true, - "BaseTypeOrInterfaces": [] - } - ] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Protected", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.ObjectPoolProviderExtensions", - "Visibility": "Public", - "Kind": "Class", - "Abstract": true, - "Static": true, - "Sealed": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "CreateStringBuilderPool", - "Parameters": [ - { - "Name": "provider", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider" - } - ], - "ReturnType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Static": true, - "Extension": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "CreateStringBuilderPool", - "Parameters": [ - { - "Name": "provider", - "Type": "Microsoft.Extensions.ObjectPool.ObjectPoolProvider" - }, - { - "Name": "initialCapacity", - "Type": "System.Int32" - }, - { - "Name": "maximumRetainedCapacity", - "Type": "System.Int32" - } - ], - "ReturnType": "Microsoft.Extensions.ObjectPool.ObjectPool", - "Static": true, - "Extension": true, - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.ObjectPool.StringBuilderPooledObjectPolicy", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_InitialCapacity", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_InitialCapacity", - "Parameters": [ - { - "Name": "value", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_MaximumRetainedCapacity", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "set_MaximumRetainedCapacity", - "Parameters": [ - { - "Name": "value", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Void", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Create", - "Parameters": [], - "ReturnType": "System.Text.StringBuilder", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Return", - "Parameters": [ - { - "Name": "obj", - "Type": "System.Text.StringBuilder" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.ObjectPool.IPooledObjectPolicy", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - } - ] -} \ No newline at end of file diff --git a/src/Microsoft.Extensions.Primitives/CancellationChangeToken.cs b/src/Microsoft.Extensions.Primitives/CancellationChangeToken.cs deleted file mode 100644 index 03949c28..00000000 --- a/src/Microsoft.Extensions.Primitives/CancellationChangeToken.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Threading; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// A implementation using . - /// - public class CancellationChangeToken : IChangeToken - { - /// - /// Initializes a new instance of . - /// - /// The . - public CancellationChangeToken(CancellationToken cancellationToken) - { - Token = cancellationToken; - } - - /// - public bool ActiveChangeCallbacks => true; - - /// - public bool HasChanged => Token.IsCancellationRequested; - - private CancellationToken Token { get; } - - /// - public IDisposable RegisterChangeCallback(Action callback, object state) => Token.Register(callback, state); - } -} \ No newline at end of file diff --git a/src/Microsoft.Extensions.Primitives/ChangeToken.cs b/src/Microsoft.Extensions.Primitives/ChangeToken.cs deleted file mode 100644 index ed722475..00000000 --- a/src/Microsoft.Extensions.Primitives/ChangeToken.cs +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// Propagates notifications that a change has occurred. - /// - public static class ChangeToken - { - /// - /// Registers the action to be called whenever the token produced changes. - /// - /// Produces the change token. - /// Action called when the token changes. - /// - public static IDisposable OnChange(Func changeTokenProducer, Action changeTokenConsumer) - { - if (changeTokenProducer == null) - { - throw new ArgumentNullException(nameof(changeTokenProducer)); - } - if (changeTokenConsumer == null) - { - throw new ArgumentNullException(nameof(changeTokenConsumer)); - } - - Action callback = null; - callback = (s) => - { - // The order here is important. We need to take the token and then apply our changes BEFORE - // registering. This prevents us from possible having two change updates to process concurrently. - // - // If the token changes after we take the token, then we'll process the update immediately upon - // registering the callback. - var t = changeTokenProducer(); - try - { - changeTokenConsumer(); - } - finally // We always want to ensure the callback is registered - { - t.RegisterChangeCallback(callback, null); - } - }; - - return changeTokenProducer().RegisterChangeCallback(callback, null); - } - - /// - /// Registers the action to be called whenever the token produced changes. - /// - /// Produces the change token. - /// Action called when the token changes. - /// state for the consumer. - /// - public static IDisposable OnChange(Func changeTokenProducer, Action changeTokenConsumer, TState state) - { - if (changeTokenProducer == null) - { - throw new ArgumentNullException(nameof(changeTokenProducer)); - } - if (changeTokenConsumer == null) - { - throw new ArgumentNullException(nameof(changeTokenConsumer)); - } - - Action callback = null; - callback = (s) => - { - // The order here is important. We need to take the token and then apply our changes BEFORE - // registering. This prevents us from possible having two change updates to process concurrently. - // - // If the token changes after we take the token, then we'll process the update immediately upon - // registering the callback. - var t = changeTokenProducer(); - try - { - changeTokenConsumer((TState)s); - } - finally // We always want to ensure the callback is registered - { - t.RegisterChangeCallback(callback, s); - } - }; - - return changeTokenProducer().RegisterChangeCallback(callback, state); - } - } -} \ No newline at end of file diff --git a/src/Microsoft.Extensions.Primitives/CompositeChangeToken.cs b/src/Microsoft.Extensions.Primitives/CompositeChangeToken.cs deleted file mode 100644 index 81f9623c..00000000 --- a/src/Microsoft.Extensions.Primitives/CompositeChangeToken.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// An which represents one or more instances. - /// - public class CompositeChangeToken : IChangeToken - { - private static readonly Action _onChangeDelegate = OnChange; - private readonly object _callbackLock = new object(); - private CancellationTokenSource _cancellationTokenSource; - private bool _registeredCallbackProxy; - private List _disposables; - - /// - /// Creates a new instance of . - /// - /// The list of to compose. - public CompositeChangeToken(IReadOnlyList changeTokens) - { - ChangeTokens = changeTokens ?? throw new ArgumentNullException(nameof(changeTokens)); - for (var i = 0; i < ChangeTokens.Count; i++) - { - if (ChangeTokens[i].ActiveChangeCallbacks) - { - ActiveChangeCallbacks = true; - break; - } - } - } - - /// - /// Returns the list of which compose the current . - /// - public IReadOnlyList ChangeTokens { get; } - - /// - public IDisposable RegisterChangeCallback(Action callback, object state) - { - EnsureCallbacksInitialized(); - return _cancellationTokenSource.Token.Register(callback, state); - } - - /// - public bool HasChanged - { - get - { - if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested) - { - return true; - } - - for (var i = 0; i < ChangeTokens.Count; i++) - { - if (ChangeTokens[i].HasChanged) - { - OnChange(this); - return true; - } - } - - return false; - } - } - - /// - public bool ActiveChangeCallbacks { get; } - - private void EnsureCallbacksInitialized() - { - if (_registeredCallbackProxy) - { - return; - } - - lock (_callbackLock) - { - if (_registeredCallbackProxy) - { - return; - } - - _cancellationTokenSource = new CancellationTokenSource(); - _disposables = new List(); - for (var i = 0; i < ChangeTokens.Count; i++) - { - if (ChangeTokens[i].ActiveChangeCallbacks) - { - var disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this); - _disposables.Add(disposable); - } - } - _registeredCallbackProxy = true; - } - } - - private static void OnChange(object state) - { - var compositeChangeTokenState = (CompositeChangeToken)state; - if (compositeChangeTokenState._cancellationTokenSource == null) - { - return; - } - - lock (compositeChangeTokenState._callbackLock) - { - try - { - compositeChangeTokenState._cancellationTokenSource.Cancel(); - } - catch - { - } - } - - var disposables = compositeChangeTokenState._disposables; - Debug.Assert(disposables != null); - for (var i = 0; i < disposables.Count; i++) - { - disposables[i].Dispose(); - } - - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/Extensions.cs b/src/Microsoft.Extensions.Primitives/Extensions.cs deleted file mode 100644 index 6bff6188..00000000 --- a/src/Microsoft.Extensions.Primitives/Extensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; - -namespace Microsoft.Extensions.Primitives -{ - public static class Extensions - { - /// - /// Add the given to the . - /// - /// The to add to. - /// The to add. - /// The original . - public static StringBuilder Append(this StringBuilder builder, StringSegment segment) - { - return builder.Append(segment.Buffer, segment.Offset, segment.Length); - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/IChangeToken.cs b/src/Microsoft.Extensions.Primitives/IChangeToken.cs deleted file mode 100644 index 357447fc..00000000 --- a/src/Microsoft.Extensions.Primitives/IChangeToken.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// Propagates notifications that a change has occurred. - /// - public interface IChangeToken - { - /// - /// Gets a value that indicates if a change has occurred. - /// - bool HasChanged { get; } - - /// - /// Indicates if this token will pro-actively raise callbacks. Callbacks are still guaranteed to fire, eventually. - /// - bool ActiveChangeCallbacks { get; } - - /// - /// Registers for a callback that will be invoked when the entry has changed. - /// MUST be set before the callback is invoked. - /// - /// The to invoke. - /// State to be passed into the callback. - /// An that is used to unregister the callback. - IDisposable RegisterChangeCallback(Action callback, object state); - } -} \ No newline at end of file diff --git a/src/Microsoft.Extensions.Primitives/InplaceStringBuilder.cs b/src/Microsoft.Extensions.Primitives/InplaceStringBuilder.cs deleted file mode 100644 index 90ca5e63..00000000 --- a/src/Microsoft.Extensions.Primitives/InplaceStringBuilder.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; -using System.Runtime.CompilerServices; - -namespace Microsoft.Extensions.Primitives -{ - [DebuggerDisplay("Value = {_value}")] - public struct InplaceStringBuilder - { - private int _capacity; - private int _offset; - private bool _writing; - private string _value; - - public InplaceStringBuilder(int capacity) : this() - { - _capacity = capacity; - } - - public int Capacity - { - get { return _capacity; } - set - { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } - if (_writing) - { - throw new InvalidOperationException("Cannot change capacity after write started."); - } - _capacity = value; - } - } - - public unsafe void Append(string s) - { - if (s == null) - { - throw new ArgumentNullException(nameof(s)); - } - - Append(s, 0, s.Length); - } - - public void Append(StringSegment segment) - { - Append(segment.Buffer, segment.Offset, segment.Length); - } - - public unsafe void Append(string s, int offset, int count) - { - if (s == null) - { - throw new ArgumentNullException(nameof(s)); - } - - if (offset < 0 || s.Length - offset < count) - { - throw new ArgumentOutOfRangeException(); - } - - EnsureCapacity(count); - fixed (char* destination = _value) - fixed (char* source = s) - { - Unsafe.CopyBlockUnaligned(destination + _offset, source + offset, (uint)count * 2); - _offset += count; - } - } - - public unsafe void Append(char c) - { - EnsureCapacity(1); - fixed (char* destination = _value) - { - destination[_offset++] = c; - } - } - - private void EnsureCapacity(int length) - { - if (_value == null) - { - _writing = true; - _value = new string('\0', _capacity); - } - if (_offset + length > _capacity) - { - throw new InvalidOperationException($"Not enough capacity to write '{length}' characters, only '{_capacity - _offset}' left."); - } - } - - public override string ToString() - { - if (_offset != _capacity) - { - throw new InvalidOperationException($"Entire reserved capacity was not used. Capacity: '{_capacity}', written '{_offset}'."); - } - return _value; - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/Microsoft.Extensions.Primitives.csproj b/src/Microsoft.Extensions.Primitives/Microsoft.Extensions.Primitives.csproj deleted file mode 100755 index 0754b2a4..00000000 --- a/src/Microsoft.Extensions.Primitives/Microsoft.Extensions.Primitives.csproj +++ /dev/null @@ -1,23 +0,0 @@ - - - - Primitives shared by framework extensions. Commonly used types include: -Microsoft.Extensions.Primitives.IChangeToken -Microsoft.Extensions.Primitives.StringValues -Microsoft.Extensions.Primitives.StringSegment - netstandard2.0 - $(NoWarn);CS1591 - true - true - primitives - - - - - - - - - - - diff --git a/src/Microsoft.Extensions.Primitives/Resources.Designer.cs b/src/Microsoft.Extensions.Primitives/Resources.Designer.cs deleted file mode 100644 index 74291023..00000000 --- a/src/Microsoft.Extensions.Primitives/Resources.Designer.cs +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.Extensions.Primitives { - using System; - using System.Reflection; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Extensions.Primitives.Resources", typeof(Resources).GetTypeInfo().Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Offset and length are out of bounds for the string or length is greater than the number of characters from index to the end of the string.. - /// - internal static string Argument_InvalidOffsetLength { - get { - return ResourceManager.GetString("Argument_InvalidOffsetLength", resourceCulture); - } - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/Resources.resx b/src/Microsoft.Extensions.Primitives/Resources.resx deleted file mode 100644 index 2a1968d2..00000000 --- a/src/Microsoft.Extensions.Primitives/Resources.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Offset and length are out of bounds for the string or length is greater than the number of characters from index to the end of the string. - - \ No newline at end of file diff --git a/src/Microsoft.Extensions.Primitives/StringSegment.cs b/src/Microsoft.Extensions.Primitives/StringSegment.cs deleted file mode 100644 index 9518875f..00000000 --- a/src/Microsoft.Extensions.Primitives/StringSegment.cs +++ /dev/null @@ -1,613 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.CompilerServices; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// An optimized representation of a substring. - /// - public struct StringSegment : IEquatable, IEquatable - { - /// - /// A for . - /// - public static readonly StringSegment Empty = string.Empty; - - /// - /// Initializes an instance of the struct. - /// - /// - /// The original . The includes the whole . - /// - public StringSegment(string buffer) - { - Buffer = buffer; - Offset = 0; - Length = buffer?.Length ?? 0; - } - - /// - /// Initializes an instance of the struct. - /// - /// The original used as buffer. - /// The offset of the segment within the . - /// The length of the segment. - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public StringSegment(string buffer, int offset, int length) - { - // Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path - // Negative values discovered though conversion to high values when converted to unsigned - // Failure should be rare and location determination and message is delegated to failure functions - if (buffer == null || (uint)offset > (uint)buffer.Length || (uint)length > (uint)(buffer.Length - offset)) - { - ThrowInvalidArguments(buffer, offset, length); - } - - Buffer = buffer; - Offset = offset; - Length = length; - } - - private static void ThrowInvalidArguments(string buffer, int offset, int length) - { - // Only have single throw in method so is marked as "does not return" and isn't inlined to caller - throw GetInvalidArgumentException(buffer, offset, length); - } - - private static Exception GetInvalidArgumentException(string buffer, int offset, int length) - { - if (buffer == null) - { - return ThrowHelper.GetArgumentNullException(ExceptionArgument.buffer); - } - - if (offset < 0) - { - return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.offset); - } - - if (length < 0) - { - return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length); - } - - return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLength); - } - - /// - /// Gets the buffer for this . - /// - public string Buffer { get; } - - /// - /// Gets the offset within the buffer for this . - /// - public int Offset { get; } - - /// - /// Gets the length of this . - /// - public int Length { get; } - - /// - /// Gets the value of this segment as a . - /// - public string Value - { - get - { - if (!HasValue) - { - return null; - } - else - { - return Buffer.Substring(Offset, Length); - } - } - } - - /// - /// Gets whether or not this contains a valid value. - /// - public bool HasValue - { - get { return Buffer != null; } - } - - /// - /// Gets the at a specified position in the current . - /// - /// The offset into the - /// The at a specified position. - public char this[int index] - { - get - { - if (index < 0 || (uint)index >= (uint)Length) - { - throw new IndexOutOfRangeException(); - } - - return Buffer[Offset + index]; - } - } - - /// - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) - { - return false; - } - - return obj is StringSegment && Equals((StringSegment)obj); - } - - /// - /// Indicates whether the current object is equal to another object of the same type. - /// - /// An object to compare with this object. - /// true if the current object is equal to the other parameter; otherwise, false. - public bool Equals(StringSegment other) - { - return Equals(other, StringComparison.Ordinal); - } - - - /// - /// Indicates whether the current object is equal to another object of the same type. - /// - /// An object to compare with this object. - /// One of the enumeration values that specifies the rules to use in the comparison. - /// true if the current object is equal to the other parameter; otherwise, false. - public bool Equals(StringSegment other, StringComparison comparisonType) - { - int textLength = other.Length; - if (Length != textLength) - { - return false; - } - - return string.Compare(Buffer, Offset, other.Buffer, other.Offset, textLength, comparisonType) == 0; - } - - // This handles StringSegment.Equals(string, StringSegment, StringComparison) and StringSegment.Equals(StringSegment, string, StringComparison) - // via the implicit type converter - /// - /// Determines whether two specified StringSegment objects have the same value. A parameter specifies the culture, case, and - /// sort rules used in the comparison. - /// - /// The first StringSegment to compare. - /// The second StringSegment to compare. - /// One of the enumeration values that specifies the rules for the comparison. - /// true if the objects are equal; otherwise, false. - public static bool Equals(StringSegment a, StringSegment b, StringComparison comparisonType) - { - return a.Equals(b, comparisonType); - } - - /// - /// Checks if the specified is equal to the current . - /// - /// The to compare with the current . - /// true if the specified is equal to the current ; otherwise, false. - public bool Equals(string text) - { - return Equals(text, StringComparison.Ordinal); - } - - /// - /// Checks if the specified is equal to the current . - /// - /// The to compare with the current . - /// One of the enumeration values that specifies the rules to use in the comparison. - /// true if the specified is equal to the current ; otherwise, false. - public bool Equals(string text, StringComparison comparisonType) - { - if (text == null) - { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); - } - - int textLength = text.Length; - if (!HasValue || Length != textLength) - { - return false; - } - - return string.Compare(Buffer, Offset, text, 0, textLength, comparisonType) == 0; - } - - /// - /// - /// This GetHashCode is expensive since it allocates on every call. - /// However this is required to ensure we retain any behavior (such as hash code randomization) that - /// string.GetHashCode has. - /// - public override int GetHashCode() - { - if (!HasValue) - { - return 0; - } - else - { - // TODO: PERF; Note that .NET Core strings use randomized hash codes for security reasons. - return Value.GetHashCode(); - } - } - - /// - /// Checks if two specified have the same value. - /// - /// The first to compare, or null. - /// The second to compare, or null. - /// true if the value of is the same as the value of ; otherwise, false. - public static bool operator ==(StringSegment left, StringSegment right) - { - return left.Equals(right); - } - - /// - /// Checks if two specified have different values. - /// - /// The first to compare, or null. - /// The second to compare, or null. - /// true if the value of is different from the value of ; otherwise, false. - public static bool operator !=(StringSegment left, StringSegment right) - { - return !left.Equals(right); - } - - // PERF: Do NOT add a implicit converter from StringSegment to String. That would negate most of the perf safety. - /// - /// Creates a new from the given . - /// - /// The to convert to a - public static implicit operator StringSegment(string value) - { - return new StringSegment(value); - } - - /// - /// Checks if the beginning of this matches the specified when compared using the specified . - /// - /// The to compare. - /// One of the enumeration values that specifies the rules to use in the comparison. - /// true if matches the beginning of this ; otherwise, false. - public bool StartsWith(string text, StringComparison comparisonType) - { - if (text == null) - { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); - } - - var textLength = text.Length; - if (!HasValue || Length < textLength) - { - return false; - } - - return string.Compare(Buffer, Offset, text, 0, textLength, comparisonType) == 0; - } - - /// - /// Checks if the end of this matches the specified when compared using the specified . - /// - /// The to compare. - /// One of the enumeration values that specifies the rules to use in the comparison. - /// true if matches the end of this ; otherwise, false. - public bool EndsWith(string text, StringComparison comparisonType) - { - if (text == null) - { - ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); - } - - var textLength = text.Length; - if (!HasValue || Length < textLength) - { - return false; - } - - return string.Compare(Buffer, Offset + Length - textLength, text, 0, textLength, comparisonType) == 0; - } - - /// - /// Retrieves a substring from this . - /// The substring starts at the position specified by and has the remaining length. - /// - /// The zero-based starting character position of a substring in this . - /// A that is equivalent to the substring of remaining length that begins at - /// in this - public string Substring(int offset) - { - return Substring(offset, Length - offset); - } - - /// - /// Retrieves a substring from this . - /// The substring starts at the position specified by and has the specified . - /// - /// The zero-based starting character position of a substring in this . - /// The number of characters in the substring. - /// A that is equivalent to the substring of length that begins at - /// in this - public string Substring(int offset, int length) - { - if (!HasValue) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); - } - - if (offset < 0 || offset + length > Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); - } - - if (length < 0 || Offset + offset + length > Buffer.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); - } - - return Buffer.Substring(Offset + offset, length); - } - - /// - /// Retrieves a that represents a substring from this . - /// The starts at the position specified by . - /// - /// The zero-based starting character position of a substring in this . - /// A that begins at in this - /// whose length is the remainder. - public StringSegment Subsegment(int offset) - { - return Subsegment(offset, Length - offset); - } - - /// - /// Retrieves a that represents a substring from this . - /// The starts at the position specified by and has the specified . - /// - /// The zero-based starting character position of a substring in this . - /// The number of characters in the substring. - /// A that is equivalent to the substring of length that begins at in this - public StringSegment Subsegment(int offset, int length) - { - if (!HasValue) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); - } - - if (offset < 0 || offset + length > Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset); - } - - if (length < 0 || Offset + offset + length > Buffer.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); - } - - return new StringSegment(Buffer, Offset + offset, length); - } - - /// - /// Gets the zero-based index of the first occurrence of the character in this . - /// The search starts at and examines a specified number of character positions. - /// - /// The Unicode character to seek. - /// The zero-based index position at which the search starts. - /// The number of characters to examine. - /// The zero-based index position of from the beginning of the if that character is found, or -1 if it is not. - public int IndexOf(char c, int start, int count) - { - if (start < 0 || Offset + start > Buffer.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); - } - - if (count < 0 || Offset + start + count > Buffer.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); - } - var index = Buffer.IndexOf(c, start + Offset, count); - if (index != -1) - { - return index - Offset; - } - else - { - return index; - } - } - - /// - /// Gets the zero-based index of the first occurrence of the character in this . - /// The search starts at . - /// - /// The Unicode character to seek. - /// The zero-based index position at which the search starts. - /// The zero-based index position of from the beginning of the if that character is found, or -1 if it is not. - public int IndexOf(char c, int start) - { - return IndexOf(c, start, Length - start); - } - - /// - /// Gets the zero-based index of the first occurrence of the character in this . - /// - /// The Unicode character to seek. - /// The zero-based index position of from the beginning of the if that character is found, or -1 if it is not. - public int IndexOf(char c) - { - return IndexOf(c, 0, Length); - } - - /// - /// Reports the zero-based index of the first occurrence in this instance of any character in a specified array - /// of Unicode characters. The search starts at a specified character position and examines a specified number - /// of character positions. - /// - /// A Unicode character array containing one or more characters to seek. - /// The search starting position. - /// The number of character positions to examine. - /// The zero-based index position of the first occurrence in this instance where any character in anyOf - /// was found; -1 if no character in anyOf was found. - public int IndexOfAny(char[] anyOf, int startIndex, int count) - { - if (!HasValue) - { - return -1; - } - - if (startIndex < 0 || Offset + startIndex > Buffer.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); - } - - if (count < 0 || Offset + startIndex + count > Buffer.Length) - { - ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count); - } - - var index = Buffer.IndexOfAny(anyOf, Offset + startIndex, count); - if (index == -1) - { - return index; - } - - return index - Offset; - } - - /// - /// Reports the zero-based index of the first occurrence in this instance of any character in a specified array - /// of Unicode characters. The search starts at a specified character position. - /// - /// A Unicode character array containing one or more characters to seek. - /// The search starting position. - /// The zero-based index position of the first occurrence in this instance where any character in anyOf - /// was found; -1 if no character in anyOf was found. - public int IndexOfAny(char[] anyOf, int startIndex) - { - return IndexOfAny(anyOf, startIndex, Length - startIndex); - } - - /// - /// Reports the zero-based index of the first occurrence in this instance of any character in a specified array - /// of Unicode characters. - /// - /// A Unicode character array containing one or more characters to seek. - /// The zero-based index position of the first occurrence in this instance where any character in anyOf - /// was found; -1 if no character in anyOf was found. - public int IndexOfAny(char[] anyOf) - { - return IndexOfAny(anyOf, 0, Length); - } - - /// - /// Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. - /// - /// The Unicode character to seek. - /// The zero-based index position of value if that character is found, or -1 if it is not. - public int LastIndexOf(char value) - { - if (!HasValue) - { - return -1; - } - - var index = Buffer.LastIndexOf(value, Offset + Length - 1, Length); - if (index == -1) - { - return -1; - } - - return index - Offset; - } - - /// - /// Removes all leading and trailing whitespaces. - /// - /// The trimmed . - public StringSegment Trim() - { - return TrimStart().TrimEnd(); - } - - /// - /// Removes all leading whitespaces. - /// - /// The trimmed . - public StringSegment TrimStart() - { - var trimmedStart = Offset; - while (trimmedStart < Offset + Length) - { - if (!char.IsWhiteSpace(Buffer, trimmedStart)) - { - break; - } - - trimmedStart++; - } - - return new StringSegment(Buffer, trimmedStart, Offset + Length - trimmedStart); - } - - /// - /// Removes all trailing whitespaces. - /// - /// The trimmed . - public StringSegment TrimEnd() - { - var trimmedEnd = Offset + Length - 1; - while (trimmedEnd >= Offset) - { - if (!char.IsWhiteSpace(Buffer, trimmedEnd)) - { - break; - } - - trimmedEnd--; - } - - return new StringSegment(Buffer, Offset, trimmedEnd - Offset + 1); - } - - /// - /// Splits a string into StringSegments that are based on the characters in an array. - /// - /// A character array that delimits the substrings in this string, an empty array that - /// contains no delimiters, or null. - /// An whose elements contain the StringSegmeents from this instance - /// that are delimited by one or more characters in separator. - public StringTokenizer Split(char[] chars) - { - return new StringTokenizer(this, chars); - } - - /// - /// Indicates whether the specified StringSegment is null or an Empty string. - /// - /// The StringSegment to test. - /// - public static bool IsNullOrEmpty(StringSegment value) - { - return !value.HasValue || value.Length == 0; - } - - /// - /// Returns the represented by this or String.Empty if the does not contain a value. - /// - /// The represented by this or String.Empty if the does not contain a value. - public override string ToString() - { - return Value ?? string.Empty; - } - } -} \ No newline at end of file diff --git a/src/Microsoft.Extensions.Primitives/StringSegmentComparer.cs b/src/Microsoft.Extensions.Primitives/StringSegmentComparer.cs deleted file mode 100644 index 1adca685..00000000 --- a/src/Microsoft.Extensions.Primitives/StringSegmentComparer.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; - -namespace Microsoft.Extensions.Primitives -{ - public class StringSegmentComparer : IEqualityComparer - { - public static StringSegmentComparer Ordinal { get; } - = new StringSegmentComparer(StringComparison.Ordinal, StringComparer.Ordinal); - public static StringSegmentComparer OrdinalIgnoreCase { get; } - = new StringSegmentComparer(StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase); - - private StringSegmentComparer(StringComparison comparison, StringComparer comparer) - { - Comparison = comparison; - Comparer = comparer; - } - - private StringComparison Comparison { get; } - private StringComparer Comparer { get; } - - public bool Equals(StringSegment x, StringSegment y) - { - return StringSegment.Equals(x, y, Comparison); - } - - public int GetHashCode(StringSegment obj) - { - // TODO: PERF; Note that .NET Core strings use randomized hash codes for security reasons. - return Comparer.GetHashCode(obj.Value); - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/StringTokenizer.cs b/src/Microsoft.Extensions.Primitives/StringTokenizer.cs deleted file mode 100644 index 1d443305..00000000 --- a/src/Microsoft.Extensions.Primitives/StringTokenizer.cs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// Tokenizes a string into s. - /// - public struct StringTokenizer : IEnumerable - { - private readonly StringSegment _value; - private readonly char[] _separators; - - /// - /// Initializes a new instance of . - /// - /// The string to tokenize. - /// The characters to tokenize by. - public StringTokenizer(string value, char[] separators) : this((StringSegment)value, separators) - { - } - - /// - /// Initializes a new instance of . - /// - /// The StringSegment to tokenize. - /// The characters to tokenize by. - public StringTokenizer(StringSegment value, char[] separators) - { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (separators == null) - { - throw new ArgumentNullException(nameof(separators)); - } - - _value = value; - _separators = separators; - } - - public Enumerator GetEnumerator() => new Enumerator(ref this); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - - public struct Enumerator : IEnumerator - { - private readonly StringSegment _value; - private readonly char[] _separators; - private int _index; - - public Enumerator(ref StringTokenizer tokenizer) - { - _value = tokenizer._value; - _separators = tokenizer._separators; - Current = default(StringSegment); - _index = 0; - } - - public StringSegment Current { get; private set; } - - object IEnumerator.Current => Current; - - public void Dispose() - { - } - - public bool MoveNext() - { - if (_value == null || _index > _value.Length) - { - Current = default(StringSegment); - return false; - } - - var next = _value.IndexOfAny(_separators, _index); - if (next == -1) - { - // No separator found. Consume the remainder of the string. - next = _value.Length; - } - - Current = _value.Subsegment(_index, next - _index); - _index = next + 1; - - return true; - } - - public void Reset() - { - Current = default(StringSegment); - _index = 0; - } - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/StringValues.cs b/src/Microsoft.Extensions.Primitives/StringValues.cs deleted file mode 100644 index 28ac00b0..00000000 --- a/src/Microsoft.Extensions.Primitives/StringValues.cs +++ /dev/null @@ -1,472 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using Microsoft.Extensions.Internal; - -namespace Microsoft.Extensions.Primitives -{ - /// - /// Represents zero/null, one, or many strings in an efficient way. - /// - public struct StringValues : IList, IReadOnlyList, IEquatable, IEquatable, IEquatable - { - private static readonly string[] EmptyArray = new string[0]; - public static readonly StringValues Empty = new StringValues(EmptyArray); - - private readonly string _value; - private readonly string[] _values; - - public StringValues(string value) - { - _value = value; - _values = null; - } - - public StringValues(string[] values) - { - _value = null; - _values = values; - } - - public static implicit operator StringValues(string value) - { - return new StringValues(value); - } - - public static implicit operator StringValues(string[] values) - { - return new StringValues(values); - } - - public static implicit operator string (StringValues values) - { - return values.GetStringValue(); - } - - public static implicit operator string[] (StringValues value) - { - return value.GetArrayValue(); - } - - public int Count => _value != null ? 1 : (_values?.Length ?? 0); - - bool ICollection.IsReadOnly - { - get { return true; } - } - - string IList.this[int index] - { - get { return this[index]; } - set { throw new NotSupportedException(); } - } - - public string this[int index] - { - get - { - if (_values != null) - { - return _values[index]; // may throw - } - if (index == 0 && _value != null) - { - return _value; - } - return EmptyArray[0]; // throws - } - } - - public override string ToString() - { - return GetStringValue() ?? string.Empty; - } - - private string GetStringValue() - { - if (_values == null) - { - return _value; - } - switch (_values.Length) - { - case 0: return null; - case 1: return _values[0]; - default: return string.Join(",", _values); - } - } - - public string[] ToArray() - { - return GetArrayValue() ?? EmptyArray; - } - - private string[] GetArrayValue() - { - if (_value != null) - { - return new[] { _value }; - } - return _values; - } - - int IList.IndexOf(string item) - { - return IndexOf(item); - } - - private int IndexOf(string item) - { - if (_values != null) - { - var values = _values; - for (int i = 0; i < values.Length; i++) - { - if (string.Equals(values[i], item, StringComparison.Ordinal)) - { - return i; - } - } - return -1; - } - - if (_value != null) - { - return string.Equals(_value, item, StringComparison.Ordinal) ? 0 : -1; - } - - return -1; - } - - bool ICollection.Contains(string item) - { - return IndexOf(item) >= 0; - } - - void ICollection.CopyTo(string[] array, int arrayIndex) - { - CopyTo(array, arrayIndex); - } - - private void CopyTo(string[] array, int arrayIndex) - { - if (_values != null) - { - Array.Copy(_values, 0, array, arrayIndex, _values.Length); - return; - } - - if (_value != null) - { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - if (arrayIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - } - if (array.Length - arrayIndex < 1) - { - throw new ArgumentException( - $"'{nameof(array)}' is not long enough to copy all the items in the collection. Check '{nameof(arrayIndex)}' and '{nameof(array)}' length."); - } - - array[arrayIndex] = _value; - } - } - - void ICollection.Add(string item) - { - throw new NotSupportedException(); - } - - void IList.Insert(int index, string item) - { - throw new NotSupportedException(); - } - - bool ICollection.Remove(string item) - { - throw new NotSupportedException(); - } - - void IList.RemoveAt(int index) - { - throw new NotSupportedException(); - } - - void ICollection.Clear() - { - throw new NotSupportedException(); - } - - public Enumerator GetEnumerator() - { - return new Enumerator(ref this); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public static bool IsNullOrEmpty(StringValues value) - { - if (value._values == null) - { - return string.IsNullOrEmpty(value._value); - } - switch (value._values.Length) - { - case 0: return true; - case 1: return string.IsNullOrEmpty(value._values[0]); - default: return false; - } - } - - public static StringValues Concat(StringValues values1, StringValues values2) - { - var count1 = values1.Count; - var count2 = values2.Count; - - if (count1 == 0) - { - return values2; - } - - if (count2 == 0) - { - return values1; - } - - var combined = new string[count1 + count2]; - values1.CopyTo(combined, 0); - values2.CopyTo(combined, count1); - return new StringValues(combined); - } - - public static bool Equals(StringValues left, StringValues right) - { - var count = left.Count; - - if (count != right.Count) - { - return false; - } - - for (var i = 0; i < count; i++) - { - if (left[i] != right[i]) - { - return false; - } - } - - return true; - } - - public static bool operator ==(StringValues left, StringValues right) - { - return Equals(left, right); - } - - public static bool operator !=(StringValues left, StringValues right) - { - return !Equals(left, right); - } - - public bool Equals(StringValues other) - { - return Equals(this, other); - } - - public static bool Equals(string left, StringValues right) - { - return Equals(new StringValues(left), right); - } - - public static bool Equals(StringValues left, string right) - { - return Equals(left, new StringValues(right)); - } - - public bool Equals(string other) - { - return Equals(this, new StringValues(other)); - } - - public static bool Equals(string[] left, StringValues right) - { - return Equals(new StringValues(left), right); - } - - public static bool Equals(StringValues left, string[] right) - { - return Equals(left, new StringValues(right)); - } - - public bool Equals(string[] other) - { - return Equals(this, new StringValues(other)); - } - - public static bool operator ==(StringValues left, string right) - { - return Equals(left, new StringValues(right)); - } - - public static bool operator !=(StringValues left, string right) - { - return !Equals(left, new StringValues(right)); - } - - public static bool operator ==(string left, StringValues right) - { - return Equals(new StringValues(left), right); - } - - public static bool operator !=(string left, StringValues right) - { - return !Equals(new StringValues(left), right); - } - - public static bool operator ==(StringValues left, string[] right) - { - return Equals(left, new StringValues(right)); - } - - public static bool operator !=(StringValues left, string[] right) - { - return !Equals(left, new StringValues(right)); - } - - public static bool operator ==(string[] left, StringValues right) - { - return Equals(new StringValues(left), right); - } - - public static bool operator !=(string[] left, StringValues right) - { - return !Equals(new StringValues(left), right); - } - - public static bool operator ==(StringValues left, object right) - { - return left.Equals(right); - } - - public static bool operator !=(StringValues left, object right) - { - return !left.Equals(right); - } - public static bool operator ==(object left, StringValues right) - { - return right.Equals(left); - } - - public static bool operator !=(object left, StringValues right) - { - return !right.Equals(left); - } - - public override bool Equals(object obj) - { - if (obj == null) - { - return Equals(this, StringValues.Empty); - } - - if (obj is string) - { - return Equals(this, (string)obj); - } - - if (obj is string[]) - { - return Equals(this, (string[])obj); - } - - if (obj is StringValues) - { - return Equals(this, (StringValues)obj); - } - - return false; - } - - public override int GetHashCode() - { - if (_values == null) - { - return _value == null ? 0 : _value.GetHashCode(); - } - - var hcc = new HashCodeCombiner(); - for (var i = 0; i < _values.Length; i++) - { - hcc.Add(_values[i]); - } - return hcc.CombinedHash; - } - - public struct Enumerator : IEnumerator - { - private readonly string[] _values; - private string _current; - private int _index; - - public Enumerator(ref StringValues values) - { - _values = values._values; - _current = values._value; - _index = 0; - } - - public bool MoveNext() - { - if (_index < 0) - { - return false; - } - - if (_values != null) - { - if (_index < _values.Length) - { - _current = _values[_index]; - _index++; - return true; - } - - _index = -1; - return false; - } - - _index = -1; // sentinel value - return _current != null; - } - - public string Current => _current; - - object IEnumerator.Current => _current; - - void IEnumerator.Reset() - { - throw new NotSupportedException(); - } - - public void Dispose() - { - } - } - } -} diff --git a/src/Microsoft.Extensions.Primitives/ThrowHelper.cs b/src/Microsoft.Extensions.Primitives/ThrowHelper.cs deleted file mode 100644 index 290fea3d..00000000 --- a/src/Microsoft.Extensions.Primitives/ThrowHelper.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Diagnostics; - -namespace Microsoft.Extensions.Primitives -{ - internal static class ThrowHelper - { - internal static void ThrowArgumentNullException(ExceptionArgument argument) - { - throw new ArgumentNullException(GetArgumentName(argument)); - } - - internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) - { - throw new ArgumentOutOfRangeException(GetArgumentName(argument)); - } - - internal static void ThrowArgumentException(ExceptionResource resource) - { - throw new ArgumentException(GetResourceText(resource)); - } - - internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) - { - return new ArgumentNullException(GetArgumentName(argument)); - } - - internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument) - { - return new ArgumentOutOfRangeException(GetArgumentName(argument)); - } - - internal static ArgumentException GetArgumentException(ExceptionResource resource) - { - return new ArgumentException(GetResourceText(resource)); - } - - private static string GetResourceText(ExceptionResource resource) - { - return Resources.ResourceManager.GetString(GetResourceName(resource), Resources.Culture); - } - - private static string GetArgumentName(ExceptionArgument argument) - { - Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument), - "The enum value is not defined, please check the ExceptionArgument Enum."); - - return argument.ToString(); - } - - private static string GetResourceName(ExceptionResource resource) - { - Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource), - "The enum value is not defined, please check the ExceptionResource Enum."); - - return resource.ToString(); - } - } - - internal enum ExceptionArgument - { - buffer, - offset, - length, - text, - start, - count - } - - internal enum ExceptionResource - { - Argument_InvalidOffsetLength - } -} diff --git a/src/Microsoft.Extensions.Primitives/baseline.netcore.json b/src/Microsoft.Extensions.Primitives/baseline.netcore.json deleted file mode 100644 index 264d1c9b..00000000 --- a/src/Microsoft.Extensions.Primitives/baseline.netcore.json +++ /dev/null @@ -1,1291 +0,0 @@ -{ - "AssemblyIdentity": "Microsoft.Extensions.Primitives, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60", - "Types": [ - { - "Name": "Microsoft.Extensions.Primitives.CancellationChangeToken", - "Visibility": "Public", - "Kind": "Class", - "ImplementedInterfaces": [ - "Microsoft.Extensions.Primitives.IChangeToken" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_ActiveChangeCallbacks", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.Primitives.IChangeToken", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HasChanged", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.Primitives.IChangeToken", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "RegisterChangeCallback", - "Parameters": [ - { - "Name": "callback", - "Type": "System.Action" - }, - { - "Name": "state", - "Type": "System.Object" - } - ], - "ReturnType": "System.IDisposable", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "Microsoft.Extensions.Primitives.IChangeToken", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "cancellationToken", - "Type": "System.Threading.CancellationToken" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.ChangeToken", - "Visibility": "Public", - "Kind": "Class", - "Abstract": true, - "Static": true, - "Sealed": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "OnChange", - "Parameters": [ - { - "Name": "changeTokenProducer", - "Type": "System.Func" - }, - { - "Name": "changeTokenConsumer", - "Type": "System.Action" - } - ], - "ReturnType": "System.IDisposable", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "OnChange", - "Parameters": [ - { - "Name": "changeTokenProducer", - "Type": "System.Func" - }, - { - "Name": "changeTokenConsumer", - "Type": "System.Action" - }, - { - "Name": "state", - "Type": "T0" - } - ], - "ReturnType": "System.IDisposable", - "Static": true, - "Visibility": "Public", - "GenericParameter": [ - { - "ParameterName": "TState", - "ParameterPosition": 0, - "BaseTypeOrInterfaces": [] - } - ] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.IChangeToken", - "Visibility": "Public", - "Kind": "Interface", - "Abstract": true, - "ImplementedInterfaces": [], - "Members": [ - { - "Kind": "Method", - "Name": "get_HasChanged", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_ActiveChangeCallbacks", - "Parameters": [], - "ReturnType": "System.Boolean", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "RegisterChangeCallback", - "Parameters": [ - { - "Name": "callback", - "Type": "System.Action" - }, - { - "Name": "state", - "Type": "System.Object" - } - ], - "ReturnType": "System.IDisposable", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.StringSegment", - "Visibility": "Public", - "Kind": "Struct", - "Sealed": true, - "ImplementedInterfaces": [ - "System.IEquatable", - "System.IEquatable" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_Buffer", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Offset", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Length", - "Parameters": [], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Value", - "Parameters": [], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_HasValue", - "Parameters": [], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "obj", - "Type": "System.Object" - } - ], - "ReturnType": "System.Boolean", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "Microsoft.Extensions.Primitives.StringSegment" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "Microsoft.Extensions.Primitives.StringSegment" - }, - { - "Name": "comparisonType", - "Type": "System.StringComparison" - } - ], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "text", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "text", - "Type": "System.String" - }, - { - "Name": "comparisonType", - "Type": "System.StringComparison" - } - ], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetHashCode", - "Parameters": [], - "ReturnType": "System.Int32", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringSegment" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringSegment" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringSegment" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringSegment" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "StartsWith", - "Parameters": [ - { - "Name": "text", - "Type": "System.String" - }, - { - "Name": "comparisonType", - "Type": "System.StringComparison" - } - ], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "EndsWith", - "Parameters": [ - { - "Name": "text", - "Type": "System.String" - }, - { - "Name": "comparisonType", - "Type": "System.StringComparison" - } - ], - "ReturnType": "System.Boolean", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Substring", - "Parameters": [ - { - "Name": "offset", - "Type": "System.Int32" - }, - { - "Name": "length", - "Type": "System.Int32" - } - ], - "ReturnType": "System.String", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Subsegment", - "Parameters": [ - { - "Name": "offset", - "Type": "System.Int32" - }, - { - "Name": "length", - "Type": "System.Int32" - } - ], - "ReturnType": "Microsoft.Extensions.Primitives.StringSegment", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IndexOf", - "Parameters": [ - { - "Name": "c", - "Type": "System.Char" - }, - { - "Name": "start", - "Type": "System.Int32" - }, - { - "Name": "count", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IndexOf", - "Parameters": [ - { - "Name": "c", - "Type": "System.Char" - }, - { - "Name": "start", - "Type": "System.Int32" - } - ], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IndexOf", - "Parameters": [ - { - "Name": "c", - "Type": "System.Char" - } - ], - "ReturnType": "System.Int32", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Trim", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringSegment", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "TrimStart", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringSegment", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "TrimEnd", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringSegment", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ToString", - "Parameters": [], - "ReturnType": "System.String", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "buffer", - "Type": "System.String" - } - ], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "buffer", - "Type": "System.String" - }, - { - "Name": "offset", - "Type": "System.Int32" - }, - { - "Name": "length", - "Type": "System.Int32" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.StringTokenizer", - "Visibility": "Public", - "Kind": "Struct", - "Sealed": true, - "ImplementedInterfaces": [ - "System.Collections.Generic.IEnumerable" - ], - "Members": [ - { - "Kind": "Method", - "Name": "GetEnumerator", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringTokenizer+Enumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - }, - { - "Name": "separators", - "Type": "System.Char[]" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.StringValues", - "Visibility": "Public", - "Kind": "Struct", - "Sealed": true, - "ImplementedInterfaces": [ - "System.Collections.Generic.IList", - "System.Collections.Generic.IReadOnlyList", - "System.IEquatable", - "System.IEquatable", - "System.IEquatable" - ], - "Members": [ - { - "Kind": "Method", - "Name": "op_Implicit", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "ReturnType": "Microsoft.Extensions.Primitives.StringValues", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Implicit", - "Parameters": [ - { - "Name": "values", - "Type": "System.String[]" - } - ], - "ReturnType": "Microsoft.Extensions.Primitives.StringValues", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Implicit", - "Parameters": [ - { - "Name": "values", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.String", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Implicit", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.String[]", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Count", - "Parameters": [], - "ReturnType": "System.Int32", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.Generic.ICollection", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Item", - "Parameters": [ - { - "Name": "index", - "Type": "System.Int32" - } - ], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.Generic.IReadOnlyList", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ToString", - "Parameters": [], - "ReturnType": "System.String", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "ToArray", - "Parameters": [], - "ReturnType": "System.String[]", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetEnumerator", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringValues+Enumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "IsNullOrEmpty", - "Parameters": [ - { - "Name": "value", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Concat", - "Parameters": [ - { - "Name": "values1", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "values2", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "Microsoft.Extensions.Primitives.StringValues", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "left", - "Type": "System.String" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "left", - "Type": "System.String[]" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.String[]" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "other", - "Type": "System.String[]" - } - ], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IEquatable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.String" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "System.String" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "System.String" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.String[]" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.String[]" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "System.String[]" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "System.String[]" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.Object" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "Microsoft.Extensions.Primitives.StringValues" - }, - { - "Name": "right", - "Type": "System.Object" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Equality", - "Parameters": [ - { - "Name": "left", - "Type": "System.Object" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "op_Inequality", - "Parameters": [ - { - "Name": "left", - "Type": "System.Object" - }, - { - "Name": "right", - "Type": "Microsoft.Extensions.Primitives.StringValues" - } - ], - "ReturnType": "System.Boolean", - "Static": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Equals", - "Parameters": [ - { - "Name": "obj", - "Type": "System.Object" - } - ], - "ReturnType": "System.Boolean", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "GetHashCode", - "Parameters": [], - "ReturnType": "System.Int32", - "Virtual": true, - "Override": true, - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "value", - "Type": "System.String" - } - ], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "values", - "Type": "System.String[]" - } - ], - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Field", - "Name": "Empty", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringValues", - "Static": true, - "ReadOnly": true, - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.StringTokenizer+Enumerator", - "Visibility": "Public", - "Kind": "Struct", - "Sealed": true, - "ImplementedInterfaces": [ - "System.Collections.Generic.IEnumerator" - ], - "Members": [ - { - "Kind": "Method", - "Name": "get_Current", - "Parameters": [], - "ReturnType": "Microsoft.Extensions.Primitives.StringSegment", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.Generic.IEnumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Dispose", - "Parameters": [], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.IDisposable", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "MoveNext", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.IEnumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "Reset", - "Parameters": [], - "ReturnType": "System.Void", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.IEnumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "tokenizer", - "Type": "Microsoft.Extensions.Primitives.StringTokenizer", - "Direction": "Ref" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - }, - { - "Name": "Microsoft.Extensions.Primitives.StringValues+Enumerator", - "Visibility": "Public", - "Kind": "Struct", - "Sealed": true, - "ImplementedInterfaces": [ - "System.Collections.Generic.IEnumerator" - ], - "Members": [ - { - "Kind": "Method", - "Name": "MoveNext", - "Parameters": [], - "ReturnType": "System.Boolean", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.IEnumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Method", - "Name": "get_Current", - "Parameters": [], - "ReturnType": "System.String", - "Sealed": true, - "Virtual": true, - "ImplementedInterface": "System.Collections.Generic.IEnumerator", - "Visibility": "Public", - "GenericParameter": [] - }, - { - "Kind": "Constructor", - "Name": ".ctor", - "Parameters": [ - { - "Name": "values", - "Type": "Microsoft.Extensions.Primitives.StringValues", - "Direction": "Ref" - } - ], - "Visibility": "Public", - "GenericParameter": [] - } - ], - "GenericParameters": [] - } - ] -} \ No newline at end of file diff --git a/test/Microsoft.Extensions.CommandLineUtils.Tests/ArgumentEscaperTests.cs b/test/CommandLineUtils.Tests/ArgumentEscaperTests.cs similarity index 95% rename from test/Microsoft.Extensions.CommandLineUtils.Tests/ArgumentEscaperTests.cs rename to test/CommandLineUtils.Tests/ArgumentEscaperTests.cs index a706b05b..9dd801fc 100644 --- a/test/Microsoft.Extensions.CommandLineUtils.Tests/ArgumentEscaperTests.cs +++ b/test/CommandLineUtils.Tests/ArgumentEscaperTests.cs @@ -3,7 +3,7 @@ using Xunit; -namespace Microsoft.Extensions.CommandLineUtils +namespace McMaster.Extensions.CommandLineUtils.Tests { public class ArgumentEscaperTests { diff --git a/test/Microsoft.Extensions.CommandLineUtils.Tests/CommandLineApplicationTests.cs b/test/CommandLineUtils.Tests/CommandLineApplicationTests.cs similarity index 99% rename from test/Microsoft.Extensions.CommandLineUtils.Tests/CommandLineApplicationTests.cs rename to test/CommandLineUtils.Tests/CommandLineApplicationTests.cs index 44b7ebda..f7d81b12 100644 --- a/test/Microsoft.Extensions.CommandLineUtils.Tests/CommandLineApplicationTests.cs +++ b/test/CommandLineUtils.Tests/CommandLineApplicationTests.cs @@ -5,10 +5,9 @@ using System.IO; using System.Linq; using System.Text; -using Microsoft.Extensions.CommandLineUtils; using Xunit; -namespace Microsoft.Extensions.Internal +namespace McMaster.Extensions.CommandLineUtils.Tests { public class CommandLineApplicationTests { diff --git a/test/CommandLineUtils.Tests/DotNetExeTests.cs b/test/CommandLineUtils.Tests/DotNetExeTests.cs new file mode 100644 index 00000000..6600642c --- /dev/null +++ b/test/CommandLineUtils.Tests/DotNetExeTests.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +#if NETCOREAPP2_0 +using System.IO; +using System.Runtime.InteropServices; +using Xunit; + +namespace McMaster.Extensions.CommandLineUtils.Tests +{ + public class DotNetExeTests + { + [Fact] + public void FindsTheDoNetPath() + { + var dotnetPath = DotNetExe.FullPath; + Assert.NotNull(dotnetPath); + Assert.True(File.Exists(dotnetPath), "The file did not exist"); + Assert.True(Path.IsPathRooted(dotnetPath), "The path should be rooted"); + Assert.Equal("dotnet", Path.GetFileNameWithoutExtension(dotnetPath), ignoreCase: true); + } + } +} +#endif diff --git a/test/CommandLineUtils.Tests/McMaster.Extensions.CommandLineUtils.Tests.csproj b/test/CommandLineUtils.Tests/McMaster.Extensions.CommandLineUtils.Tests.csproj new file mode 100644 index 00000000..95818489 --- /dev/null +++ b/test/CommandLineUtils.Tests/McMaster.Extensions.CommandLineUtils.Tests.csproj @@ -0,0 +1,21 @@ + + + + netcoreapp2.0;net461 + netcoreapp2.0 + false + + + + + + + + + + + + + + + diff --git a/test/Directory.Build.props b/test/Directory.Build.props deleted file mode 100644 index 9ceaf28b..00000000 --- a/test/Directory.Build.props +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/test/Microsoft.Extensions.CommandLineUtils.Tests/DotNetMuxerTests.cs b/test/Microsoft.Extensions.CommandLineUtils.Tests/DotNetMuxerTests.cs deleted file mode 100644 index b8612fa1..00000000 --- a/test/Microsoft.Extensions.CommandLineUtils.Tests/DotNetMuxerTests.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -#if NETCOREAPP2_0 -using System.IO; -using System.Runtime.InteropServices; -using Xunit; - -namespace Microsoft.Extensions.CommandLineUtils -{ - public class DotNetMuxerTests - { - [Fact] - public void FindsTheMuxer() - { - var muxerPath = DotNetMuxer.MuxerPath; - Assert.NotNull(muxerPath); - Assert.True(File.Exists(muxerPath), "The file did not exist"); - Assert.True(Path.IsPathRooted(muxerPath), "The path should be rooted"); - Assert.Equal("dotnet", Path.GetFileNameWithoutExtension(muxerPath), ignoreCase: true); - } - } -} -#endif diff --git a/test/Microsoft.Extensions.CommandLineUtils.Tests/Microsoft.Extensions.CommandLineUtils.Tests.csproj b/test/Microsoft.Extensions.CommandLineUtils.Tests/Microsoft.Extensions.CommandLineUtils.Tests.csproj deleted file mode 100755 index 9f03402b..00000000 --- a/test/Microsoft.Extensions.CommandLineUtils.Tests/Microsoft.Extensions.CommandLineUtils.Tests.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - netcoreapp2.0;net461 - netcoreapp2.0 - - - - - - - diff --git a/test/Microsoft.Extensions.Internal.Test/ClosedGenericMatcherTest.cs b/test/Microsoft.Extensions.Internal.Test/ClosedGenericMatcherTest.cs deleted file mode 100644 index e71a7926..00000000 --- a/test/Microsoft.Extensions.Internal.Test/ClosedGenericMatcherTest.cs +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class ClosedGenericMatcherTest - { - // queryType, interfaceType, expectedResult - public static TheoryData ExtractGenericInterfaceDataSet - { - get - { - return new TheoryData - { - // Closed generic types that match given open generic type. - { - typeof(IEnumerable), - typeof(IEnumerable<>), - typeof(IEnumerable) - }, - { - typeof(IReadOnlyList), - typeof(IReadOnlyList<>), - typeof(IReadOnlyList) - }, - { - typeof(KeyValuePair), - typeof(KeyValuePair<,>), - typeof(KeyValuePair) - }, - // Closed generic interfaces that implement sub-interface of given open generic type. - { - typeof(ICollection), - typeof(IEnumerable<>), - typeof(IEnumerable) - }, - { - typeof(IReadOnlyList), - typeof(IEnumerable<>), - typeof(IEnumerable) - }, - { - typeof(IDictionary), - typeof(IEnumerable<>), - typeof(IEnumerable>) - }, - // Class that implements closed generic based on given open generic interface. - { - typeof(BaseClass), - typeof(IDictionary<,>), - typeof(IDictionary) - }, - { - typeof(BaseClass), - typeof(IEquatable<>), - typeof(IEquatable) - }, - { - typeof(BaseClass), - typeof(ICollection<>), - typeof(ICollection>) - }, - // Derived class that implements closed generic based on given open generic interface. - { - typeof(DerivedClass), - typeof(IDictionary<,>), - typeof(IDictionary) - }, - { - typeof(DerivedClass), - typeof(IEquatable<>), - typeof(IEquatable) - }, - { - typeof(DerivedClass), - typeof(ICollection<>), - typeof(ICollection>) - }, - // Derived class that also implements another interface. - { - typeof(DerivedClassWithComparable), - typeof(IDictionary<,>), - typeof(IDictionary) - }, - { - typeof(DerivedClassWithComparable), - typeof(IEquatable<>), - typeof(IEquatable) - }, - { - typeof(DerivedClassWithComparable), - typeof(ICollection<>), - typeof(ICollection>) - }, - { - typeof(DerivedClassWithComparable), - typeof(IComparable<>), - typeof(IComparable) - }, - // Derived class using system implementation. - { - typeof(DerivedClassFromSystemImplementation), - typeof(ICollection<>), - typeof(ICollection) - }, - { - typeof(DerivedClassFromSystemImplementation), - typeof(IReadOnlyList<>), - typeof(IReadOnlyList) - }, - { - typeof(DerivedClassFromSystemImplementation), - typeof(IEnumerable<>), - typeof(IEnumerable) - }, - // Not given an open generic type. - { - typeof(IEnumerable), - typeof(IEnumerable), - null - }, - { - typeof(IEnumerable), - typeof(IEnumerable), - null - }, - { - typeof(IReadOnlyList), - typeof(BaseClass), - null - }, - { - typeof(KeyValuePair<,>), - typeof(KeyValuePair), - null - }, - // Not a match. - { - typeof(IEnumerable), - typeof(IReadOnlyList<>), - null - }, - { - typeof(IList), - typeof(IReadOnlyList<>), - null - }, - { - typeof(IDictionary), - typeof(KeyValuePair<,>), - null - }, - }; - } - } - - [Theory] - [MemberData(nameof(ExtractGenericInterfaceDataSet))] - public void ExtractGenericInterface_ReturnsExpectedType( - Type queryType, - Type interfaceType, - Type expectedResult) - { - // Arrange & Act - var result = ClosedGenericMatcher.ExtractGenericInterface(queryType, interfaceType); - - // Assert - Assert.Equal(expectedResult, result); - } - - // IEnumerable is preferred because it is defined on the more-derived type. - [Fact] - public void ExtractGenericInterface_MultipleDefinitionsInherited() - { - // Arrange - var type = typeof(TwoIEnumerableImplementationsInherited); - - // Act - var result = ClosedGenericMatcher.ExtractGenericInterface(type, typeof(IEnumerable<>)); - - // Sort - Assert.Equal(typeof(IEnumerable), result); - } - - // IEnumerable is preferred because we sort by Ordinal on the full name. - [Fact] - public void ExtractGenericInterface_MultipleDefinitionsOnSameType() - { - // Arrange - var type = typeof(TwoIEnumerableImplementationsOnSameClass); - - // Act - var result = ClosedGenericMatcher.ExtractGenericInterface(type, typeof(IEnumerable<>)); - - // Sort - Assert.Equal(typeof(IEnumerable), result); - } - - private class TwoIEnumerableImplementationsOnSameClass : IEnumerable, IEnumerable - { - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - } - - private class TwoIEnumerableImplementationsInherited : List, IEnumerable - { - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - } - - private class BaseClass : IDictionary, IEquatable - { - object IDictionary.this[string key] - { - get - { - throw new NotImplementedException(); - } - - set - { - throw new NotImplementedException(); - } - } - - int ICollection>.Count - { - get - { - throw new NotImplementedException(); - } - } - - bool ICollection>.IsReadOnly - { - get - { - throw new NotImplementedException(); - } - } - - ICollection IDictionary.Keys - { - get - { - throw new NotImplementedException(); - } - } - - ICollection IDictionary.Values - { - get - { - throw new NotImplementedException(); - } - } - - public bool Equals(BaseClass other) - { - throw new NotImplementedException(); - } - - void ICollection>.Add(KeyValuePair item) - { - throw new NotImplementedException(); - } - - void IDictionary.Add(string key, object value) - { - throw new NotImplementedException(); - } - - void ICollection>.Clear() - { - throw new NotImplementedException(); - } - - bool ICollection>.Contains(KeyValuePair item) - { - throw new NotImplementedException(); - } - - bool IDictionary.ContainsKey(string key) - { - throw new NotImplementedException(); - } - - void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) - { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - - IEnumerator> IEnumerable>.GetEnumerator() - { - throw new NotImplementedException(); - } - - bool ICollection>.Remove(KeyValuePair item) - { - throw new NotImplementedException(); - } - - bool IDictionary.Remove(string key) - { - throw new NotImplementedException(); - } - - bool IDictionary.TryGetValue(string key, out object value) - { - throw new NotImplementedException(); - } - } - - private class DerivedClass : BaseClass - { - } - - private class DerivedClassWithComparable : DerivedClass, IComparable - { - public int CompareTo(DerivedClassWithComparable other) - { - throw new NotImplementedException(); - } - } - - private class DerivedClassFromSystemImplementation : Collection - { - } - } -} \ No newline at end of file diff --git a/test/Microsoft.Extensions.Internal.Test/CopyOnWriteDictionaryHolderTest.cs b/test/Microsoft.Extensions.Internal.Test/CopyOnWriteDictionaryHolderTest.cs deleted file mode 100644 index 9a0951eb..00000000 --- a/test/Microsoft.Extensions.Internal.Test/CopyOnWriteDictionaryHolderTest.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class CopyOnWriteDictionaryHolderTest - { - [Fact] - public void ReadOperation_DelegatesToSourceDictionary_IfNoMutationsArePerformed() - { - // Arrange - var source = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "test-key", "test-value" }, - { "key2", "key2-value" } - }; - - var holder = new CopyOnWriteDictionaryHolder(source); - - // Act and Assert - Assert.Equal("key2-value", holder["key2"]); - Assert.Equal(2, holder.Count); - Assert.Equal(new string[] { "test-key", "key2" }, holder.Keys.ToArray()); - Assert.Equal(new object[] { "test-value", "key2-value" }, holder.Values.ToArray()); - Assert.True(holder.ContainsKey("test-key")); - - object value; - Assert.False(holder.TryGetValue("different-key", out value)); - - Assert.False(holder.HasBeenCopied); - Assert.Same(source, holder.ReadDictionary); - } - - [Fact] - public void ReadOperation_DoesNotDelegateToSourceDictionary_OnceAValueIsChanged() - { - // Arrange - var source = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "key1", "value1" }, - { "key2", "value2" } - }; - - var holder = new CopyOnWriteDictionaryHolder(source); - - // Act - holder["key2"] = "value3"; - - // Assert - Assert.Equal("value2", source["key2"]); - Assert.Equal(2, holder.Count); - Assert.Equal("value1", holder["key1"]); - Assert.Equal("value3", holder["key2"]); - - Assert.True(holder.HasBeenCopied); - Assert.NotSame(source, holder.ReadDictionary); - } - - [Fact] - public void ReadOperation_DoesNotDelegateToSourceDictionary_OnceValueIsAdded() - { - // Arrange - var source = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { "key1", "value1" }, - { "key2", "value2" } - }; - - var holder = new CopyOnWriteDictionaryHolder(source); - - // Act - holder.Add("key3", "value3"); - holder.Remove("key1"); - - // Assert - Assert.Equal(2, source.Count); - Assert.Equal("value1", source["key1"]); - Assert.Equal(2, holder.Count); - Assert.Equal("value2", holder["KeY2"]); - Assert.Equal("value3", holder["key3"]); - - Assert.True(holder.HasBeenCopied); - Assert.NotSame(source, holder.ReadDictionary); - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/CopyOnWriteDictionaryTest.cs b/test/Microsoft.Extensions.Internal.Test/CopyOnWriteDictionaryTest.cs deleted file mode 100644 index c1b54036..00000000 --- a/test/Microsoft.Extensions.Internal.Test/CopyOnWriteDictionaryTest.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Moq; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class CopyOnWriteDictionaryTest - { - [Fact] - public void ReadOperation_DelegatesToSourceDictionary_IfNoMutationsArePerformed() - { - // Arrange - var values = new List(); - var enumerator = Mock.Of>>(); - var sourceDictionary = new Mock>(MockBehavior.Strict); - sourceDictionary - .SetupGet(d => d.Count) - .Returns(100) - .Verifiable(); - sourceDictionary - .SetupGet(d => d.Values) - .Returns(values) - .Verifiable(); - sourceDictionary - .Setup(d => d.ContainsKey("test-key")) - .Returns(value: true) - .Verifiable(); - sourceDictionary - .Setup(d => d.GetEnumerator()) - .Returns(enumerator) - .Verifiable(); - sourceDictionary - .Setup(d => d["key2"]) - .Returns("key2-value") - .Verifiable(); - object value; - sourceDictionary.Setup(d => d.TryGetValue("different-key", out value)) - .Returns(false) - .Verifiable(); - - var copyOnWriteDictionary = new CopyOnWriteDictionary(sourceDictionary.Object, - StringComparer.OrdinalIgnoreCase); - - // Act and Assert - Assert.Equal("key2-value", copyOnWriteDictionary["key2"]); - Assert.Equal(100, copyOnWriteDictionary.Count); - Assert.Same(values, copyOnWriteDictionary.Values); - Assert.True(copyOnWriteDictionary.ContainsKey("test-key")); - Assert.Same(enumerator, copyOnWriteDictionary.GetEnumerator()); - Assert.False(copyOnWriteDictionary.TryGetValue("different-key", out value)); - sourceDictionary.Verify(); - } - - [Fact] - public void ReadOperation_DoesNotDelegateToSourceDictionary_OnceAValueIsChanged() - { - // Arrange - var values = new List(); - var sourceDictionary = new Dictionary - { - { "key1", "value1" }, - { "key2", "value2" } - }; - var copyOnWriteDictionary = new CopyOnWriteDictionary( - sourceDictionary, - StringComparer.OrdinalIgnoreCase); - - // Act - copyOnWriteDictionary["key2"] = "value3"; - - // Assert - Assert.Equal("value2", sourceDictionary["key2"]); - Assert.Equal(2, copyOnWriteDictionary.Count); - Assert.Equal("value1", copyOnWriteDictionary["key1"]); - Assert.Equal("value3", copyOnWriteDictionary["key2"]); - } - - [Fact] - public void ReadOperation_DoesNotDelegateToSourceDictionary_OnceDictionaryIsModified() - { - // Arrange - var values = new List(); - var sourceDictionary = new Dictionary - { - { "key1", "value1" }, - { "key2", "value2" } - }; - var copyOnWriteDictionary = new CopyOnWriteDictionary( - sourceDictionary, - StringComparer.OrdinalIgnoreCase); - - // Act - copyOnWriteDictionary.Add("key3", "value3"); - copyOnWriteDictionary.Remove("key1"); - - - // Assert - Assert.Equal(2, sourceDictionary.Count); - Assert.Equal("value1", sourceDictionary["key1"]); - Assert.Equal(2, copyOnWriteDictionary.Count); - Assert.Equal("value2", copyOnWriteDictionary["KeY2"]); - Assert.Equal("value3", copyOnWriteDictionary["key3"]); - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/HashCodeCombinerTest.cs b/test/Microsoft.Extensions.Internal.Test/HashCodeCombinerTest.cs deleted file mode 100644 index fab3e309..00000000 --- a/test/Microsoft.Extensions.Internal.Test/HashCodeCombinerTest.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class HashCodeCombinerTest - { - [Fact] - public void GivenTheSameInputs_ItProducesTheSameOutput() - { - var hashCode1 = new HashCodeCombiner(); - var hashCode2 = new HashCodeCombiner(); - - hashCode1.Add(42); - hashCode1.Add("foo"); - hashCode2.Add(42); - hashCode2.Add("foo"); - - Assert.Equal(hashCode1.CombinedHash, hashCode2.CombinedHash); - } - - [Fact] - public void HashCode_Is_OrderSensitive() - { - var hashCode1 = HashCodeCombiner.Start(); - var hashCode2 = HashCodeCombiner.Start(); - - hashCode1.Add(42); - hashCode1.Add("foo"); - - hashCode2.Add("foo"); - hashCode2.Add(42); - - Assert.NotEqual(hashCode1.CombinedHash, hashCode2.CombinedHash); - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/Microsoft.Extensions.Internal.Test.csproj b/test/Microsoft.Extensions.Internal.Test/Microsoft.Extensions.Internal.Test.csproj deleted file mode 100755 index 482089fd..00000000 --- a/test/Microsoft.Extensions.Internal.Test/Microsoft.Extensions.Internal.Test.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - netcoreapp2.0;net461 - netcoreapp2.0 - portable - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/test/Microsoft.Extensions.Internal.Test/ObjectMethodExecutorTest.cs b/test/Microsoft.Extensions.Internal.Test/ObjectMethodExecutorTest.cs deleted file mode 100644 index 1c26ef1d..00000000 --- a/test/Microsoft.Extensions.Internal.Test/ObjectMethodExecutorTest.cs +++ /dev/null @@ -1,634 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Microsoft.FSharp.Control; -using Microsoft.FSharp.Core; -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class ObjectMethodExecutorTest - { - private TestObject _targetObject = new TestObject(); - private TypeInfo targetTypeInfo = typeof(TestObject).GetTypeInfo(); - - [Fact] - public void ExecuteValueMethod() - { - var executor = GetExecutorForMethod("ValueMethod"); - var result = executor.Execute( - _targetObject, - new object[] { 10, 20 }); - Assert.False(executor.IsMethodAsync); - Assert.Equal(30, (int)result); - } - - [Fact] - public void ExecuteVoidValueMethod() - { - var executor = GetExecutorForMethod("VoidValueMethod"); - var result = executor.Execute( - _targetObject, - new object[] { 10 }); - Assert.False(executor.IsMethodAsync); - Assert.Null(result); - } - - [Fact] - public void ExecuteValueMethodWithReturnType() - { - var executor = GetExecutorForMethod("ValueMethodWithReturnType"); - var result = executor.Execute( - _targetObject, - new object[] { 10 }); - var resultObject = Assert.IsType(result); - Assert.False(executor.IsMethodAsync); - Assert.Equal("Hello", resultObject.value); - } - - [Fact] - public void ExecuteValueMethodUpdateValue() - { - var executor = GetExecutorForMethod("ValueMethodUpdateValue"); - var parameter = new TestObject(); - var result = executor.Execute( - _targetObject, - new object[] { parameter }); - var resultObject = Assert.IsType(result); - Assert.False(executor.IsMethodAsync); - Assert.Equal("HelloWorld", resultObject.value); - } - - [Fact] - public void ExecuteValueMethodWithReturnTypeThrowsException() - { - var executor = GetExecutorForMethod("ValueMethodWithReturnTypeThrowsException"); - var parameter = new TestObject(); - Assert.False(executor.IsMethodAsync); - Assert.Throws( - () => executor.Execute( - _targetObject, - new object[] { parameter })); - } - - [Fact] - public async Task ExecuteValueMethodAsync() - { - var executor = GetExecutorForMethod("ValueMethodAsync"); - var result = await executor.ExecuteAsync( - _targetObject, - new object[] { 10, 20 }); - Assert.True(executor.IsMethodAsync); - Assert.Equal(30, (int)result); - } - - [Fact] - public async Task ExecuteValueMethodWithReturnTypeAsync() - { - var executor = GetExecutorForMethod("ValueMethodWithReturnTypeAsync"); - var result = await executor.ExecuteAsync( - _targetObject, - new object[] { 10 }); - var resultObject = Assert.IsType(result); - Assert.True(executor.IsMethodAsync); - Assert.Equal("Hello", resultObject.value); - } - - [Fact] - public async Task ExecuteValueMethodUpdateValueAsync() - { - var executor = GetExecutorForMethod("ValueMethodUpdateValueAsync"); - var parameter = new TestObject(); - var result = await executor.ExecuteAsync( - _targetObject, - new object[] { parameter }); - var resultObject = Assert.IsType(result); - Assert.True(executor.IsMethodAsync); - Assert.Equal("HelloWorld", resultObject.value); - } - - [Fact] - public async Task ExecuteValueMethodWithReturnTypeThrowsExceptionAsync() - { - var executor = GetExecutorForMethod("ValueMethodWithReturnTypeThrowsExceptionAsync"); - var parameter = new TestObject(); - Assert.True(executor.IsMethodAsync); - await Assert.ThrowsAsync( - async () => await executor.ExecuteAsync( - _targetObject, - new object[] { parameter })); - } - - [Fact] - public async Task ExecuteValueMethodWithReturnVoidThrowsExceptionAsync() - { - var executor = GetExecutorForMethod("ValueMethodWithReturnVoidThrowsExceptionAsync"); - var parameter = new TestObject(); - Assert.True(executor.IsMethodAsync); - await Assert.ThrowsAsync( - async () => await executor.ExecuteAsync( - _targetObject, - new object[] { parameter })); - } - - [Fact] - public void GetDefaultValueForParameters_ReturnsSuppliedValues() - { - var suppliedDefaultValues = new object[] { 123, "test value" }; - var executor = GetExecutorForMethod("MethodWithMultipleParameters", suppliedDefaultValues); - Assert.Equal(suppliedDefaultValues[0], executor.GetDefaultValueForParameter(0)); - Assert.Equal(suppliedDefaultValues[1], executor.GetDefaultValueForParameter(1)); - Assert.Throws(() => executor.GetDefaultValueForParameter(2)); - } - - [Fact] - public void GetDefaultValueForParameters_ThrowsIfNoneWereSupplied() - { - var executor = GetExecutorForMethod("MethodWithMultipleParameters"); - Assert.Throws(() => executor.GetDefaultValueForParameter(0)); - } - - [Fact] - public async void TargetMethodReturningCustomAwaitableOfReferenceType_CanInvokeViaExecute() - { - // Arrange - var executor = GetExecutorForMethod("CustomAwaitableOfReferenceTypeAsync"); - - // Act - var result = await (TestAwaitable)executor.Execute(_targetObject, new object[] { "Hello", 123 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(TestObject), executor.AsyncResultType); - Assert.NotNull(result); - Assert.Equal("Hello 123", result.value); - } - - [Fact] - public async void TargetMethodReturningCustomAwaitableOfValueType_CanInvokeViaExecute() - { - // Arrange - var executor = GetExecutorForMethod("CustomAwaitableOfValueTypeAsync"); - - // Act - var result = await (TestAwaitable)executor.Execute(_targetObject, new object[] { 123, 456 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(int), executor.AsyncResultType); - Assert.Equal(579, result); - } - - [Fact] - public async void TargetMethodReturningCustomAwaitableOfReferenceType_CanInvokeViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("CustomAwaitableOfReferenceTypeAsync"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[] { "Hello", 123 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(TestObject), executor.AsyncResultType); - Assert.NotNull(result); - Assert.IsType(result); - Assert.Equal("Hello 123", ((TestObject)result).value); - } - - [Fact] - public async void TargetMethodReturningCustomAwaitableOfValueType_CanInvokeViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("CustomAwaitableOfValueTypeAsync"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[] { 123, 456 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(int), executor.AsyncResultType); - Assert.NotNull(result); - Assert.IsType(result); - Assert.Equal(579, (int)result); - } - - [Fact] - public async void TargetMethodReturningAwaitableOfVoidType_CanInvokeViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("VoidValueMethodAsync"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[] { 123 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(void), executor.AsyncResultType); - Assert.Null(result); - } - - [Fact] - public async void TargetMethodReturningAwaitableWithICriticalNotifyCompletion_UsesUnsafeOnCompleted() - { - // Arrange - var executor = GetExecutorForMethod("CustomAwaitableWithICriticalNotifyCompletion"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[0]); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - Assert.Equal("Used UnsafeOnCompleted", (string)result); - } - - [Fact] - public async void TargetMethodReturningAwaitableWithoutICriticalNotifyCompletion_UsesOnCompleted() - { - // Arrange - var executor = GetExecutorForMethod("CustomAwaitableWithoutICriticalNotifyCompletion"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[0]); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - Assert.Equal("Used OnCompleted", (string)result); - } - - [Fact] - public async void TargetMethodReturningValueTaskOfValueType_CanBeInvokedViaExecute() - { - // Arrange - var executor = GetExecutorForMethod("ValueTaskOfValueType"); - - // Act - var result = await (ValueTask)executor.Execute(_targetObject, new object[] { 123 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(int), executor.AsyncResultType); - Assert.Equal(123, result); - } - - [Fact] - public async void TargetMethodReturningValueTaskOfReferenceType_CanBeInvokedViaExecute() - { - // Arrange - var executor = GetExecutorForMethod("ValueTaskOfReferenceType"); - - // Act - var result = await (ValueTask)executor.Execute(_targetObject, new object[] { "test result" }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - Assert.Equal("test result", result); - } - - [Fact] - public async void TargetMethodReturningValueTaskOfValueType_CanBeInvokedViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("ValueTaskOfValueType"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[] { 123 }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(int), executor.AsyncResultType); - Assert.NotNull(result); - Assert.Equal(123, (int)result); - } - - [Fact] - public async void TargetMethodReturningValueTaskOfReferenceType_CanBeInvokedViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("ValueTaskOfReferenceType"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[] { "test result" }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - Assert.Equal("test result", result); - } - - [Fact] - public async void TargetMethodReturningFSharpAsync_CanBeInvokedViaExecute() - { - // Arrange - var executor = GetExecutorForMethod("FSharpAsyncMethod"); - - // Act - var fsharpAsync = (FSharpAsync)executor.Execute(_targetObject, new object[] { "test result" }); - var result = await FSharpAsync.StartAsTask(fsharpAsync, - FSharpOption.None, - FSharpOption.None); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - Assert.Equal("test result", result); - } - - [Fact] - public async void TargetMethodReturningFailingFSharpAsync_CanBeInvokedViaExecute() - { - // Arrange - var executor = GetExecutorForMethod("FSharpAsyncFailureMethod"); - - // Act - var fsharpAsync = (FSharpAsync)executor.Execute(_targetObject, new object[] { "test result" }); - var resultTask = FSharpAsync.StartAsTask(fsharpAsync, - FSharpOption.None, - FSharpOption.None); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - - var exception = await Assert.ThrowsAsync(async () => await resultTask); - Assert.IsType(exception.InnerException); - Assert.Equal("Test exception", exception.InnerException.Message); - } - - [Fact] - public async void TargetMethodReturningFSharpAsync_CanBeInvokedViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("FSharpAsyncMethod"); - - // Act - var result = await executor.ExecuteAsync(_targetObject, new object[] { "test result" }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - Assert.Equal("test result", result); - } - - [Fact] - public async void TargetMethodReturningFailingFSharpAsync_CanBeInvokedViaExecuteAsync() - { - // Arrange - var executor = GetExecutorForMethod("FSharpAsyncFailureMethod"); - - // Act - var resultTask = executor.ExecuteAsync(_targetObject, new object[] { "test result" }); - - // Assert - Assert.True(executor.IsMethodAsync); - Assert.Same(typeof(string), executor.AsyncResultType); - - var exception = await Assert.ThrowsAsync(async () => await resultTask); - Assert.IsType(exception.InnerException); - Assert.Equal("Test exception", exception.InnerException.Message); - } - - private ObjectMethodExecutor GetExecutorForMethod(string methodName) - { - var method = typeof(TestObject).GetMethod(methodName); - return ObjectMethodExecutor.Create(method, targetTypeInfo); - } - - private ObjectMethodExecutor GetExecutorForMethod(string methodName, object[] parameterDefaultValues) - { - var method = typeof(TestObject).GetMethod(methodName); - return ObjectMethodExecutor.Create(method, targetTypeInfo, parameterDefaultValues); - } - - public class TestObject - { - public string value; - public int ValueMethod(int i, int j) - { - return i + j; - } - - public void VoidValueMethod(int i) - { - - } - - public TestObject ValueMethodWithReturnType(int i) - { - return new TestObject() { value = "Hello" }; ; - } - - public TestObject ValueMethodWithReturnTypeThrowsException(TestObject i) - { - throw new NotImplementedException("Not Implemented Exception"); - } - - public TestObject ValueMethodUpdateValue(TestObject parameter) - { - parameter.value = "HelloWorld"; - return parameter; - } - - public Task ValueMethodAsync(int i, int j) - { - return Task.FromResult(i + j); - } - - public async Task VoidValueMethodAsync(int i) - { - await ValueMethodAsync(3, 4); - } - public Task ValueMethodWithReturnTypeAsync(int i) - { - return Task.FromResult(new TestObject() { value = "Hello" }); - } - - public async Task ValueMethodWithReturnVoidThrowsExceptionAsync(TestObject i) - { - await Task.CompletedTask; - throw new NotImplementedException("Not Implemented Exception"); - } - - public async Task ValueMethodWithReturnTypeThrowsExceptionAsync(TestObject i) - { - await Task.CompletedTask; - throw new NotImplementedException("Not Implemented Exception"); - } - - public Task ValueMethodUpdateValueAsync(TestObject parameter) - { - parameter.value = "HelloWorld"; - return Task.FromResult(parameter); - } - - public TestAwaitable CustomAwaitableOfReferenceTypeAsync( - string input1, - int input2) - { - return new TestAwaitable(new TestObject - { - value = $"{input1} {input2}" - }); - } - - public TestAwaitable CustomAwaitableOfValueTypeAsync( - int input1, - int input2) - { - return new TestAwaitable(input1 + input2); - } - - public TestAwaitableWithICriticalNotifyCompletion CustomAwaitableWithICriticalNotifyCompletion() - { - return new TestAwaitableWithICriticalNotifyCompletion(); - } - - public TestAwaitableWithoutICriticalNotifyCompletion CustomAwaitableWithoutICriticalNotifyCompletion() - { - return new TestAwaitableWithoutICriticalNotifyCompletion(); - } - - public ValueTask ValueTaskOfValueType(int result) - { - return new ValueTask(result); - } - - public ValueTask ValueTaskOfReferenceType(string result) - { - return new ValueTask(result); - } - - public void MethodWithMultipleParameters(int valueTypeParam, string referenceTypeParam) - { - } - - public FSharpAsync FSharpAsyncMethod(string parameter) - { - return FSharpAsync.AwaitTask(Task.FromResult(parameter)); - } - - public FSharpAsync FSharpAsyncFailureMethod(string parameter) - { - return FSharpAsync.AwaitTask( - Task.FromException(new InvalidOperationException("Test exception"))); - } - } - - public class TestAwaitable - { - private T _result; - private bool _isCompleted; - private List _onCompletedCallbacks = new List(); - - public TestAwaitable(T result) - { - _result = result; - - // Simulate a brief delay before completion - ThreadPool.QueueUserWorkItem(_ => - { - Thread.Sleep(100); - SetCompleted(); - }); - } - - private void SetCompleted() - { - _isCompleted = true; - - foreach (var callback in _onCompletedCallbacks) - { - callback(); - } - } - - public TestAwaiter GetAwaiter() - { - return new TestAwaiter(this); - } - - public struct TestAwaiter : INotifyCompletion - { - private TestAwaitable _owner; - - public TestAwaiter(TestAwaitable owner) : this() - { - _owner = owner; - } - - public bool IsCompleted => _owner._isCompleted; - - public void OnCompleted(Action continuation) - { - if (_owner._isCompleted) - { - continuation(); - } - else - { - _owner._onCompletedCallbacks.Add(continuation); - } - } - - public T GetResult() - { - return _owner._result; - } - } - } - - public class TestAwaitableWithICriticalNotifyCompletion - { - public TestAwaiterWithICriticalNotifyCompletion GetAwaiter() - => new TestAwaiterWithICriticalNotifyCompletion(); - } - - public class TestAwaitableWithoutICriticalNotifyCompletion - { - public TestAwaiterWithoutICriticalNotifyCompletion GetAwaiter() - => new TestAwaiterWithoutICriticalNotifyCompletion(); - } - - public class TestAwaiterWithICriticalNotifyCompletion - : CompletionTrackingAwaiterBase, ICriticalNotifyCompletion - { - } - - public class TestAwaiterWithoutICriticalNotifyCompletion - : CompletionTrackingAwaiterBase, INotifyCompletion - { - } - - public class CompletionTrackingAwaiterBase - { - private string _result; - - public bool IsCompleted { get; private set; } - - public string GetResult() => _result; - - public void OnCompleted(Action continuation) - { - _result = "Used OnCompleted"; - IsCompleted = true; - continuation(); - } - - public void UnsafeOnCompleted(Action continuation) - { - _result = "Used UnsafeOnCompleted"; - IsCompleted = true; - continuation(); - } - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/PropertyActivatorTest.cs b/test/Microsoft.Extensions.Internal.Test/PropertyActivatorTest.cs deleted file mode 100644 index a5cb1605..00000000 --- a/test/Microsoft.Extensions.Internal.Test/PropertyActivatorTest.cs +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Reflection; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class PropertyActivatorTest - { - [Fact] - public void Activate_InvokesValueAccessorWithExpectedValue() - { - // Arrange - var instance = new TestClass(); - var typeInfo = instance.GetType().GetTypeInfo(); - var property = typeInfo.GetDeclaredProperty("IntProperty"); - var invokedWith = -1; - var activator = new PropertyActivator( - property, - valueAccessor: (val) => - { - invokedWith = val; - return val; - }); - - // Act - activator.Activate(instance, 123); - - // Assert - Assert.Equal(123, invokedWith); - } - - [Fact] - public void Activate_SetsPropertyValue() - { - // Arrange - var instance = new TestClass(); - var typeInfo = instance.GetType().GetTypeInfo(); - var property = typeInfo.GetDeclaredProperty("IntProperty"); - var activator = new PropertyActivator(property, valueAccessor: (val) => val + 1); - - // Act - activator.Activate(instance, 123); - - // Assert - Assert.Equal(124, instance.IntProperty); - } - - [Fact] - public void GetPropertiesToActivate_RestrictsActivatableProperties() - { - // Arrange - var instance = new TestClass(); - var typeInfo = instance.GetType().GetTypeInfo(); - var expectedPropertyInfo = typeInfo.GetDeclaredProperty("ActivatableProperty"); - - // Act - var propertiesToActivate = PropertyActivator.GetPropertiesToActivate( - type: typeof(TestClass), - activateAttributeType: typeof(TestActivateAttribute), - createActivateInfo: - (propertyInfo) => new PropertyActivator(propertyInfo, valueAccessor: (val) => val + 1)); - - // Assert - Assert.Collection( - propertiesToActivate, - (activator) => - { - Assert.Equal(expectedPropertyInfo, activator.PropertyInfo); - }); - } - - [Fact] - public void GetPropertiesToActivate_CanCreateCustomPropertyActivators() - { - // Arrange - var instance = new TestClass(); - var typeInfo = instance.GetType().GetTypeInfo(); - var expectedPropertyInfo = typeInfo.GetDeclaredProperty("IntProperty"); - - // Act - var propertiesToActivate = PropertyActivator.GetPropertiesToActivate( - type: typeof(TestClass), - activateAttributeType: typeof(TestActivateAttribute), - createActivateInfo: - (propertyInfo) => new PropertyActivator(expectedPropertyInfo, valueAccessor: (val) => val + 1)); - - // Assert - Assert.Collection( - propertiesToActivate, - (activator) => - { - Assert.Equal(expectedPropertyInfo, activator.PropertyInfo); - }); - } - - [Fact] - public void GetPropertiesToActivate_ExcludesNonPublic() - { - // Arrange - var instance = new TestClassWithPropertyVisiblity(); - var typeInfo = instance.GetType().GetTypeInfo(); - var expectedPropertyInfo = typeInfo.GetDeclaredProperty("Public"); - - // Act - var propertiesToActivate = PropertyActivator.GetPropertiesToActivate( - typeof(TestClassWithPropertyVisiblity), - typeof(TestActivateAttribute), - (propertyInfo) => new PropertyActivator(propertyInfo, valueAccessor: (val) => val)); - - // Assert - Assert.Single(propertiesToActivate); - Assert.Single(propertiesToActivate, p => p.PropertyInfo == expectedPropertyInfo); - } - - [Fact] - public void GetPropertiesToActivate_IncludesNonPublic() - { - // Arrange - var instance = new TestClassWithPropertyVisiblity(); - var typeInfo = instance.GetType().GetTypeInfo(); - - // Act - var propertiesToActivate = PropertyActivator.GetPropertiesToActivate( - typeof(TestClassWithPropertyVisiblity), - typeof(TestActivateAttribute), - (propertyInfo) => new PropertyActivator(propertyInfo, valueAccessor: (val) => val), - includeNonPublic: true); - - // Assert - Assert.Equal(5, propertiesToActivate.Length); - } - - private class TestClass - { - public int IntProperty { get; set; } - - [TestActivate] - public int ActivatableProperty { get; set; } - - [TestActivate] - public int NoSetterActivatableProperty { get; } - - [TestActivate] - public int this[int something] // Not activatable - { - get - { - return 0; - } - } - - [TestActivate] - public static int StaticActivatablProperty { get; set; } - } - - private class TestClassWithPropertyVisiblity - { - [TestActivate] - public int Public { get; set; } - - [TestActivate] - protected int Protected { get; set; } - - [TestActivate] - internal int Internal { get; set; } - - [TestActivate] - protected internal int ProtectedInternal {get; set; } - - [TestActivate] - private int Private { get; set; } - } - - [AttributeUsage(AttributeTargets.Property)] - private class TestActivateAttribute : Attribute - { - } - - private class ActivationInfo - { - public string Name { get; set; } - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/PropertyHelperTest.cs b/test/Microsoft.Extensions.Internal.Test/PropertyHelperTest.cs deleted file mode 100644 index 19cf08b3..00000000 --- a/test/Microsoft.Extensions.Internal.Test/PropertyHelperTest.cs +++ /dev/null @@ -1,831 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class PropertyHelperTest - { - [Fact] - public void PropertyHelper_ReturnsNameCorrectly() - { - // Arrange - var anonymous = new { foo = "bar" }; - var property = PropertyHelper.GetProperties(anonymous.GetType()).First().Property; - - // Act - var helper = new PropertyHelper(property); - - // Assert - Assert.Equal("foo", property.Name); - Assert.Equal("foo", helper.Name); - } - - [Fact] - public void PropertyHelper_ReturnsValueCorrectly() - { - // Arrange - var anonymous = new { bar = "baz" }; - var property = PropertyHelper.GetProperties(anonymous.GetType()).First().Property; - - // Act - var helper = new PropertyHelper(property); - - // Assert - Assert.Equal("bar", helper.Name); - Assert.Equal("baz", helper.GetValue(anonymous)); - } - - [Fact] - public void PropertyHelper_ReturnsGetterDelegate() - { - // Arrange - var anonymous = new { bar = "baz" }; - var property = PropertyHelper.GetProperties(anonymous.GetType()).First().Property; - - // Act - var helper = new PropertyHelper(property); - - // Assert - Assert.NotNull(helper.ValueGetter); - Assert.Equal("baz", helper.ValueGetter(anonymous)); - } - - [Fact] - public void SetValue_SetsPropertyValue() - { - // Arrange - var expected = "new value"; - var instance = new BaseClass { PropA = "old value" }; - var helper = PropertyHelper.GetProperties( - instance.GetType()).First(prop => prop.Name == "PropA"); - - // Act - helper.SetValue(instance, expected); - - // Assert - Assert.Equal(expected, instance.PropA); - } - - [Fact] - public void PropertyHelper_ReturnsSetterDelegate() - { - // Arrange - var expected = "new value"; - var instance = new BaseClass { PropA = "old value" }; - var helper = PropertyHelper.GetProperties( - instance.GetType()).First(prop => prop.Name == "PropA"); - - // Act and Assert - Assert.NotNull(helper.ValueSetter); - helper.ValueSetter(instance, expected); - - // Assert - Assert.Equal(expected, instance.PropA); - } - - [Fact] - public void PropertyHelper_ReturnsValueCorrectly_ForValueTypes() - { - // Arrange - var anonymous = new { foo = 32 }; - var property = PropertyHelper.GetProperties(anonymous.GetType()).First().Property; - - // Act - var helper = new PropertyHelper(property); - - // Assert - Assert.Equal("foo", helper.Name); - Assert.Equal(32, helper.GetValue(anonymous)); - } - - [Fact] - public void PropertyHelper_ReturnsCachedPropertyHelper() - { - // Arrange - var anonymous = new { foo = "bar" }; - - // Act - var helpers1 = PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo()); - var helpers2 = PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo()); - - // Assert - Assert.Single(helpers1); - Assert.Same(helpers1, helpers2); - Assert.Same(helpers1[0], helpers2[0]); - } - - [Fact] - public void PropertyHelper_DoesNotChangeUnderscores() - { - // Arrange - var anonymous = new { bar_baz2 = "foo" }; - - // Act + Assert - var helper = Assert.Single(PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo())); - Assert.Equal("bar_baz2", helper.Name); - } - - [Fact] - public void PropertyHelper_DoesNotFindPrivateProperties() - { - // Arrange - var anonymous = new PrivateProperties(); - - // Act + Assert - var helper = Assert.Single(PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo())); - Assert.Equal("Prop1", helper.Name); - } - - [Fact] - public void PropertyHelper_DoesNotFindStaticProperties() - { - // Arrange - var anonymous = new Static(); - - // Act + Assert - var helper = Assert.Single(PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo())); - Assert.Equal("Prop5", helper.Name); - } - - [Fact] - public void PropertyHelper_DoesNotFindSetOnlyProperties() - { - // Arrange - var anonymous = new SetOnly(); - - // Act + Assert - var helper = Assert.Single(PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo())); - Assert.Equal("Prop6", helper.Name); - } - - [Theory] - [InlineData(typeof(int?))] - [InlineData(typeof(DayOfWeek?))] - public void PropertyHelper_WorksForNullablePrimitiveAndEnumTypes(Type nullableType) - { - // Act - var properties = PropertyHelper.GetProperties(nullableType); - - // Assert - Assert.Empty(properties); - } - - [Fact] - public void PropertyHelper_UnwrapsNullableTypes() - { - // Arrange - var myType = typeof(MyStruct?); - - // Act - var properties = PropertyHelper.GetProperties(myType); - - // Assert - var property = Assert.Single(properties); - Assert.Equal("Foo", property.Name); - } - - [Fact] - public void PropertyHelper_WorksForStruct() - { - // Arrange - var anonymous = new MyProperties(); - - anonymous.IntProp = 3; - anonymous.StringProp = "Five"; - - // Act + Assert - var helper1 = Assert.Single(PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo()).Where(prop => prop.Name == "IntProp")); - var helper2 = Assert.Single(PropertyHelper.GetProperties(anonymous.GetType().GetTypeInfo()).Where(prop => prop.Name == "StringProp")); - Assert.Equal(3, helper1.GetValue(anonymous)); - Assert.Equal("Five", helper2.GetValue(anonymous)); - } - - [Fact] - public void PropertyHelper_ForDerivedClass() - { - // Arrange - var derived = new DerivedClass { PropA = "propAValue", PropB = "propBValue" }; - - // Act - var helpers = PropertyHelper.GetProperties(derived.GetType().GetTypeInfo()).ToArray(); - - // Assert - Assert.NotNull(helpers); - Assert.Equal(2, helpers.Length); - - var propAHelper = Assert.Single(helpers.Where(h => h.Name == "PropA")); - var propBHelper = Assert.Single(helpers.Where(h => h.Name == "PropB")); - - Assert.Equal("propAValue", propAHelper.GetValue(derived)); - Assert.Equal("propBValue", propBHelper.GetValue(derived)); - } - - [Fact] - public void PropertyHelper_ForDerivedClass_WithNew() - { - // Arrange - var derived = new DerivedClassWithNew { PropA = "propAValue" }; - - // Act - var helpers = PropertyHelper.GetProperties(derived.GetType().GetTypeInfo()).ToArray(); - - // Assert - Assert.NotNull(helpers); - Assert.Equal(2, helpers.Length); - - var propAHelper = Assert.Single(helpers.Where(h => h.Name == "PropA")); - var propBHelper = Assert.Single(helpers.Where(h => h.Name == "PropB")); - - Assert.Equal("propAValue", propAHelper.GetValue(derived)); - Assert.Equal("Newed", propBHelper.GetValue(derived)); - } - - [Fact] - public void PropertyHelper_ForDerived_WithVirtual() - { - // Arrange - var derived = new DerivedClassWithOverride { PropA = "propAValue", PropB = "propBValue" }; - - // Act - var helpers = PropertyHelper.GetProperties(derived.GetType().GetTypeInfo()).ToArray(); - - // Assert - Assert.NotNull(helpers); - Assert.Equal(2, helpers.Length); - - var propAHelper = Assert.Single(helpers.Where(h => h.Name == "PropA")); - var propBHelper = Assert.Single(helpers.Where(h => h.Name == "PropB")); - - Assert.Equal("OverridenpropAValue", propAHelper.GetValue(derived)); - Assert.Equal("propBValue", propBHelper.GetValue(derived)); - } - - [Fact] - public void PropertyHelper_ForInterface_ReturnsExpectedProperties() - { - // Arrange - var expectedNames = new[] { "Count", "IsReadOnly" }; - - // Act - var helpers = PropertyHelper.GetProperties(typeof(ICollection)); - - // Assert - Assert.Collection( - helpers.OrderBy(helper => helper.Name, StringComparer.Ordinal), - helper => { Assert.Equal(expectedNames[0], helper.Name, StringComparer.Ordinal); }, - helper => { Assert.Equal(expectedNames[1], helper.Name, StringComparer.Ordinal); }); - } - - [Fact] - public void PropertyHelper_ForDerivedInterface_ReturnsAllProperties() - { - // Arrange - var expectedNames = new[] { "Count", "IsReadOnly", "Keys", "Values" }; - - // Act - var helpers = PropertyHelper.GetProperties(typeof(IDictionary)); - - // Assert - Assert.Collection( - helpers.OrderBy(helper => helper.Name, StringComparer.Ordinal), - helper => { Assert.Equal(expectedNames[0], helper.Name, StringComparer.Ordinal); }, - helper => { Assert.Equal(expectedNames[1], helper.Name, StringComparer.Ordinal); }, - helper => { Assert.Equal(expectedNames[2], helper.Name, StringComparer.Ordinal); }, - helper => { Assert.Equal(expectedNames[3], helper.Name, StringComparer.Ordinal); }); - } - - [Fact] - public void GetProperties_ExcludesIndexersAndPropertiesWithoutPublicGetters() - { - // Arrange - var type = typeof(DerivedClassWithNonReadableProperties); - - // Act - var result = PropertyHelper.GetProperties(type).ToArray(); - - // Assert - Assert.Equal(3, result.Length); - Assert.Equal("Visible", result[0].Name); - Assert.Equal("PropA", result[1].Name); - Assert.Equal("PropB", result[2].Name); - } - - [Fact] - public void GetVisibleProperties_NoHiddenProperty() - { - // Arrange - var type = typeof(string); - - // Act - var result = PropertyHelper.GetVisibleProperties(type).ToArray(); - - // Assert - var property = Assert.Single(result); - Assert.Equal("Length", property.Name); - Assert.Equal(typeof(int), property.Property.PropertyType); - } - - [Fact] - public void GetVisibleProperties_HiddenProperty() - { - // Arrange - var type = typeof(DerivedHiddenProperty); - - // Act - var result = PropertyHelper.GetVisibleProperties(type).ToArray(); - - // Assert - Assert.Equal(2, result.Length); - Assert.Equal("Id", result[0].Name); - Assert.Equal(typeof(string), result[0].Property.PropertyType); - Assert.Equal("Name", result[1].Name); - Assert.Equal(typeof(string), result[1].Property.PropertyType); - } - - [Fact] - public void GetVisibleProperties_HiddenProperty_TwoLevels() - { - // Arrange - var type = typeof(DerivedHiddenProperty2); - - // Act - var result = PropertyHelper.GetVisibleProperties(type).ToArray(); - - // Assert - Assert.Equal(2, result.Length); - Assert.Equal("Id", result[0].Name); - Assert.Equal(typeof(Guid), result[0].Property.PropertyType); - Assert.Equal("Name", result[1].Name); - Assert.Equal(typeof(string), result[1].Property.PropertyType); - } - - [Fact] - public void GetVisibleProperties_NoHiddenPropertyWithTypeInfoInput() - { - // Arrange - var type = typeof(string); - - // Act - var result = PropertyHelper.GetVisibleProperties(type.GetTypeInfo()).ToArray(); - - // Assert - var property = Assert.Single(result); - Assert.Equal("Length", property.Name); - Assert.Equal(typeof(int), property.Property.PropertyType); - } - - [Fact] - public void GetVisibleProperties_HiddenPropertyWithTypeInfoInput() - { - // Arrange - var type = typeof(DerivedHiddenProperty); - - // Act - var result = PropertyHelper.GetVisibleProperties(type.GetTypeInfo()).ToArray(); - - // Assert - Assert.Equal(2, result.Length); - Assert.Equal("Id", result[0].Name); - Assert.Equal(typeof(string), result[0].Property.PropertyType); - Assert.Equal("Name", result[1].Name); - Assert.Equal(typeof(string), result[1].Property.PropertyType); - } - - [Fact] - public void GetVisibleProperties_HiddenProperty_TwoLevelsWithTypeInfoInput() - { - // Arrange - var type = typeof(DerivedHiddenProperty2); - - // Act - var result = PropertyHelper.GetVisibleProperties(type.GetTypeInfo()).ToArray(); - - // Assert - Assert.Equal(2, result.Length); - Assert.Equal("Id", result[0].Name); - Assert.Equal(typeof(Guid), result[0].Property.PropertyType); - Assert.Equal("Name", result[1].Name); - Assert.Equal(typeof(string), result[1].Property.PropertyType); - } - - [Fact] - public void MakeFastPropertySetter_SetsPropertyValues_ForPublicAndNobPublicProperties() - { - // Arrange - var instance = new BaseClass(); - var typeInfo = instance.GetType().GetTypeInfo(); - var publicProperty = typeInfo.GetDeclaredProperty("PropA"); - var protectedProperty = typeInfo.GetDeclaredProperty("PropProtected"); - var publicPropertySetter = PropertyHelper.MakeFastPropertySetter(publicProperty); - var protectedPropertySetter = PropertyHelper.MakeFastPropertySetter(protectedProperty); - - // Act - publicPropertySetter(instance, "TestPublic"); - protectedPropertySetter(instance, "TestProtected"); - - // Assert - Assert.Equal("TestPublic", instance.PropA); - Assert.Equal("TestProtected", instance.GetPropProtected()); - } - - [Fact] - public void MakeFastPropertySetter_SetsPropertyValues_ForOverridenProperties() - { - // Arrange - var instance = new DerivedClassWithOverride(); - var typeInfo = instance.GetType().GetTypeInfo(); - var property = typeInfo.GetDeclaredProperty("PropA"); - var propertySetter = PropertyHelper.MakeFastPropertySetter(property); - - // Act - propertySetter(instance, "Test value"); - - // Assert - Assert.Equal("OverridenTest value", instance.PropA); - } - - [Fact] - public void MakeFastPropertySetter_SetsPropertyValues_ForNewedProperties() - { - // Arrange - var instance = new DerivedClassWithNew(); - var typeInfo = instance.GetType().GetTypeInfo(); - var property = typeInfo.GetDeclaredProperty("PropB"); - var propertySetter = PropertyHelper.MakeFastPropertySetter(property); - - // Act - propertySetter(instance, "Test value"); - - // Assert - Assert.Equal("NewedTest value", instance.PropB); - } - - [Fact] - public void MakeFastPropertyGetter_ReferenceType_ForNullObject_Throws() - { - // Arrange - var property = PropertyHelper - .GetProperties(typeof(BaseClass)) - .Single(p => p.Name == nameof(BaseClass.PropA)); - - var accessor = PropertyHelper.MakeFastPropertyGetter(property.Property); - - // Act & Assert - Assert.Throws(() => accessor(null)); - } - - [Fact] - public void MakeFastPropertyGetter_ValueType_ForNullObject_Throws() - { - // Arrange - var property = PropertyHelper - .GetProperties(typeof(MyProperties)) - .Single(p => p.Name == nameof(MyProperties.StringProp)); - - var accessor = PropertyHelper.MakeFastPropertyGetter(property.Property); - - // Act & Assert - Assert.Throws(() => accessor(null)); - } - - [Fact] - public void MakeNullSafeFastPropertyGetter_ReferenceType_Success() - { - // Arrange - var property = PropertyHelper - .GetProperties(typeof(BaseClass)) - .Single(p => p.Name == nameof(BaseClass.PropA)); - - var accessor = PropertyHelper.MakeNullSafeFastPropertyGetter(property.Property); - - // Act - var value = accessor(new BaseClass() { PropA = "Hi" }); - - // Assert - Assert.Equal("Hi", value); - } - - [Fact] - public void MakeNullSafeFastPropertyGetter_ValueType_Success() - { - // Arrange - var property = PropertyHelper - .GetProperties(typeof(MyProperties)) - .Single(p => p.Name == nameof(MyProperties.StringProp)); - - var accessor = PropertyHelper.MakeNullSafeFastPropertyGetter(property.Property); - - // Act - var value = accessor(new MyProperties() { StringProp = "Hi" }); - - // Assert - Assert.Equal("Hi", value); - } - - [Fact] - public void MakeNullSafeFastPropertyGetter_ReferenceType_ForNullObject_ReturnsNull() - { - // Arrange - var property = PropertyHelper - .GetProperties(typeof(BaseClass)) - .Single(p => p.Name == nameof(BaseClass.PropA)); - - var accessor = PropertyHelper.MakeNullSafeFastPropertyGetter(property.Property); - - // Act - var value = accessor(null); - - // Assert - Assert.Null(value); - } - - [Fact] - public void MakeNullSafeFastPropertyGetter_ValueType_ForNullObject_ReturnsNull() - { - // Arrange - var property = PropertyHelper - .GetProperties(typeof(MyProperties)) - .Single(p => p.Name == nameof(MyProperties.StringProp)); - - var accessor = PropertyHelper.MakeNullSafeFastPropertyGetter(property.Property); - - // Act - var value = accessor(null); - - // Assert - Assert.Null(value); - } - - public static TheoryData> IgnoreCaseTestData - { - get - { - return new TheoryData> - { - { - new - { - selected = true, - SeLeCtEd = false - }, - new KeyValuePair("selected", false) - }, - { - new - { - SeLeCtEd = false, - selected = true - }, - new KeyValuePair("SeLeCtEd", true) - }, - { - new - { - SelECTeD = false, - SeLECTED = true - }, - new KeyValuePair("SelECTeD", true) - } - }; - } - } - - [Theory] - [MemberData(nameof(IgnoreCaseTestData))] - public void ObjectToDictionary_IgnoresPropertyCase(object testObject, - KeyValuePair expectedEntry) - { - // Act - var result = PropertyHelper.ObjectToDictionary(testObject); - - // Assert - var entry = Assert.Single(result); - Assert.Equal(expectedEntry, entry); - } - - [Fact] - public void ObjectToDictionary_WithNullObject_ReturnsEmptyDictionary() - { - // Arrange - object value = null; - - // Act - var dictValues = PropertyHelper.ObjectToDictionary(value); - - // Assert - Assert.NotNull(dictValues); - Assert.Equal(0, dictValues.Count); - } - - [Fact] - public void ObjectToDictionary_WithPlainObjectType_ReturnsEmptyDictionary() - { - // Arrange - var value = new object(); - - // Act - var dictValues = PropertyHelper.ObjectToDictionary(value); - - // Assert - Assert.NotNull(dictValues); - Assert.Equal(0, dictValues.Count); - } - - [Fact] - public void ObjectToDictionary_WithPrimitiveType_LooksUpPublicProperties() - { - // Arrange - var value = "test"; - - // Act - var dictValues = PropertyHelper.ObjectToDictionary(value); - - // Assert - Assert.NotNull(dictValues); - Assert.Equal(1, dictValues.Count); - Assert.Equal(4, dictValues["Length"]); - } - - [Fact] - public void ObjectToDictionary_WithAnonymousType_LooksUpProperties() - { - // Arrange - var value = new { test = "value", other = 1 }; - - // Act - var dictValues = PropertyHelper.ObjectToDictionary(value); - - // Assert - Assert.NotNull(dictValues); - Assert.Equal(2, dictValues.Count); - Assert.Equal("value", dictValues["test"]); - Assert.Equal(1, dictValues["other"]); - } - - [Fact] - public void ObjectToDictionary_ReturnsCaseInsensitiveDictionary() - { - // Arrange - var value = new { TEST = "value", oThEr = 1 }; - - // Act - var dictValues = PropertyHelper.ObjectToDictionary(value); - - // Assert - Assert.NotNull(dictValues); - Assert.Equal(2, dictValues.Count); - Assert.Equal("value", dictValues["test"]); - Assert.Equal(1, dictValues["other"]); - } - - [Fact] - public void ObjectToDictionary_ReturnsInheritedProperties() - { - // Arrange - var value = new ThreeDPoint() { X = 5, Y = 10, Z = 17 }; - - // Act - var dictValues = PropertyHelper.ObjectToDictionary(value); - - // Assert - Assert.NotNull(dictValues); - Assert.Equal(3, dictValues.Count); - Assert.Equal(5, dictValues["X"]); - Assert.Equal(10, dictValues["Y"]); - Assert.Equal(17, dictValues["Z"]); - } - - private class Point - { - public int X { get; set; } - public int Y { get; set; } - } - - private class ThreeDPoint : Point - { - public int Z { get; set; } - } - - private class Static - { - public static int Prop2 { get; set; } - public int Prop5 { get; set; } - } - - private struct MyProperties - { - public int IntProp { get; set; } - public string StringProp { get; set; } - } - - private class SetOnly - { - public int Prop2 { set { } } - public int Prop6 { get; set; } - } - - private class PrivateProperties - { - public int Prop1 { get; set; } - protected int Prop2 { get; set; } - private int Prop3 { get; set; } - } - - public class BaseClass - { - public string PropA { get; set; } - - protected string PropProtected { get; set; } - - public string GetPropProtected() - { - return PropProtected; - } - } - - public class DerivedClass : BaseClass - { - public string PropB { get; set; } - } - - public class BaseClassWithVirtual - { - public virtual string PropA { get; set; } - public string PropB { get; set; } - } - - public class DerivedClassWithNew : BaseClassWithVirtual - { - private string _value = "Newed"; - - public new string PropB - { - get { return _value; } - set { _value = "Newed" + value; } - } - } - - public class DerivedClassWithOverride : BaseClassWithVirtual - { - private string _value = "Overriden"; - - public override string PropA - { - get { return _value; } - set { _value = "Overriden" + value; } - } - } - - private class DerivedClassWithNonReadableProperties : BaseClassWithVirtual - { - public string this[int index] - { - get { return string.Empty; } - set { } - } - - public int Visible { get; set; } - - private string NotVisible { get; set; } - - public string NotVisible2 { private get; set; } - - public string NotVisible3 - { - set { } - } - - public static string NotVisible4 { get; set; } - } - - private struct MyStruct - { - public string Foo { get; set; } - } - - private class BaseHiddenProperty - { - public int Id { get; set; } - } - - private class DerivedHiddenProperty : BaseHiddenProperty - { - public new string Id { get; set; } - - public string Name { get; set; } - } - - private class DerivedHiddenProperty2 : DerivedHiddenProperty - { - public new Guid Id { get; set; } - - public new string Name { get; private set; } - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/Readme.txt b/test/Microsoft.Extensions.Internal.Test/Readme.txt deleted file mode 100644 index b818bd81..00000000 --- a/test/Microsoft.Extensions.Internal.Test/Readme.txt +++ /dev/null @@ -1,4 +0,0 @@ -NOTE: -1. The tests for 'ExceptionDetailProvider' and 'StackTraceHelper' in project 'Microsoft.Extensions.StackTrace.Sources' are located in Diagnostics - repo. This is because they refer to some packages from FileSystem repo which causes a circular reference and breaks the - build. \ No newline at end of file diff --git a/test/Microsoft.Extensions.Internal.Test/SecurityHelperTests.cs b/test/Microsoft.Extensions.Internal.Test/SecurityHelperTests.cs deleted file mode 100644 index 8e7515ad..00000000 --- a/test/Microsoft.Extensions.Internal.Test/SecurityHelperTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using System.Security.Claims; -using System.Security.Principal; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class SecurityHelperTests - { - [Fact] - public void AddingToAnonymousIdentityDoesNotKeepAnonymousIdentity() - { - var user = SecurityHelper.MergeUserPrincipal(new ClaimsPrincipal(), new GenericPrincipal(new GenericIdentity("Test1", "Alpha"), new string[0])); - - Assert.NotNull(user); - Assert.Equal("Alpha", user.Identity.AuthenticationType); - Assert.Equal("Test1", user.Identity.Name); - Assert.IsAssignableFrom(user); - Assert.IsAssignableFrom(user.Identity); - Assert.Single(user.Identities); - } - - [Fact] - public void AddingExistingIdentityChangesDefaultButPreservesPrior() - { - ClaimsPrincipal user = new GenericPrincipal(new GenericIdentity("Test1", "Alpha"), null); - - Assert.Equal("Alpha", user.Identity.AuthenticationType); - Assert.Equal("Test1", user.Identity.Name); - - user = SecurityHelper.MergeUserPrincipal(user, new GenericPrincipal(new GenericIdentity("Test2", "Beta"), new string[0])); - - Assert.Equal("Beta", user.Identity.AuthenticationType); - Assert.Equal("Test2", user.Identity.Name); - - user = SecurityHelper.MergeUserPrincipal(user, new GenericPrincipal(new GenericIdentity("Test3", "Gamma"), new string[0])); - - Assert.Equal("Gamma", user.Identity.AuthenticationType); - Assert.Equal("Test3", user.Identity.Name); - - Assert.Equal(3, user.Identities.Count()); - Assert.Equal("Test3", user.Identities.Skip(0).First().Name); - Assert.Equal("Test2", user.Identities.Skip(1).First().Name); - Assert.Equal("Test1", user.Identities.Skip(2).First().Name); - } - - [Fact] - public void AddingPreservesNewIdentitiesAndDropsEmpty() - { - var existingPrincipal = new ClaimsPrincipal(new ClaimsIdentity()); - var identityNoAuthTypeWithClaim = new ClaimsIdentity(); - identityNoAuthTypeWithClaim.AddClaim(new Claim("identityNoAuthTypeWithClaim", "yes")); - existingPrincipal.AddIdentity(identityNoAuthTypeWithClaim); - var identityEmptyWithAuthType = new ClaimsIdentity("empty"); - existingPrincipal.AddIdentity(identityEmptyWithAuthType); - - Assert.False(existingPrincipal.Identity.IsAuthenticated); - - var newPrincipal = new ClaimsPrincipal(); - var newEmptyIdentity = new ClaimsIdentity(); - var identityTwo = new ClaimsIdentity("yep"); - newPrincipal.AddIdentity(newEmptyIdentity); - newPrincipal.AddIdentity(identityTwo); - - var user = SecurityHelper.MergeUserPrincipal(existingPrincipal, newPrincipal); - - // Preserve newPrincipal order - Assert.False(user.Identity.IsAuthenticated); - Assert.Null(user.Identity.Name); - - Assert.Equal(4, user.Identities.Count()); - Assert.Equal(newEmptyIdentity, user.Identities.Skip(0).First()); - Assert.Equal(identityTwo, user.Identities.Skip(1).First()); - Assert.Equal(identityNoAuthTypeWithClaim, user.Identities.Skip(2).First()); - Assert.Equal(identityEmptyWithAuthType, user.Identities.Skip(3).First()); - - // This merge should drop newEmptyIdentity since its empty - user = SecurityHelper.MergeUserPrincipal(user, new GenericPrincipal(new GenericIdentity("Test3", "Gamma"), new string[0])); - - Assert.Equal("Gamma", user.Identity.AuthenticationType); - Assert.Equal("Test3", user.Identity.Name); - - Assert.Equal(4, user.Identities.Count()); - Assert.Equal("Test3", user.Identities.Skip(0).First().Name); - Assert.Equal(identityTwo, user.Identities.Skip(1).First()); - Assert.Equal(identityNoAuthTypeWithClaim, user.Identities.Skip(2).First()); - Assert.Equal(identityEmptyWithAuthType, user.Identities.Skip(3).First()); - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/StackTraceHelperTest.cs b/test/Microsoft.Extensions.Internal.Test/StackTraceHelperTest.cs deleted file mode 100644 index 59bd777a..00000000 --- a/test/Microsoft.Extensions.Internal.Test/StackTraceHelperTest.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.Extensions.StackTrace.Sources; -using ThrowingLibrary; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class StackTraceHelperTest - { - [Fact] - public void StackTraceHelper_IncludesLineNumbersForFiles() - { - // Arrange - Exception exception = null; - try - { - // Throwing an exception in the current assembly always seems to populate the full stack - // trace regardless of symbol type. Crossing assembly boundaries ensures PortablePdbReader gets used - // on desktop. - Thrower.Throw(); - } - catch (Exception ex) - { - exception = ex; - } - - // Act - var stackFrames = StackTraceHelper.GetFrames(exception); - - // Assert - Assert.Collection(stackFrames, - frame => - { - Assert.Contains("Thrower.cs", frame.FilePath); - Assert.Equal(17, frame.LineNumber); - }, - frame => - { - Assert.Contains("StackTraceHelperTest.cs", frame.FilePath); - }); - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/TypeNameHelperTest.cs b/test/Microsoft.Extensions.Internal.Test/TypeNameHelperTest.cs deleted file mode 100644 index 7bceed8c..00000000 --- a/test/Microsoft.Extensions.Internal.Test/TypeNameHelperTest.cs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class TypeNameHelperTest - { - [Fact] - public void Can_pretty_print_CLR_full_name() - { - // Predefined Types - Assert.Equal("int", - TypeNameHelper.GetTypeDisplayName(typeof(int))); - Assert.Equal("System.Collections.Generic.List", - TypeNameHelper.GetTypeDisplayName(typeof(List))); - Assert.Equal("System.Collections.Generic.Dictionary", - TypeNameHelper.GetTypeDisplayName(typeof(Dictionary))); - Assert.Equal("System.Collections.Generic.Dictionary>", - TypeNameHelper.GetTypeDisplayName(typeof(Dictionary>))); - Assert.Equal("System.Collections.Generic.List>", - TypeNameHelper.GetTypeDisplayName(typeof(List>))); - - // Classes inside NonGeneric class - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+A", - TypeNameHelper.GetTypeDisplayName(typeof(A))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+B", - TypeNameHelper.GetTypeDisplayName(typeof(B))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+C", - TypeNameHelper.GetTypeDisplayName(typeof(C))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+C>", - TypeNameHelper.GetTypeDisplayName(typeof(C>))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+B>", - TypeNameHelper.GetTypeDisplayName(typeof(B>))); - - // Classes inside Generic class - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+Outer+D", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.D))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+Outer+E", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.E))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+Outer+F", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.F))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+Outer+F+E>", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.F.E>))); - Assert.Equal("Microsoft.Extensions.Internal.TypeNameHelperTest+Outer+E+E>", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.E.E>))); - } - - [Fact] - public void Can_pretty_print_CLR_name() - { - // Predefined Types - Assert.Equal("int", - TypeNameHelper.GetTypeDisplayName(typeof(int), false)); - Assert.Equal("List", - TypeNameHelper.GetTypeDisplayName(typeof(List), false)); - Assert.Equal("Dictionary", - TypeNameHelper.GetTypeDisplayName(typeof(Dictionary), false)); - Assert.Equal("Dictionary>", - TypeNameHelper.GetTypeDisplayName(typeof(Dictionary>), false)); - Assert.Equal("List>", - TypeNameHelper.GetTypeDisplayName(typeof(List>), false)); - - // Classes inside NonGeneric class - Assert.Equal("A", - TypeNameHelper.GetTypeDisplayName(typeof(A), false)); - Assert.Equal("B", - TypeNameHelper.GetTypeDisplayName(typeof(B), false)); - Assert.Equal("C", - TypeNameHelper.GetTypeDisplayName(typeof(C), false)); - Assert.Equal("C>", - TypeNameHelper.GetTypeDisplayName(typeof(C>), false)); - Assert.Equal("B>", - TypeNameHelper.GetTypeDisplayName(typeof(B>), false)); - - // Classes inside Generic class - Assert.Equal("D", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.D), false)); - Assert.Equal("E", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.E), false)); - Assert.Equal("F", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.F), false)); - Assert.Equal("F>", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.F.E>), false)); - Assert.Equal("E>", - TypeNameHelper.GetTypeDisplayName(typeof(Outer.E.E>), false)); - } - - [Fact] - public void Returns_common_name_for_built_in_types() - { - Assert.Equal("bool", TypeNameHelper.GetTypeDisplayName(typeof(bool))); - Assert.Equal("byte", TypeNameHelper.GetTypeDisplayName(typeof(byte))); - Assert.Equal("char", TypeNameHelper.GetTypeDisplayName(typeof(char))); - Assert.Equal("decimal", TypeNameHelper.GetTypeDisplayName(typeof(decimal))); - Assert.Equal("double", TypeNameHelper.GetTypeDisplayName(typeof(double))); - Assert.Equal("float", TypeNameHelper.GetTypeDisplayName(typeof(float))); - Assert.Equal("int", TypeNameHelper.GetTypeDisplayName(typeof(int))); - Assert.Equal("long", TypeNameHelper.GetTypeDisplayName(typeof(long))); - Assert.Equal("object", TypeNameHelper.GetTypeDisplayName(typeof(object))); - Assert.Equal("sbyte", TypeNameHelper.GetTypeDisplayName(typeof(sbyte))); - Assert.Equal("short", TypeNameHelper.GetTypeDisplayName(typeof(short))); - Assert.Equal("string", TypeNameHelper.GetTypeDisplayName(typeof(string))); - Assert.Equal("uint", TypeNameHelper.GetTypeDisplayName(typeof(uint))); - Assert.Equal("ulong", TypeNameHelper.GetTypeDisplayName(typeof(ulong))); - Assert.Equal("ushort", TypeNameHelper.GetTypeDisplayName(typeof(ushort))); - } - private class A { } - - private class B { } - - private class C { } - - private class Outer - { - public class D { } - - public class E { } - - public class F { } - } - } -} diff --git a/test/Microsoft.Extensions.Internal.Test/WebEncodersTests.cs b/test/Microsoft.Extensions.Internal.Test/WebEncodersTests.cs deleted file mode 100644 index 5c71403f..00000000 --- a/test/Microsoft.Extensions.Internal.Test/WebEncodersTests.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Linq; -using Xunit; - -namespace Microsoft.Extensions.Internal -{ - public class WebEncodersTests - { - [Theory] - [InlineData("", 1, 0)] - [InlineData("", 0, 1)] - [InlineData("0123456789", 9, 2)] - [InlineData("0123456789", Int32.MaxValue, 2)] - [InlineData("0123456789", 9, -1)] - public void Base64UrlDecode_BadOffsets(string input, int offset, int count) - { - // Act & assert - Assert.ThrowsAny(() => - { - var retVal = WebEncoders.Base64UrlDecode(input, offset, count); - }); - } - - [Theory] - [InlineData("x")] - [InlineData("(x)")] - public void Base64UrlDecode_MalformedInput(string input) - { - // Act & assert - Assert.Throws(() => - { - var retVal = WebEncoders.Base64UrlDecode(input); - }); - } - - [Theory] - [InlineData("", "")] - [InlineData("123456qwerty++//X+/x", "123456qwerty--__X-_x")] - [InlineData("123456qwerty++//X+/xxw==", "123456qwerty--__X-_xxw")] - [InlineData("123456qwerty++//X+/xxw0=", "123456qwerty--__X-_xxw0")] - public void Base64UrlEncode_And_Decode(string base64Input, string expectedBase64Url) - { - // Arrange - byte[] input = new byte[3].Concat(Convert.FromBase64String(base64Input)).Concat(new byte[2]).ToArray(); - - // Act & assert - 1 - string actualBase64Url = WebEncoders.Base64UrlEncode(input, 3, input.Length - 5); // also helps test offsets - Assert.Equal(expectedBase64Url, actualBase64Url); - - // Act & assert - 2 - // Verify that values round-trip - byte[] roundTripped = WebEncoders.Base64UrlDecode("xx" + actualBase64Url + "yyy", 2, actualBase64Url.Length); // also helps test offsets - string roundTrippedAsBase64 = Convert.ToBase64String(roundTripped); - Assert.Equal(roundTrippedAsBase64, base64Input); - } - - [Theory] - [InlineData("", "")] - [InlineData("123456qwerty++//X+/x", "123456qwerty--__X-_x")] - [InlineData("123456qwerty++//X+/xxw==", "123456qwerty--__X-_xxw")] - [InlineData("123456qwerty++//X+/xxw0=", "123456qwerty--__X-_xxw0")] - public void Base64UrlEncode_And_Decode_WithBufferOffsets(string base64Input, string expectedBase64Url) - { - // Arrange - var input = new byte[3].Concat(Convert.FromBase64String(base64Input)).Concat(new byte[2]).ToArray(); - var buffer = new char[30]; - var output = new char[30]; - for (var i = 0; i < buffer.Length; i++) - { - buffer[i] = '^'; - output[i] = '^'; - } - - // Act 1 - var numEncodedChars = - WebEncoders.Base64UrlEncode(input, offset: 3, output: output, outputOffset: 4, count: input.Length - 5); - - // Assert 1 - var encodedString = new string(output, startIndex: 4, length: numEncodedChars); - Assert.Equal(expectedBase64Url, encodedString); - - // Act 2 - var roundTripInput = new string(output); - var roundTripped = - WebEncoders.Base64UrlDecode(roundTripInput, offset: 4, buffer: buffer, bufferOffset: 5, count: numEncodedChars); - - // Assert 2, verify that values round-trip - var roundTrippedAsBase64 = Convert.ToBase64String(roundTripped); - Assert.Equal(roundTrippedAsBase64, base64Input); - } - - [Theory] - [InlineData(0, 1, 0)] - [InlineData(0, 0, 1)] - [InlineData(10, 9, 2)] - [InlineData(10, Int32.MaxValue, 2)] - [InlineData(10, 9, -1)] - public void Base64UrlEncode_BadOffsets(int inputLength, int offset, int count) - { - // Arrange - byte[] input = new byte[inputLength]; - - // Act & assert - Assert.ThrowsAny(() => - { - var retVal = WebEncoders.Base64UrlEncode(input, offset, count); - }); - } - } -} diff --git a/test/Microsoft.Extensions.ObjectPool.Test/DefaultObjectPoolTest.cs b/test/Microsoft.Extensions.ObjectPool.Test/DefaultObjectPoolTest.cs deleted file mode 100644 index 2af8c40d..00000000 --- a/test/Microsoft.Extensions.ObjectPool.Test/DefaultObjectPoolTest.cs +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Xunit; - -namespace Microsoft.Extensions.ObjectPool.Test -{ - public class DefaultObjectPoolTest - { - [Fact] - public void DefaultObjectPool_GetAndReturnObject_SameInstance() - { - // Arrange - var pool = new DefaultObjectPool>(new ListPolicy()); - - var list1 = pool.Get(); - pool.Return(list1); - - // Act - var list2 = pool.Get(); - - // Assert - Assert.Same(list1, list2); - } - - [Fact] - public void DefaultObjectPool_CreatedByPolicy() - { - // Arrange - var pool = new DefaultObjectPool>(new ListPolicy()); - - // Act - var list = pool.Get(); - - // Assert - Assert.Equal(17, list.Capacity); - } - - [Fact] - public void DefaultObjectPool_Return_RejectedByPolicy() - { - // Arrange - var pool = new DefaultObjectPool>(new ListPolicy()); - var list1 = pool.Get(); - list1.Capacity = 20; - - // Act - pool.Return(list1); - var list2 = pool.Get(); - - // Assert - Assert.NotSame(list1, list2); - } - - private class ListPolicy : IPooledObjectPolicy> - { - public List Create() - { - return new List(17); - } - - public bool Return(List obj) - { - return obj.Capacity == 17; - } - } - } -} diff --git a/test/Microsoft.Extensions.ObjectPool.Test/Microsoft.Extensions.ObjectPool.Test.csproj b/test/Microsoft.Extensions.ObjectPool.Test/Microsoft.Extensions.ObjectPool.Test.csproj deleted file mode 100755 index 619976a9..00000000 --- a/test/Microsoft.Extensions.ObjectPool.Test/Microsoft.Extensions.ObjectPool.Test.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - netcoreapp2.0;net461 - netcoreapp2.0 - - - - - - - diff --git a/test/Microsoft.Extensions.Primitives.Tests/ChangeTokenTest.cs b/test/Microsoft.Extensions.Primitives.Tests/ChangeTokenTest.cs deleted file mode 100644 index d6120743..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/ChangeTokenTest.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace Microsoft.Extensions.Primitives -{ - public class ChangeTokenTests - { - public class TestChangeToken : IChangeToken - { - private Action _callback; - - public bool ActiveChangeCallbacks { get; set; } - public bool HasChanged { get; set; } - - public IDisposable RegisterChangeCallback(Action callback, object state) - { - _callback = () => callback(state); - return null; - } - - public void Changed() - { - HasChanged = true; - _callback(); - } - } - - [Fact] - public void HasChangeFiresChange() - { - var token = new TestChangeToken(); - bool fired = false; - ChangeToken.OnChange(() => token, () => fired = true); - Assert.False(fired); - token.Changed(); - Assert.True(fired); - } - - [Fact] - public void ChangesFireAfterExceptions() - { - TestChangeToken token = null; - var count = 0; - ChangeToken.OnChange(() => token = new TestChangeToken(), () => - { - count++; - throw new Exception(); - }); - Assert.Throws(() => token.Changed()); - Assert.Equal(1, count); - Assert.Throws(() => token.Changed()); - Assert.Equal(2, count); - } - - [Fact] - public void HasChangeFiresChangeWithState() - { - var token = new TestChangeToken(); - object state = new object(); - object callbackState = null; - ChangeToken.OnChange(() => token, s => callbackState = s, state); - Assert.Null(callbackState); - token.Changed(); - Assert.Equal(state, callbackState); - } - - [Fact] - public void ChangesFireAfterExceptionsWithState() - { - TestChangeToken token = null; - var count = 0; - object state = new object(); - object callbackState = null; - ChangeToken.OnChange(() => token = new TestChangeToken(), s => - { - callbackState = s; - count++; - throw new Exception(); - }, state); - Assert.Throws(() => token.Changed()); - Assert.Equal(1, count); - Assert.NotNull(callbackState); - Assert.Throws(() => token.Changed()); - Assert.Equal(2, count); - Assert.NotNull(callbackState); - } - } -} diff --git a/test/Microsoft.Extensions.Primitives.Tests/CompositeChangeTokenTest.cs b/test/Microsoft.Extensions.Primitives.Tests/CompositeChangeTokenTest.cs deleted file mode 100644 index 124e3851..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/CompositeChangeTokenTest.cs +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Moq; -using Xunit; - -namespace Microsoft.Extensions.Primitives -{ - public class CompositeChangeTokenTest - { - [Fact] - public void RegisteredCallbacks_AreInvokedExactlyOnce() - { - // Arrange - var firstCancellationTokenSource = new CancellationTokenSource(); - var secondCancellationTokenSource = new CancellationTokenSource(); - var thirdCancellationTokenSource = new CancellationTokenSource(); - var firstCancellationToken = firstCancellationTokenSource.Token; - var secondCancellationToken = secondCancellationTokenSource.Token; - var thirdCancellationToken = thirdCancellationTokenSource.Token; - - var firstCancellationChangeToken = new CancellationChangeToken(firstCancellationToken); - var secondCancellationChangeToken = new CancellationChangeToken(secondCancellationToken); - var thirdCancellationChangeToken = new CancellationChangeToken(thirdCancellationToken); - - var compositeChangeToken = new CompositeChangeToken(new List { firstCancellationChangeToken, secondCancellationChangeToken, thirdCancellationChangeToken }); - var count1 = 0; - var count2 = 0; - compositeChangeToken.RegisterChangeCallback(_ => count1++, null); - compositeChangeToken.RegisterChangeCallback(_ => count2++, null); - - // Act - firstCancellationTokenSource.Cancel(); - secondCancellationTokenSource.Cancel(); - - // Assert - Assert.Equal(1, count1); - Assert.Equal(1, count2); - } - - [Fact] - public void HasChanged_IsTrue_IfAnyTokenHasChanged() - { - // Arrange - var firstChangeToken = new Mock(); - var secondChangeToken = new Mock(); - var thirdChangeToken = new Mock(); - - secondChangeToken.Setup(t => t.HasChanged).Returns(true); - - // Act - var compositeChangeToken = new CompositeChangeToken(new List { firstChangeToken.Object, secondChangeToken.Object, thirdChangeToken.Object }); - - // Assert - Assert.True(compositeChangeToken.HasChanged); - } - - [Fact] - public void HasChanged_IsFalse_IfNoTokenHasChanged() - { - // Arrange - var firstChangeToken = new Mock(); - var secondChangeToken = new Mock(); - - // Act - var compositeChangeToken = new CompositeChangeToken(new List { firstChangeToken.Object, secondChangeToken.Object }); - - // Assert - Assert.False(compositeChangeToken.HasChanged); - } - - [Fact] - public void ActiveChangeCallbacks_IsTrue_IfAnyTokenHasActiveChangeCallbacks() - { - // Arrange - var firstChangeToken = new Mock(); - var secondChangeToken = new Mock(); - var thirdChangeToken = new Mock(); - - secondChangeToken.Setup(t => t.ActiveChangeCallbacks).Returns(true); - - var compositeChangeToken = new CompositeChangeToken(new List { firstChangeToken.Object, secondChangeToken.Object, thirdChangeToken.Object }); - - // Act & Assert - Assert.True(compositeChangeToken.ActiveChangeCallbacks); - } - - [Fact] - public void ActiveChangeCallbacks_IsFalse_IfNoTokenHasActiveChangeCallbacks() - { - // Arrange - var firstChangeToken = new Mock(); - var secondChangeToken = new Mock(); - - var compositeChangeToken = new CompositeChangeToken(new List { firstChangeToken.Object, secondChangeToken.Object }); - - // Act & Assert - Assert.False(compositeChangeToken.ActiveChangeCallbacks); - } - - [Fact] - public async Task RegisteredCallbackGetsInvokedExactlyOnce_WhenMultipleConcurrentChangeEventsOccur() - { - // Arrange - var event1 = new ManualResetEvent(false); - var event2 = new ManualResetEvent(false); - var event3 = new ManualResetEvent(false); - - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - var cancellationChangeToken = new CancellationChangeToken(cancellationToken); - var count = 0; - Action callback = _ => - { - count++; - event3.Set(); - event1.WaitOne(5000); - }; - - var compositeChangeToken = new CompositeChangeToken(new List { cancellationChangeToken }); - compositeChangeToken.RegisterChangeCallback(callback, null); - - // Act - var firstChange = Task.Run(() => - { - event2.WaitOne(5000); - cancellationTokenSource.Cancel(); - }); - var secondChange = Task.Run(() => - { - event3.WaitOne(5000); - cancellationTokenSource.Cancel(); - event1.Set(); - }); - - event2.Set(); - - await Task.WhenAll(firstChange, secondChange); - - // Assert - Assert.Equal(1, count); - } - } -} diff --git a/test/Microsoft.Extensions.Primitives.Tests/InplaceStringBuilderTest.cs b/test/Microsoft.Extensions.Primitives.Tests/InplaceStringBuilderTest.cs deleted file mode 100644 index b0c7c5b1..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/InplaceStringBuilderTest.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using Microsoft.Extensions.Primitives; -using Xunit; - -namespace Microsoft.AspNetCore.Http.Tests.Internal -{ - public class InplaceStringBuilderTest - { - [Fact] - public void ToString_ReturnsStringWithAllAppendedValues() - { - var s1 = "123"; - var c1 = '4'; - var s2 = "56789"; - var seg = new StringSegment("890123", 2, 2); - - var formatter = new InplaceStringBuilder(); - formatter.Capacity += s1.Length + 1 + s2.Length + seg.Length; - formatter.Append(s1); - formatter.Append(c1); - formatter.Append(s2, 0, 2); - formatter.Append(s2, 2, 2); - formatter.Append(s2, 4, 1); - formatter.Append(seg); - Assert.Equal("12345678901", formatter.ToString()); - } - - [Fact] - public void Build_ThrowsIfNotEnoughWritten() - { - var formatter = new InplaceStringBuilder(5); - formatter.Append("123"); - var exception = Assert.Throws(() => formatter.ToString()); - Assert.Equal("Entire reserved capacity was not used. Capacity: '5', written '3'.", exception.Message); - } - - [Fact] - public void Capacity_ThrowsIfAppendWasCalled() - { - var formatter = new InplaceStringBuilder(3); - formatter.Append("123"); - - var exception = Assert.Throws(() => formatter.Capacity = 5); - Assert.Equal("Cannot change capacity after write started.", exception.Message); - } - - [Fact] - public void Append_ThrowsIfNotEnoughSpace() - { - var formatter = new InplaceStringBuilder(1); - - var exception = Assert.Throws(() => formatter.Append("123")); - Assert.Equal("Not enough capacity to write '3' characters, only '1' left.", exception.Message); - } - } -} diff --git a/test/Microsoft.Extensions.Primitives.Tests/Microsoft.Extensions.Primitives.Tests.csproj b/test/Microsoft.Extensions.Primitives.Tests/Microsoft.Extensions.Primitives.Tests.csproj deleted file mode 100755 index faa1cc70..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/Microsoft.Extensions.Primitives.Tests.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - netcoreapp2.0;net461 - netcoreapp2.0 - - - - - - - diff --git a/test/Microsoft.Extensions.Primitives.Tests/StringSegmentTest.cs b/test/Microsoft.Extensions.Primitives.Tests/StringSegmentTest.cs deleted file mode 100644 index 2dd5507c..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/StringSegmentTest.cs +++ /dev/null @@ -1,903 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Xunit; - -namespace Microsoft.Extensions.Primitives -{ - public class StringSegmentTest - { - [Fact] - public void StringSegment_Empty() - { - // Arrange & Act - var segment = StringSegment.Empty; - - // Assert - Assert.True(segment.HasValue); - Assert.Same(string.Empty, segment.Value); - Assert.Equal(0, segment.Offset); - Assert.Equal(0, segment.Length); - } - - [Fact] - public void StringSegment_ImplicitConvertFromString() - { - StringSegment segment = "Hello"; - - Assert.True(segment.HasValue); - Assert.Equal(0, segment.Offset); - Assert.Equal(5, segment.Length); - Assert.Equal("Hello", segment.Value); - } - - [Fact] - public void StringSegment_StringCtor_AllowsNullBuffers() - { - // Arrange & Act - var segment = new StringSegment(null); - - // Assert - Assert.False(segment.HasValue); - Assert.Equal(0, segment.Offset); - Assert.Equal(0, segment.Length); - } - - [Fact] - public void StringSegmentConstructor_NullBuffer_Throws() - { - // Arrange, Act and Assert - var exception = Assert.Throws(() => new StringSegment(null, 0, 0)); - Assert.Contains("buffer", exception.Message); - } - - [Fact] - public void StringSegmentConstructor_NegativeOffset_Throws() - { - // Arrange, Act and Assert - var exception = Assert.Throws(() => new StringSegment("", -1, 0)); - Assert.Contains("offset", exception.Message); - } - - [Fact] - public void StringSegmentConstructor_NegativeLength_Throws() - { - // Arrange, Act and Assert - var exception = Assert.Throws(() => new StringSegment("", 0, -1)); - Assert.Contains("length", exception.Message); - } - - [Theory] - [InlineData(0, 10)] - [InlineData(10, 0)] - [InlineData(5, 5)] - [InlineData(int.MaxValue, int.MaxValue)] - public void StringSegmentConstructor_OffsetOrLengthOutOfBounds_Throws(int offset, int length) - { - // Arrange, Act and Assert - Assert.Throws(() => new StringSegment("lengthof9", offset, length)); - } - - [Theory] - [InlineData("", 0, 0)] - [InlineData("abc", 2, 0)] - public void StringSegmentConstructor_AllowsEmptyBuffers(string text, int offset, int length) - { - // Arrange & Act - var segment = new StringSegment(text, offset, length); - - // Assert - Assert.True(segment.HasValue); - Assert.Equal(offset, segment.Offset); - Assert.Equal(length, segment.Length); - } - - [Fact] - public void StringSegment_StringCtor_InitializesValuesCorrectly() - { - // Arrange - var buffer = "Hello world!"; - - // Act - var segment = new StringSegment(buffer); - - // Assert - Assert.True(segment.HasValue); - Assert.Equal(0, segment.Offset); - Assert.Equal(buffer.Length, segment.Length); - } - - [Fact] - public void StringSegment_Value_Valid() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var value = segment.Value; - - // Assert - Assert.Equal("ello", value); - } - - [Fact] - public void StringSegment_Value_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act - var value = segment.Value; - - // Assert - Assert.Null(value); - } - - [Fact] - public void StringSegment_HasValue_Valid() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var hasValue = segment.HasValue; - - // Assert - Assert.True(hasValue); - } - - [Fact] - public void StringSegment_HasValue_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act - var hasValue = segment.HasValue; - - // Assert - Assert.False(hasValue); - } - - [Theory] - [InlineData("a", 0, 1, 0, 'a')] - [InlineData("abc", 1, 1, 0, 'b')] - [InlineData("abcdef", 1, 4, 0, 'b')] - [InlineData("abcdef", 1, 4, 1, 'c')] - [InlineData("abcdef", 1, 4, 2, 'd')] - [InlineData("abcdef", 1, 4, 3, 'e')] - public void StringSegment_Indexer_InRange(string value, int offset, int length, int index, char expected) - { - var segment = new StringSegment(value, offset, length); - - var result = segment[index]; - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("", 0, 0, 0)] - [InlineData("a", 0, 1, -1)] - [InlineData("a", 0, 1, 1)] - public void StringSegment_Indexer_OutOfRangeThrows(string value, int offset, int length, int index) - { - var segment = new StringSegment(value, offset, length); - - Assert.Throws(() => segment[index]); - } - - public static TheoryData EndsWithData - { - get - { - // candidate / comparer / expected result - return new TheoryData() - { - { "Hello", StringComparison.Ordinal, false }, - { "ello ", StringComparison.Ordinal, false }, - { "ll", StringComparison.Ordinal, false }, - { "ello", StringComparison.Ordinal, true }, - { "llo", StringComparison.Ordinal, true }, - { "lo", StringComparison.Ordinal, true }, - { "o", StringComparison.Ordinal, true }, - { string.Empty, StringComparison.Ordinal, true }, - { "eLLo", StringComparison.Ordinal, false }, - { "eLLo", StringComparison.OrdinalIgnoreCase, true }, - }; - } - } - - [Theory] - [MemberData(nameof(EndsWithData))] - public void StringSegment_EndsWith_Valid(string candidate, StringComparison comparison, bool expectedResult) - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.EndsWith(candidate, comparison); - - // Assert - Assert.Equal(expectedResult, result); - } - - [Fact] - public void StringSegment_EndsWith_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act - var result = segment.EndsWith(string.Empty, StringComparison.Ordinal); - - // Assert - Assert.False(result); - } - - public static TheoryData StartsWithData - { - get - { - // candidate / comparer / expected result - return new TheoryData() - { - { "Hello", StringComparison.Ordinal, false }, - { "ello ", StringComparison.Ordinal, false }, - { "ll", StringComparison.Ordinal, false }, - { "ello", StringComparison.Ordinal, true }, - { "ell", StringComparison.Ordinal, true }, - { "el", StringComparison.Ordinal, true }, - { "e", StringComparison.Ordinal, true }, - { string.Empty, StringComparison.Ordinal, true }, - { "eLLo", StringComparison.Ordinal, false }, - { "eLLo", StringComparison.OrdinalIgnoreCase, true }, - }; - } - } - - [Theory] - [MemberData(nameof(StartsWithData))] - public void StringSegment_StartsWith_Valid(string candidate, StringComparison comparison, bool expectedResult) - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.StartsWith(candidate, comparison); - - // Assert - Assert.Equal(expectedResult, result); - } - - [Fact] - public void StringSegment_StartsWith_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act - var result = segment.StartsWith(string.Empty, StringComparison.Ordinal); - - // Assert - Assert.False(result); - } - - public static TheoryData EqualsStringData - { - get - { - // candidate / comparer / expected result - return new TheoryData() - { - { "eLLo", StringComparison.OrdinalIgnoreCase, true }, - { "eLLo", StringComparison.Ordinal, false }, - }; - } - } - - [Theory] - [MemberData(nameof(EqualsStringData))] - public void StringSegment_Equals_String_Valid(string candidate, StringComparison comparison, bool expectedResult) - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.Equals(candidate, comparison); - - // Assert - Assert.Equal(expectedResult, result); - } - - [Fact] - public void StringSegment_StaticEquals_Valid() - { - var segment1 = new StringSegment("My Car Is Cool", 3, 3); - var segment2 = new StringSegment("Your Carport is blue", 5, 3); - - Assert.True(StringSegment.Equals(segment1, segment2)); - } - - [Fact] - public void StringSegment_StaticEquals_Invalid() - { - var segment1 = new StringSegment("My Car Is Cool", 3, 4); - var segment2 = new StringSegment("Your Carport is blue", 5, 4); - - Assert.False(StringSegment.Equals(segment1, segment2)); - } - - [Fact] - public void StringSegment_IsNullOrEmpty_Valid() - { - Assert.True(StringSegment.IsNullOrEmpty(null)); - Assert.True(StringSegment.IsNullOrEmpty(string.Empty)); - Assert.True(StringSegment.IsNullOrEmpty(new StringSegment(null))); - Assert.True(StringSegment.IsNullOrEmpty(new StringSegment(string.Empty))); - Assert.True(StringSegment.IsNullOrEmpty(StringSegment.Empty)); - Assert.True(StringSegment.IsNullOrEmpty(new StringSegment(string.Empty, 0, 0))); - Assert.True(StringSegment.IsNullOrEmpty(new StringSegment("Hello", 0, 0))); - Assert.True(StringSegment.IsNullOrEmpty(new StringSegment("Hello", 3, 0))); - } - - [Fact] - public void StringSegment_IsNullOrEmpty_Invalid() - { - Assert.False(StringSegment.IsNullOrEmpty("A")); - Assert.False(StringSegment.IsNullOrEmpty("ABCDefg")); - Assert.False(StringSegment.IsNullOrEmpty(new StringSegment("A", 0 , 1))); - Assert.False(StringSegment.IsNullOrEmpty(new StringSegment("ABCDefg", 3, 2))); - } - - public static TheoryData GetHashCode_ReturnsSameValueForEqualSubstringsData - { - get - { - return new TheoryData - { - { default(StringSegment), default(StringSegment) }, - { default(StringSegment), new StringSegment() }, - { new StringSegment("Test123", 0, 0), new StringSegment(string.Empty) }, - { new StringSegment("C`est si bon", 2, 3), new StringSegment("Yesterday", 1, 3) }, - { new StringSegment("Hello", 1, 4), new StringSegment("Hello world", 1, 4) }, - { new StringSegment("Hello"), new StringSegment("Hello", 0, 5) }, - }; - } - } - - [Theory] - [MemberData(nameof(GetHashCode_ReturnsSameValueForEqualSubstringsData))] - public void GetHashCode_ReturnsSameValueForEqualSubstrings(StringSegment segment1, StringSegment segment2) - { - // Act - var hashCode1 = segment1.GetHashCode(); - var hashCode2 = segment2.GetHashCode(); - - // Assert - Assert.Equal(hashCode1, hashCode2); - } - - public static TheoryData GetHashCode_ReturnsDifferentValuesForInequalSubstringsData - { - get - { - var testString = "Test123"; - return new TheoryData - { - { new StringSegment(testString, 0, 1), new StringSegment(string.Empty) }, - { new StringSegment(testString, 0, 1), new StringSegment(testString, 1, 1) }, - { new StringSegment(testString, 1, 2), new StringSegment(testString, 1, 3) }, - { new StringSegment(testString, 0, 4), new StringSegment("TEST123", 0, 4) }, - }; - } - } - - [Theory] - [MemberData(nameof(GetHashCode_ReturnsDifferentValuesForInequalSubstringsData))] - public void GetHashCode_ReturnsDifferentValuesForInequalSubstrings( - StringSegment segment1, - StringSegment segment2) - { - // Act - var hashCode1 = segment1.GetHashCode(); - var hashCode2 = segment2.GetHashCode(); - - // Assert - Assert.NotEqual(hashCode1, hashCode2); - } - - [Fact] - public void StringSegment_EqualsString_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act - var result = segment.Equals(string.Empty, StringComparison.Ordinal); - - // Assert - Assert.False(result); - } - - public static TheoryData DefaultStringSegmentEqualsStringSegmentData - { - get - { - // candidate - return new TheoryData() - { - { default(StringSegment) }, - { new StringSegment() }, - }; - } - } - - [Theory] - [MemberData(nameof(DefaultStringSegmentEqualsStringSegmentData))] - public void DefaultStringSegment_EqualsStringSegment(StringSegment candidate) - { - // Arrange - var segment = default(StringSegment); - - // Act - var result = segment.Equals(candidate, StringComparison.Ordinal); - - // Assert - Assert.True(result); - } - - public static TheoryData DefaultStringSegmentDoesNotEqualStringSegmentData - { - get - { - // candidate - return new TheoryData() - { - { new StringSegment("Hello, World!", 1, 4) }, - { new StringSegment("Hello", 1, 0) }, - { new StringSegment(string.Empty) }, - }; - } - } - - [Theory] - [MemberData(nameof(DefaultStringSegmentDoesNotEqualStringSegmentData))] - public void DefaultStringSegment_DoesNotEqualStringSegment(StringSegment candidate) - { - // Arrange - var segment = default(StringSegment); - - // Act - var result = segment.Equals(candidate, StringComparison.Ordinal); - - // Assert - Assert.False(result); - } - - public static TheoryData DefaultStringSegmentDoesNotEqualStringData - { - get - { - // candidate - return new TheoryData() - { - { string.Empty }, - { "Hello, World!" }, - }; - } - } - - [Theory] - [MemberData(nameof(DefaultStringSegmentDoesNotEqualStringData))] - public void DefaultStringSegment_DoesNotEqualString(string candidate) - { - // Arrange - var segment = default(StringSegment); - - // Act - var result = segment.Equals(candidate, StringComparison.Ordinal); - - // Assert - Assert.False(result); - } - - public static TheoryData EqualsStringSegmentData - { - get - { - // candidate / comparer / expected result - return new TheoryData() - { - { new StringSegment("Hello, World!", 1, 4), StringComparison.Ordinal, true }, - { new StringSegment("HELlo, World!", 1, 4), StringComparison.Ordinal, false }, - { new StringSegment("HELlo, World!", 1, 4), StringComparison.OrdinalIgnoreCase, true }, - { new StringSegment("ello, World!", 0, 4), StringComparison.Ordinal, true }, - { new StringSegment("ello, World!", 0, 3), StringComparison.Ordinal, false }, - { new StringSegment("ello, World!", 1, 3), StringComparison.Ordinal, false }, - }; - } - } - - [Theory] - [MemberData(nameof(EqualsStringSegmentData))] - public void StringSegment_Equals_StringSegment_Valid(StringSegment candidate, StringComparison comparison, bool expectedResult) - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.Equals(candidate, comparison); - - // Assert - Assert.Equal(expectedResult, result); - } - - [Fact] - public void StringSegment_EqualsStringSegment_Invalid() - { - // Arrange - var segment = new StringSegment(); - var candidate = new StringSegment("Hello, World!", 3, 2); - - // Act - var result = segment.Equals(candidate, StringComparison.Ordinal); - - // Assert - Assert.False(result); - } - - [Fact] - public void StringSegment_SubstringOffset_Valid() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.Substring(offset: 1); - - // Assert - Assert.Equal("llo", result); - } - - [Fact] - public void StringSegment_Substring_Valid() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.Substring(offset: 1, length: 2); - - // Assert - Assert.Equal("ll", result); - } - - [Fact] - public void StringSegment_Substring_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act & Assert - Assert.Throws(() => segment.Substring(0, 0)); - } - - [Fact] - public void StringSegment_Substring_InvalidOffset() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act & Assert - Assert.Throws(() => segment.Substring(-1, 1)); - } - - [Fact] - public void StringSegment_Substring_InvalidOffsetAndLength() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act & Assert - Assert.Throws(() => segment.Substring(2, 3)); - } - - [Fact] - public void StringSegment_SubsegmentOffset_Valid() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.Subsegment(offset: 1); - - // Assert - Assert.Equal(new StringSegment("Hello, World!", 2, 3), result); - Assert.Equal("llo", result.Value); - } - - [Fact] - public void StringSegment_Subsegment_Valid() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 4); - - // Act - var result = segment.Subsegment(offset: 1, length: 2); - - // Assert - Assert.Equal(new StringSegment("Hello, World!", 2, 2), result); - Assert.Equal("ll", result.Value); - } - - [Fact] - public void StringSegment_Subsegment_Invalid() - { - // Arrange - var segment = new StringSegment(); - - // Act & Assert - Assert.Throws(() => segment.Subsegment(0, 0)); - } - - [Fact] - public void StringSegment_Subsegment_InvalidOffset() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act & Assert - Assert.Throws(() => segment.Subsegment(-1, 1)); - } - - [Fact] - public void StringSegment_Subsegment_InvalidOffsetAndLength() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act & Assert - Assert.Throws(() => segment.Subsegment(2, 3)); - } - - [Fact] - public void IndexOf_ComputesIndex_RelativeToTheCurrentSegment() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 10); - - // Act - var result = segment.IndexOf(','); - - // Assert - Assert.Equal(4, result); - } - - [Fact] - public void IndexOf_ReturnsMinusOne_IfElementNotInSegment() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act - var result = segment.IndexOf(','); - - // Assert - Assert.Equal(-1, result); - } - - [Fact] - public void IndexOf_SkipsANumberOfCaracters_IfStartIsProvided() - { - // Arrange - const string buffer = "Hello, World!, Hello people!"; - var segment = new StringSegment(buffer, 3, buffer.Length - 3); - - // Act - var result = segment.IndexOf('!', 15); - - // Assert - Assert.Equal(buffer.Length - 4, result); - } - - [Fact] - public void IndexOf_SearchOnlyInsideTheRange_IfStartAndCountAreProvided() - { - // Arrange - const string buffer = "Hello, World!, Hello people!"; - var segment = new StringSegment(buffer, 3, buffer.Length - 3); - - // Act - var result = segment.IndexOf('!', 15, 5); - - // Assert - Assert.Equal(-1, result); - } - - [Fact] - public void IndexOfAny_ComputesIndex_RelativeToTheCurrentSegment() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 10); - - // Act - var result = segment.IndexOfAny(new[] { ',' }); - - // Assert - Assert.Equal(4, result); - } - - [Fact] - public void IndexOfAny_ReturnsMinusOne_IfElementNotInSegment() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act - var result = segment.IndexOfAny(new[] { ',' }); - - // Assert - Assert.Equal(-1, result); - } - - [Fact] - public void IndexOfAny_SkipsANumberOfCaracters_IfStartIsProvided() - { - // Arrange - const string buffer = "Hello, World!, Hello people!"; - var segment = new StringSegment(buffer, 3, buffer.Length - 3); - - // Act - var result = segment.IndexOfAny(new[] { '!' }, 15); - - // Assert - Assert.Equal(buffer.Length - 4, result); - } - - [Fact] - public void IndexOfAny_SearchOnlyInsideTheRange_IfStartAndCountAreProvided() - { - // Arrange - const string buffer = "Hello, World!, Hello people!"; - var segment = new StringSegment(buffer, 3, buffer.Length - 3); - - // Act - var result = segment.IndexOfAny(new[] { '!' }, 15, 5); - - // Assert - Assert.Equal(-1, result); - } - - [Fact] - public void LastIndexOf_ComputesIndex_RelativeToTheCurrentSegment() - { - // Arrange - var segment = new StringSegment("Hello, World, how, are, you!", 1, 14); - - // Act - var result = segment.LastIndexOf(','); - - // Assert - Assert.Equal(11, result); - } - - [Fact] - public void LastIndexOf_ReturnsMinusOne_IfElementNotInSegment() - { - // Arrange - var segment = new StringSegment("Hello, World!", 1, 3); - - // Act - var result = segment.LastIndexOf(','); - - // Assert - Assert.Equal(-1, result); - } - - [Fact] - public void Value_DoesNotAllocateANewString_IfTheSegmentContainsTheWholeBuffer() - { - // Arrange - const string buffer = "Hello, World!"; - var segment = new StringSegment(buffer); - - // Act - var result = segment.Value; - - // Assert - Assert.Same(buffer, result); - } - - [Fact] - public void StringSegment_CreateEmptySegment() - { - // Arrange - var segment = new StringSegment("//", 1, 0); - - // Assert - Assert.True(segment.HasValue); - } - - [Theory] - [InlineData(" value", 0, 8, "value")] - [InlineData("value ", 0, 8, "value")] - [InlineData("\t\tvalue", 0, 7, "value")] - [InlineData("value\t\t", 0, 7, "value")] - [InlineData("\t\tvalue \t a", 1, 8, "value")] - [InlineData(" a ", 0, 9, "a")] - [InlineData("value\t value value ", 2, 13, "lue\t value v")] - [InlineData("\x0009value \x0085", 0, 8, "value")] - [InlineData(" \f\t\u000B\u2028Hello \u2029\n\t ", 1, 13, "Hello")] - [InlineData(" ", 1, 2, "")] - [InlineData("\t\t\t", 0, 3, "")] - [InlineData("\n\n\t\t \t", 2, 3, "")] - [InlineData(" ", 1, 0, "")] - [InlineData("", 0, 0, "")] - public void Trim_RemovesLeadingAndTrailingWhitespaces(string value, int start, int length, string expected) - { - // Arrange - var segment = new StringSegment(value, start, length); - - // Act - var actual = segment.Trim(); - - // Assert - Assert.Equal(expected, actual.Value); - } - - [Theory] - [InlineData(" value", 0, 8, "value")] - [InlineData("value ", 0, 8, "value ")] - [InlineData("\t\tvalue", 0, 7, "value")] - [InlineData("value\t\t", 0, 7, "value\t\t")] - [InlineData("\t\tvalue \t a", 1, 8, "value \t")] - [InlineData(" a ", 0, 9, "a ")] - [InlineData("value\t value value ", 2, 13, "lue\t value v")] - [InlineData("\x0009value \x0085", 0, 8, "value \x0085")] - [InlineData(" \f\t\u000B\u2028Hello \u2029\n\t ", 1, 13, "Hello \u2029\n\t")] - [InlineData(" ", 1, 2, "")] - [InlineData("\t\t\t", 0, 3, "")] - [InlineData("\n\n\t\t \t", 2, 3, "")] - [InlineData(" ", 1, 0, "")] - [InlineData("", 0, 0, "")] - public void TrimStart_RemovesLeadingWhitespaces(string value, int start, int length, string expected) - { - // Arrange - var segment = new StringSegment(value, start, length); - - // Act - var actual = segment.TrimStart(); - - // Assert - Assert.Equal(expected, actual.Value); - } - - [Theory] - [InlineData(" value", 0, 8, " value")] - [InlineData("value ", 0, 8, "value")] - [InlineData("\t\tvalue", 0, 7, "\t\tvalue")] - [InlineData("value\t\t", 0, 7, "value")] - [InlineData("\t\tvalue \t a", 1, 8, "\tvalue")] - [InlineData(" a ", 0, 9, " a")] - [InlineData("value\t value value ", 2, 13, "lue\t value v")] - [InlineData("\x0009value \x0085", 0, 8, "\x0009value")] - [InlineData(" \f\t\u000B\u2028Hello \u2029\n\t ", 1, 13, "\f\t\u000B\u2028Hello")] - [InlineData(" ", 1, 2, "")] - [InlineData("\t\t\t", 0, 3, "")] - [InlineData("\n\n\t\t \t", 2, 3, "")] - [InlineData(" ", 1, 0, "")] - [InlineData("", 0, 0, "")] - public void TrimEnd_RemovesTrailingWhitespaces(string value, int start, int length, string expected) - { - // Arrange - var segment = new StringSegment(value, start, length); - - // Act - var actual = segment.TrimEnd(); - - // Assert - Assert.Equal(expected, actual.Value); - } - } -} diff --git a/test/Microsoft.Extensions.Primitives.Tests/StringTokenizerTest.cs b/test/Microsoft.Extensions.Primitives.Tests/StringTokenizerTest.cs deleted file mode 100644 index 0bc218b5..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/StringTokenizerTest.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using Xunit; - -namespace Microsoft.Extensions.Primitives -{ - public class StringTokenizerTest - { - [Fact] - public void TokenizerReturnsEmptySequenceForNullValues() - { - // Arrange - var stringTokenizer = new StringTokenizer(); - var enumerator = stringTokenizer.GetEnumerator(); - - // Act - var next = enumerator.MoveNext(); - - // Assert - Assert.False(next); - } - - [Theory] - [InlineData("", new[] { "" })] - [InlineData("a", new[] { "a" })] - [InlineData("abc", new[] { "abc" })] - [InlineData("a,b", new[] { "a", "b" })] - [InlineData("a,,b", new[] { "a", "", "b" })] - [InlineData(",a,b", new[] { "", "a", "b" })] - [InlineData(",,a,b", new[] { "", "", "a", "b" })] - [InlineData("a,b,", new[] { "a", "b", "" })] - [InlineData("a,b,,", new[] { "a", "b", "", "" })] - [InlineData("ab,cde,efgh", new[] { "ab", "cde", "efgh" })] - public void Tokenizer_ReturnsSequenceOfValues(string value, string[] expected) - { - // Arrange - var tokenizer = new StringTokenizer(value, new [] { ',' }); - - // Act - var result = tokenizer.Select(t => t.Value).ToArray(); - - // Assert - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("", new[] { "" })] - [InlineData("a", new[] { "a" })] - [InlineData("abc", new[] { "abc" })] - [InlineData("a.b", new[] { "a", "b" })] - [InlineData("a,b", new[] { "a", "b" })] - [InlineData("a.b,c", new[] { "a", "b", "c" })] - [InlineData("a,b.c", new[] { "a", "b", "c" })] - [InlineData("ab.cd,ef", new[] { "ab", "cd", "ef" })] - [InlineData("ab,cd.ef", new[] { "ab", "cd", "ef" })] - [InlineData(",a.b", new[] { "", "a", "b" })] - [InlineData(".a,b", new[] { "", "a", "b" })] - [InlineData(".,a.b", new[] { "", "", "a", "b" })] - [InlineData(",.a,b", new[] { "", "", "a", "b" })] - [InlineData("a.b,", new[] { "a", "b", "" })] - [InlineData("a,b.", new[] { "a", "b", "" })] - [InlineData("a.b,.", new[] { "a", "b", "", "" })] - [InlineData("a,b.,", new[] { "a", "b", "", "" })] - public void Tokenizer_SupportsMultipleSeparators(string value, string[] expected) - { - // Arrange - var tokenizer = new StringTokenizer(value, new[] { '.', ',' }); - - // Act - var result = tokenizer.Select(t => t.Value).ToArray(); - - // Assert - Assert.Equal(expected, result); - } - } -} diff --git a/test/Microsoft.Extensions.Primitives.Tests/StringValuesTests.cs b/test/Microsoft.Extensions.Primitives.Tests/StringValuesTests.cs deleted file mode 100644 index 5267cf2d..00000000 --- a/test/Microsoft.Extensions.Primitives.Tests/StringValuesTests.cs +++ /dev/null @@ -1,461 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Xunit; - -namespace Microsoft.Extensions.Primitives -{ - public class StringValuesTests - { - public static TheoryData DefaultOrNullStringValues - { - get - { - return new TheoryData - { - new StringValues(), - new StringValues((string)null), - new StringValues((string[])null), - (string)null, - (string[])null - }; - } - } - - public static TheoryData EmptyStringValues - { - get - { - return new TheoryData - { - StringValues.Empty, - new StringValues(new string[0]), - new string[0] - }; - } - } - - public static TheoryData FilledStringValues - { - get - { - return new TheoryData - { - new StringValues("abc"), - new StringValues(new[] { "abc" }), - new StringValues(new[] { "abc", "bcd" }), - new StringValues(new[] { "abc", "bcd", "foo" }), - "abc", - new[] { "abc" }, - new[] { "abc", "bcd" }, - new[] { "abc", "bcd", "foo" } - }; - } - } - - public static TheoryData FilledStringValuesWithExpectedStrings - { - get - { - return new TheoryData - { - { default(StringValues), (string)null }, - { StringValues.Empty, (string)null }, - { new StringValues(new string[] { }), (string)null }, - { new StringValues(string.Empty), string.Empty }, - { new StringValues(new string[] { string.Empty }), string.Empty }, - { new StringValues("abc"), "abc" } - }; - } - } - - public static TheoryData FilledStringValuesWithExpectedObjects - { - get - { - return new TheoryData - { - { default(StringValues), (object)null }, - { StringValues.Empty, (object)null }, - { new StringValues(new string[] { }), (object)null }, - { new StringValues("abc"), (object)"abc" }, - { new StringValues("abc"), (object)new[] { "abc" } }, - { new StringValues(new[] { "abc" }), (object)new[] { "abc" } }, - { new StringValues(new[] { "abc", "bcd" }), (object)new[] { "abc", "bcd" } } - }; - } - } - - public static TheoryData FilledStringValuesWithExpected - { - get - { - return new TheoryData - { - { default(StringValues), new string[0] }, - { StringValues.Empty, new string[0] }, - { new StringValues(string.Empty), new[] { string.Empty } }, - { new StringValues("abc"), new[] { "abc" } }, - { new StringValues(new[] { "abc" }), new[] { "abc" } }, - { new StringValues(new[] { "abc", "bcd" }), new[] { "abc", "bcd" } }, - { new StringValues(new[] { "abc", "bcd", "foo" }), new[] { "abc", "bcd", "foo" } }, - { string.Empty, new[] { string.Empty } }, - { "abc", new[] { "abc" } }, - { new[] { "abc" }, new[] { "abc" } }, - { new[] { "abc", "bcd" }, new[] { "abc", "bcd" } }, - { new[] { "abc", "bcd", "foo" }, new[] { "abc", "bcd", "foo" } } - }; - } - } - - [Theory] - [MemberData(nameof(DefaultOrNullStringValues))] - [MemberData(nameof(EmptyStringValues))] - [MemberData(nameof(FilledStringValues))] - public void IsReadOnly_True(StringValues stringValues) - { - Assert.True(((IList)stringValues).IsReadOnly); - Assert.Throws(() => ((IList)stringValues)[0] = string.Empty); - Assert.Throws(() => ((ICollection)stringValues).Add(string.Empty)); - Assert.Throws(() => ((IList)stringValues).Insert(0, string.Empty)); - Assert.Throws(() => ((ICollection)stringValues).Remove(string.Empty)); - Assert.Throws(() => ((IList)stringValues).RemoveAt(0)); - Assert.Throws(() => ((ICollection)stringValues).Clear()); - } - - [Theory] - [MemberData(nameof(DefaultOrNullStringValues))] - public void DefaultOrNull_ExpectedValues(StringValues stringValues) - { - Assert.Null((string[])stringValues); - } - - [Theory] - [MemberData(nameof(DefaultOrNullStringValues))] - [MemberData(nameof(EmptyStringValues))] - public void DefaultNullOrEmpty_ExpectedValues(StringValues stringValues) - { - Assert.Equal(0, stringValues.Count); - Assert.Null((string)stringValues); - Assert.Equal((string)null, stringValues); - Assert.Equal(string.Empty, stringValues.ToString()); - Assert.Equal(new string[0], stringValues.ToArray()); - - Assert.True(StringValues.IsNullOrEmpty(stringValues)); - Assert.Throws(() => stringValues[0]); - Assert.Throws(() => ((IList)stringValues)[0]); - Assert.Equal(string.Empty, stringValues.ToString()); - Assert.Equal(-1, ((IList)stringValues).IndexOf(null)); - Assert.Equal(-1, ((IList)stringValues).IndexOf(string.Empty)); - Assert.Equal(-1, ((IList)stringValues).IndexOf("not there")); - Assert.False(((ICollection)stringValues).Contains(null)); - Assert.False(((ICollection)stringValues).Contains(string.Empty)); - Assert.False(((ICollection)stringValues).Contains("not there")); - Assert.Empty(stringValues); - } - - [Fact] - public void ImplicitStringConverter_Works() - { - string nullString = null; - StringValues stringValues = nullString; - Assert.Equal(0, stringValues.Count); - Assert.Null((string)stringValues); - Assert.Null((string[])stringValues); - - string aString = "abc"; - stringValues = aString; - Assert.Equal(1, stringValues.Count); - Assert.Equal(aString, stringValues); - Assert.Equal(aString, stringValues[0]); - Assert.Equal(aString, ((IList)stringValues)[0]); - Assert.Equal(new string[] { aString }, stringValues); - } - - [Fact] - public void ImplicitStringArrayConverter_Works() - { - string[] nullStringArray = null; - StringValues stringValues = nullStringArray; - Assert.Equal(0, stringValues.Count); - Assert.Null((string)stringValues); - Assert.Null((string[])stringValues); - - string aString = "abc"; - string[] aStringArray = new[] { aString }; - stringValues = aStringArray; - Assert.Equal(1, stringValues.Count); - Assert.Equal(aString, stringValues); - Assert.Equal(aString, stringValues[0]); - Assert.Equal(aString, ((IList)stringValues)[0]); - Assert.Equal(aStringArray, stringValues); - - aString = "abc"; - string bString = "bcd"; - aStringArray = new[] { aString, bString }; - stringValues = aStringArray; - Assert.Equal(2, stringValues.Count); - Assert.Equal("abc,bcd", stringValues); - Assert.Equal(aStringArray, stringValues); - } - - [Theory] - [MemberData(nameof(DefaultOrNullStringValues))] - [MemberData(nameof(EmptyStringValues))] - public void DefaultNullOrEmpty_Enumerator(StringValues stringValues) - { - var e = stringValues.GetEnumerator(); - Assert.Null(e.Current); - Assert.False(e.MoveNext()); - Assert.Null(e.Current); - Assert.False(e.MoveNext()); - Assert.False(e.MoveNext()); - Assert.False(e.MoveNext()); - - var e1 = ((IEnumerable)stringValues).GetEnumerator(); - Assert.Null(e1.Current); - Assert.False(e1.MoveNext()); - Assert.Null(e1.Current); - Assert.False(e1.MoveNext()); - Assert.False(e1.MoveNext()); - Assert.False(e1.MoveNext()); - - var e2 = ((IEnumerable)stringValues).GetEnumerator(); - Assert.Null(e2.Current); - Assert.False(e2.MoveNext()); - Assert.Null(e2.Current); - Assert.False(e2.MoveNext()); - Assert.False(e2.MoveNext()); - Assert.False(e2.MoveNext()); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpected))] - public void Enumerator(StringValues stringValues, string[] expected) - { - var e = stringValues.GetEnumerator(); - for (int i = 0; i < expected.Length; i++) - { - Assert.True(e.MoveNext()); - Assert.Equal(expected[i], e.Current); - } - Assert.False(e.MoveNext()); - Assert.False(e.MoveNext()); - Assert.False(e.MoveNext()); - - var e1 = ((IEnumerable)stringValues).GetEnumerator(); - for (int i = 0; i < expected.Length; i++) - { - Assert.True(e1.MoveNext()); - Assert.Equal(expected[i], e1.Current); - } - Assert.False(e1.MoveNext()); - Assert.False(e1.MoveNext()); - Assert.False(e1.MoveNext()); - - var e2 = ((IEnumerable)stringValues).GetEnumerator(); - for (int i = 0; i < expected.Length; i++) - { - Assert.True(e2.MoveNext()); - Assert.Equal(expected[i], e2.Current); - } - Assert.False(e2.MoveNext()); - Assert.False(e2.MoveNext()); - Assert.False(e2.MoveNext()); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpected))] - public void IndexOf(StringValues stringValues, string[] expected) - { - IList list = stringValues; - Assert.Equal(-1, list.IndexOf("not there")); - for (int i = 0; i < expected.Length; i++) - { - Assert.Equal(i, list.IndexOf(expected[i])); - } - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpected))] - public void Contains(StringValues stringValues, string[] expected) - { - ICollection collection = stringValues; - Assert.False(collection.Contains("not there")); - for (int i = 0; i < expected.Length; i++) - { - Assert.True(collection.Contains(expected[i])); - } - } - - [Theory] - [MemberData(nameof(DefaultOrNullStringValues))] - [MemberData(nameof(EmptyStringValues))] - [MemberData(nameof(FilledStringValues))] - public void CopyTo_TooSmall(StringValues stringValues) - { - ICollection collection = stringValues; - string[] tooSmall = new string[0]; - - if (collection.Count > 0) - { - Assert.Throws(() => collection.CopyTo(tooSmall, 0)); - } - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpected))] - public void CopyTo_CorrectSize(StringValues stringValues, string[] expected) - { - ICollection collection = stringValues; - string[] actual = new string[expected.Length]; - - if (collection.Count > 0) - { - Assert.Throws(() => collection.CopyTo(actual, -1)); - Assert.Throws(() => collection.CopyTo(actual, actual.Length + 1)); - } - collection.CopyTo(actual, 0); - Assert.Equal(expected, actual); - } - - [Theory] - [MemberData(nameof(DefaultOrNullStringValues))] - [MemberData(nameof(EmptyStringValues))] - public void DefaultNullOrEmpty_Concat(StringValues stringValues) - { - string[] expected = new[] { "abc", "bcd", "foo" }; - Assert.Equal(expected, StringValues.Concat(stringValues, new StringValues(expected))); - Assert.Equal(expected, StringValues.Concat(new StringValues(expected), stringValues)); - - string[] empty = new string[0]; - Assert.Equal(empty, StringValues.Concat(stringValues, StringValues.Empty)); - Assert.Equal(empty, StringValues.Concat(StringValues.Empty, stringValues)); - Assert.Equal(empty, StringValues.Concat(stringValues, new StringValues())); - Assert.Equal(empty, StringValues.Concat(new StringValues(), stringValues)); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpected))] - public void Concat(StringValues stringValues, string[] array) - { - string[] filled = new[] { "abc", "bcd", "foo" }; - - string[] expectedPrepended = array.Concat(filled).ToArray(); - Assert.Equal(expectedPrepended, StringValues.Concat(stringValues, new StringValues(filled))); - - string[] expectedAppended = filled.Concat(array).ToArray(); - Assert.Equal(expectedAppended, StringValues.Concat(new StringValues(filled), stringValues)); - } - - [Fact] - public void Equals_OperatorEqual() - { - var equalString = "abc"; - - var equalStringArray = new string[] { equalString }; - var equalStringValues = new StringValues(equalString); - var otherStringValues = new StringValues(equalString); - var stringArray = new string[] { equalString, equalString }; - var stringValuesArray = new StringValues(stringArray); - - Assert.True(equalStringValues == otherStringValues); - - Assert.True(equalStringValues == equalString); - Assert.True(equalString == equalStringValues); - - Assert.True(equalStringValues == equalStringArray); - Assert.True(equalStringArray == equalStringValues); - - Assert.True(stringArray == stringValuesArray); - Assert.True(stringValuesArray == stringArray); - - Assert.False(stringValuesArray == equalString); - Assert.False(stringValuesArray == equalStringArray); - Assert.False(stringValuesArray == equalStringValues); - } - - [Fact] - public void Equals_OperatorNotEqual() - { - var equalString = "abc"; - - var equalStringArray = new string[] { equalString }; - var equalStringValues = new StringValues(equalString); - var otherStringValues = new StringValues(equalString); - var stringArray = new string[] { equalString, equalString }; - var stringValuesArray = new StringValues(stringArray); - - Assert.False(equalStringValues != otherStringValues); - - Assert.False(equalStringValues != equalString); - Assert.False(equalString != equalStringValues); - - Assert.False(equalStringValues != equalStringArray); - Assert.False(equalStringArray != equalStringValues); - - Assert.False(stringArray != stringValuesArray); - Assert.False(stringValuesArray != stringArray); - - Assert.True(stringValuesArray != equalString); - Assert.True(stringValuesArray != equalStringArray); - Assert.True(stringValuesArray != equalStringValues); - } - - [Fact] - public void Equals_Instance() - { - var equalString = "abc"; - - var equalStringArray = new string[] { equalString }; - var equalStringValues = new StringValues(equalString); - var stringArray = new string[] { equalString, equalString }; - var stringValuesArray = new StringValues(stringArray); - - Assert.True(equalStringValues.Equals(equalStringValues)); - Assert.True(equalStringValues.Equals(equalString)); - Assert.True(equalStringValues.Equals(equalStringArray)); - Assert.True(stringValuesArray.Equals(stringArray)); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpectedObjects))] - public void Equals_ObjectEquals(StringValues stringValues, object obj) - { - Assert.True(stringValues == obj); - Assert.True(obj == stringValues); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpectedObjects))] - public void Equals_ObjectNotEquals(StringValues stringValues, object obj) - { - Assert.False(stringValues != obj); - Assert.False(obj != stringValues); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpectedStrings))] - public void Equals_String(StringValues stringValues, string expected) - { - var notEqual = new StringValues("bcd"); - - Assert.True(StringValues.Equals(stringValues, expected)); - Assert.False(StringValues.Equals(stringValues, notEqual)); - } - - [Theory] - [MemberData(nameof(FilledStringValuesWithExpected))] - public void Equals_StringArray(StringValues stringValues, string[] expected) - { - var notEqual = new StringValues(new[] { "bcd", "abc" }); - - Assert.True(StringValues.Equals(stringValues, expected)); - Assert.False(StringValues.Equals(stringValues, notEqual)); - } - } -} diff --git a/testassets/ThrowingLibrary/Thrower.cs b/testassets/ThrowingLibrary/Thrower.cs deleted file mode 100644 index babe2387..00000000 --- a/testassets/ThrowingLibrary/Thrower.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.CompilerServices; - -namespace ThrowingLibrary -{ - // Throwing an exception in the current assembly always seems to populate the full stack - // trace regardless of symbol type. This type exists to simulate an exception thrown - // across assemblies which is the typical use case for StackTraceHelper. - public static class Thrower - { - [MethodImpl(MethodImplOptions.NoInlining)] - public static void Throw() - { - throw new DivideByZeroException(); - } - } -} diff --git a/testassets/ThrowingLibrary/ThrowingLibrary.csproj b/testassets/ThrowingLibrary/ThrowingLibrary.csproj deleted file mode 100644 index d77d3928..00000000 --- a/testassets/ThrowingLibrary/ThrowingLibrary.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - netstandard2.0 - portable - - - diff --git a/version.xml b/version.xml deleted file mode 100644 index e6564ae4..00000000 --- a/version.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - dev - 2.1.0 - preview1 - -