diff --git a/.appveyor.yml b/.appveyor.yml index aef7f02c1..776f337d8 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -2,7 +2,7 @@ - git config --global core.autocrlf true branches: only: - - master + - main - /^(.*\/)?ci-.*$/ - /^rel\/.*/ configuration: diff --git a/.azuredevops/dependabot.yml b/.azuredevops/dependabot.yml new file mode 100644 index 000000000..e99cd24bd --- /dev/null +++ b/.azuredevops/dependabot.yml @@ -0,0 +1,3 @@ +version: 2 +enable-campaigned-updates: false +enable-security-updates: false diff --git a/.config/CredScanSuppressions.json b/.config/CredScanSuppressions.json new file mode 100644 index 000000000..8db08e538 --- /dev/null +++ b/.config/CredScanSuppressions.json @@ -0,0 +1,29 @@ +{ + "tool": "Credential Scanner", + "suppressions": [ + { + "placeholder": "abcdefg", + "_justification": "This is a fake password used in test code." + }, + { + "placeholder": "Pa$$AAECAw==", + "_justification": "This is a fake password used in test code." + }, + { + "placeholder": "ALyuoraY/cIWD1hjo+K81/pf83qo6Q6T+UBYcXN9P3A9WHLvEY10f+lwW5qPG6h9xw==", + "_justification": "This is a fake hashed password used in test code." + }, + { + "placeholder": "abcdefg123", + "_justification": "This is a fake password used in test code." + }, + { + "placeholder": "3e29b24f825e737d97aed5eb62df5076", + "_justification": "This is a fake password used in test code." + }, + { + "placeholder": "My Password", + "_justification": "This is a fake password used in test code." + } + ] +} \ No newline at end of file diff --git a/.config/tsaoptions.json b/.config/tsaoptions.json new file mode 100644 index 000000000..cb7d8b10a --- /dev/null +++ b/.config/tsaoptions.json @@ -0,0 +1,12 @@ +{ + "areaPath": "DevDiv\\ASP.NET Core\\Policy Violations", + "codebaseName": "AspNetWebStack", + "instanceUrl": "https://devdiv.visualstudio.com/", + "iterationPath": "DevDiv", + "notificationAliases": [ + "aspnetcore-build@microsoft.com" + ], + "projectName": "DEVDIV", + "repositoryName": "AspNetWebStack", + "template": "TFSDEVDIV" +} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..4d92ff8bf --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +registries: + dotnet-public: + type: nuget-feed + url: https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json +updates: + - package-ecosystem: "nuget" + directory: "/" + registries: + - dotnet-public + schedule: + interval: "weekly" + groups: + nuget: + patterns: + - "*" + ignore: + - dependency-name: "*" + update-types: ["version-update:semver-major"] diff --git a/.gitignore b/.gitignore index 11bf8ccc5..9f67f0ee8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,20 @@ -[Bb]in -[Oo]bj -[Tt]est[Rr]esults -*.suo -*.user +.msbuild/ +.vs/ +bin/ +obj/ +packages/ + *.[Cc]ache -*[Rr]esharper* -packages -NuGet.exe -_[Ss]cripts -*.exe +*.binlog *.dll -*.nupkg *.dot[Cc]over -*.vsp -*.psess +*.exe +*.nupkg *.orig +*.psess *.sln.ide -.vs/ -project.lock.json +*.suo +*.user +*.vsp +*[Rr]esharper* *launchSettings.json diff --git a/.nuget/NuGet.Config b/.nuget/NuGet.Config deleted file mode 100644 index 6ff25f633..000000000 --- a/.nuget/NuGet.Config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/.nuget/packages.config b/.nuget/packages.config index ed6c18bcb..a8fe9612a 100644 --- a/.nuget/packages.config +++ b/.nuget/packages.config @@ -3,5 +3,5 @@ - + \ No newline at end of file diff --git a/CODE-OF-CONDUCT.md b/CODE-OF-CONDUCT.md new file mode 100644 index 000000000..775f221c9 --- /dev/null +++ b/CODE-OF-CONDUCT.md @@ -0,0 +1,6 @@ +# Code of Conduct + +This project has adopted the code of conduct defined by the Contributor Covenant +to clarify expected behavior in our community. + +For more information, see the [.NET Foundation Code of Conduct](https://dotnetfoundation.org/code-of-conduct). diff --git a/Directory.Build.props b/Directory.Build.props index 407f4248f..fef50e3d3 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -3,6 +3,14 @@ - 15.0 + 16.0 + + true + + false + diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 000000000..837d83954 --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 189d9dc15..f164f7606 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,4 @@ -ASP.NET MVC, Web API, Web Pages, and Razor -=== - -AppVeyor: [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/aspnet/aspnetwebstack?branch=master&svg=true)](https://ci.appveyor.com/project/aspnetci/aspnetwebstack/branch/master) +# ASP.NET MVC, Web API, Web Pages, and Razor ## Note: This repo is for ASP.NET MVC 5.x, Web API 2.x, and Web Pages 3.x. For ASP.NET Core MVC, check the [AspNetCore repo](https://github.com/aspnet/AspNetCore). @@ -14,22 +11,21 @@ This repo includes: * ASP.NET Web Pages 3.x * ASP.NET Razor 3.x -### Nightly builds - -The latest built and tested packages from this repo are available on this MyGet feed: https://dotnet.myget.org/gallery/aspnetwebstack-dev - ### Contributing Check out the [contributing](CONTRIBUTING.md) page to see the best places to log issues and start discussions. ### Tags and releases -Git tag|Git branch|Other products|MVC package versions|Web API package (product) versions|Web Pages package versions ---------|--------------|------------|------------|------------|------------ -[v2.0.4](https://github.com/aspnet/AspNetWebStack/tree/v2.0.4)|[v2.0-rtm](https://github.com/aspnet/AspNetWebStack/tree/v2.0-rtm)||4.0.40804|4.0.30506|2.0.30506 -[v2.1](https://github.com/aspnet/AspNetWebStack/tree/v2.1)||ASP.NET and Web Tools 2012.2, VS 2012 Update 2 (not on http://nuget.org)|v4 2012.2 Update RTM|v1 2012.2 Update RTM|v2 2012.2 Update RTM -[v3.0.2](https://github.com/aspnet/AspNetWebStack/tree/v3.0.2)|[v3-rtm](https://github.com/aspnet/AspNetWebStack/tree/v3-rtm)||5.0.2|5.0.1 (2.0.1)|3.0.1 -[v3.1.3](https://github.com/aspnet/AspNetWebStack/tree/v3.1.3)|[v3.1-rtm](https://github.com/aspnet/AspNetWebStack/tree/v3.1-rtm)||5.1.3|5.1.2 (2.1.2)|3.1.2 -[v3.2.4](https://github.com/aspnet/AspNetWebStack/tree/v3.2.4)|||5.2.4|5.2.4 (2.2.4)|3.2.4 -[v3.2.6](https://github.com/aspnet/AspNetWebStack/tree/v3.2.6)|||5.2.6|5.2.6|3.2.6 -||[master](https://github.com/aspnet/AspNetWebStack/tree/master)|New work e.g. MVC 5.2.7-preview1||| +Git tag or branch|Other products|MVC package versions|Web API package (product) versions|Web Pages package versions +--------|--------------|------------|------------|------------ +[v2.0.4](https://github.com/aspnet/AspNetWebStack/tree/v2.0.4)||4.0.40804|4.0.30506|2.0.30506 +[v2.1](https://github.com/aspnet/AspNetWebStack/tree/v2.1)|ASP.NET and Web Tools 2012.2, VS 2012 Update 2 (not on http://nuget.org)|v4 2012.2 Update RTM|v1 2012.2 Update RTM|v2 2012.2 Update RTM +[v3.0.2](https://github.com/aspnet/AspNetWebStack/tree/v3.0.2)||5.0.2|5.0.1 (2.0.1)|3.0.1 +[v3.1.3](https://github.com/aspnet/AspNetWebStack/tree/v3.1.3)||5.1.3|5.1.2 (2.1.2)|3.1.2 +[v3.2.6](https://github.com/aspnet/AspNetWebStack/tree/v3.2.6)||5.2.6|5.2.6|3.2.6 +[v3.2.7](https://github.com/aspnet/AspNetWebStack/tree/v3.2.7)||5.2.7|5.2.7|3.2.7 +[v3.2.8](https://github.com/aspnet/AspNetWebStack/tree/v3.2.8)||5.2.8|5.2.8|3.2.8 +[v3.2.9](https://github.com/aspnet/AspNetWebStack/tree/v3.2.9)||5.2.9|5.2.9|3.2.9 +[v3.3.0](https://github.com/aspnet/AspNetWebStack/tree/v3.3.0)||5.3.0|5.3.0 (Client 6.0.0)|3.3.0 +[main](https://github.com/aspnet/AspNetWebStack/tree/main)|New work|5.3.1|5.3.1 (Client 6.0.1)|3.3.1 diff --git a/Runtime.NetFramework.slnf b/Runtime.NetFramework.slnf new file mode 100644 index 000000000..7b79711ff --- /dev/null +++ b/Runtime.NetFramework.slnf @@ -0,0 +1,57 @@ +{ + "solution": { + "path": "Runtime.sln", + "projects": [ + "src\\Microsoft.AspNet.Facebook\\Microsoft.AspNet.Facebook.csproj", + "src\\Microsoft.Web.Helpers\\Microsoft.Web.Helpers.csproj", + "src\\Microsoft.Web.Mvc\\Microsoft.Web.Mvc.csproj", + "src\\Microsoft.Web.WebPages.OAuth\\Microsoft.Web.WebPages.OAuth.csproj", + "src\\System.Net.Http.Formatting\\System.Net.Http.Formatting.csproj", + "src\\System.Web.Cors\\System.Web.Cors.csproj", + "src\\System.Web.Helpers\\System.Web.Helpers.csproj", + "src\\System.Web.Http.Cors\\System.Web.Http.Cors.csproj", + "src\\System.Web.Http.Owin\\System.Web.Http.Owin.csproj", + "src\\System.Web.Http.SelfHost\\System.Web.Http.SelfHost.csproj", + "src\\System.Web.Http.SignalR\\System.Web.Http.SignalR.csproj", + "src\\System.Web.Http.Tracing\\System.Web.Http.Tracing.csproj", + "src\\System.Web.Http.WebHost\\System.Web.Http.WebHost.csproj", + "src\\System.Web.Http\\System.Web.Http.csproj", + "src\\System.Web.Mvc\\System.Web.Mvc.csproj", + "src\\System.Web.Razor\\System.Web.Razor.csproj", + "src\\System.Web.WebPages.Administration\\System.Web.WebPages.Administration.csproj", + "src\\System.Web.WebPages.Deployment\\System.Web.WebPages.Deployment.csproj", + "src\\System.Web.WebPages.Razor\\System.Web.WebPages.Razor.csproj", + "src\\System.Web.WebPages\\System.Web.WebPages.csproj", + "src\\WebApiHelpPage\\VB\\WebApiHelpPageVB.vbproj", + "src\\WebApiHelpPage\\WebApiHelpPage.csproj", + "src\\WebMatrix.Data\\WebMatrix.Data.csproj", + "src\\WebMatrix.WebData\\WebMatrix.WebData.csproj", + "test\\Microsoft.AspNet.Facebook.Test\\Microsoft.AspNet.Facebook.Test.csproj", + "test\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj", + "test\\Microsoft.Web.Helpers.Test\\Microsoft.Web.Helpers.Test.csproj", + "test\\Microsoft.Web.Mvc.Test\\Microsoft.Web.Mvc.Test.csproj", + "test\\Microsoft.Web.WebPages.OAuth.Test\\Microsoft.Web.WebPages.OAuth.Test.csproj", + "test\\System.Net.Http.Formatting.Test\\System.Net.Http.Formatting.Test.csproj", + "test\\System.Web.Cors.Test\\System.Web.Cors.Test.csproj", + "test\\System.Web.Helpers.Test\\System.Web.Helpers.Test.csproj", + "test\\System.Web.Http.Cors.Test\\System.Web.Http.Cors.Test.csproj", + "test\\System.Web.Http.Integration.Test\\System.Web.Http.Integration.Test.csproj", + "test\\System.Web.Http.Owin.Test\\System.Web.Http.Owin.Test.csproj", + "test\\System.Web.Http.SelfHost.Test\\System.Web.Http.SelfHost.Test.csproj", + "test\\System.Web.Http.SignalR.Test\\System.Web.Http.SignalR.Test.csproj", + "test\\System.Web.Http.Test\\System.Web.Http.Test.csproj", + "test\\System.Web.Http.Tracing.Test\\System.Web.Http.Tracing.Test.csproj", + "test\\System.Web.Http.WebHost.Test\\System.Web.Http.WebHost.Test.csproj", + "test\\System.Web.Mvc.Test\\System.Web.Mvc.Test.csproj", + "test\\System.Web.Razor.Test\\System.Web.Razor.Test.csproj", + "test\\System.Web.WebPages.Administration.Test\\System.Web.WebPages.Administration.Test.csproj", + "test\\System.Web.WebPages.Deployment.Test\\System.Web.WebPages.Deployment.Test.csproj", + "test\\System.Web.WebPages.Razor.Test\\System.Web.WebPages.Razor.Test.csproj", + "test\\System.Web.WebPages.Test\\System.Web.WebPages.Test.csproj", + "test\\WebApiHelpPage.Test\\WebApiHelpPage.Test.csproj", + "test\\WebApiHelpPage.VB.Test\\WebApiHelpPage.VB.Test.csproj", + "test\\WebMatrix.Data.Test\\WebMatrix.Data.Test.csproj", + "test\\WebMatrix.WebData.Test\\WebMatrix.WebData.Test.csproj" + ] + } +} \ No newline at end of file diff --git a/Runtime.NetStandard.slnf b/Runtime.NetStandard.slnf new file mode 100644 index 000000000..b8270ab3e --- /dev/null +++ b/Runtime.NetStandard.slnf @@ -0,0 +1,12 @@ +{ + "solution": { + "path": "Runtime.sln", + "projects": [ + "src\\System.Net.Http.Formatting.ns1_3\\System.Net.Http.Formatting.ns1_3.csproj", + "src\\System.Net.Http.Formatting.ns2_0\\System.Net.Http.Formatting.ns2_0.csproj", + "test\\Microsoft.TestCommon\\Microsoft.TestCommon.csproj", + "test\\System.Net.Http.Formatting.ns1_3.Test\\System.Net.Http.Formatting.ns1_3.Test.csproj", + "test\\System.Net.Http.Formatting.ns2_0.Test\\System.Net.Http.Formatting.ns2_0.Test.csproj" + ] + } +} \ No newline at end of file diff --git a/Runtime.msbuild b/Runtime.msbuild index c3f2294e7..815aaf93e 100644 --- a/Runtime.msbuild +++ b/Runtime.msbuild @@ -8,26 +8,16 @@ Release true true - true true false - $(BuildInParallel) + false + false $(MSBuildThisFileDirectory)bin\$(Configuration)\test\TestResults\ $(MSBuildThisFileDirectory)packages\Microsoft.Web.SkipStrongNames.1.0.0\tools\SkipStrongNames.exe $(MSBuildThisFileDirectory)tools\SkipStrongNames.xml .nuget\NuGet.exe - - - $(BuildInParallel) - - - $(BuildInParallel) - true - - - @@ -48,9 +38,8 @@ @@ -60,53 +49,90 @@ - + - - - - - + + <_Testing_NetStandard1_3 Include="true;false" /> + - + + + + + + + + - $(MsBuildThisFileDirectory)tools\src\Microsoft.Web.FxCop\ - $(MsBuildThisFileDirectory)packages\CustomFxCopRules + $(MSBuildThisFileDirectory)tools\src\Microsoft.Web.FxCop\ + $(MSBuildThisFileDirectory)packages\CustomFxCopRules - + - - - + + + + + + + Projects="Runtime.sln" + BuildInParallel="$(BuildInParallel)" + Targets="Build" + Properties="Configuration=$(Configuration);CodeAnalysis=$(CodeAnalysis);StyleCopEnabled=$(StyleCopEnabled); + VisualStudioVersion=$(VisualStudioVersion)" /> - - - + - <_TestDLLsXunit Include="bin\$(Configuration)\test\*.Test.dll" /> - <_TestDLLsXunit Include="bin\$(Configuration)\test\*.Test.*.dll" /> - <_TestDLLsXunit Include="bin\$(Configuration)\Test\NetCore\*.Test.dll" Condition="'$(BuildPortable)' == 'true'" /> - <_XunitProject Include="tools\WebStack.xunit.targets"> - TestAssembly=%(_TestDLLsXunit.FullPath);XmlPath=$(TestResultsDirectory)%(_TestDLLsXunit.FileName)-XunitResults.xml + <_TestDLLsXunit Include="bin\$(Configuration)\test\*.Test.dll; + bin\$(Configuration)\test\*\net4*\*.Test.dll" /> + <_XunitProject Include="tools\WebStack.testing.targets"> + TestAssembly=%(_TestDLLsXunit.FullPath); + XmlPath=$(TestResultsDirectory)%(_TestDLLsXunit.FileName)-XunitResults.xml + + + <_VSTestDLLs Include="bin\$(Configuration)\test\ns1_3\**\*.Test.dll; + bin\$(Configuration)\test\ns2_0\**\*.Test.dll" + Exclude="bin\$(Configuration)\test\*\net4*\*.Test.dll" /> + <_XunitProject Include="tools\WebStack.testing.targets"> + TestAssembly=%(_VSTestDLLs.FullPath); + XmlPath=$(TestResultsDirectory)%(_VSTestDLLs.FileName)-$([System.String]::Copy('%(_VSTestDLLs.RecursiveDir)').Trim('\\'))-XunitResults.xml; + UseVSTest=true @@ -114,14 +140,9 @@ - - - - + + + @@ -131,7 +152,11 @@ - + + + + diff --git a/Runtime.sln b/Runtime.sln index 372dfdb62..56de063a7 100644 --- a/Runtime.sln +++ b/Runtime.sln @@ -57,7 +57,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.Test", "tes EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting", "src\System.Net.Http.Formatting\System.Net.Http.Formatting.csproj", "{668E9021-CE84-49D9-98FB-DF125A9FCDB0}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.TestCommon", "test\Microsoft.TestCommon\Microsoft.TestCommon.csproj", "{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.TestCommon", "test\Microsoft.TestCommon\Microsoft.TestCommon.csproj", "{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting.Test", "test\System.Net.Http.Formatting.Test\System.Net.Http.Formatting.Test.csproj", "{7AF77741-9158-4D5F-8782-8F21FADF025F}" EndProject @@ -95,9 +95,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.Owin", "src EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Web.Http.Owin.Test", "test\System.Web.Http.Owin.Test\System.Web.Http.Owin.Test.csproj", "{C19267DD-3984-430C-AE18-4034F85DE4E5}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{CB34D534-9A09-4EE4-B350-C1C23AFBF5EE}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution items", "Solution items", "{CB34D534-9A09-4EE4-B350-C1C23AFBF5EE}" ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config + global.json = global.json + NuGet.Config = NuGet.Config .nuget\packages.config = .nuget\packages.config EndProjectSection EndProject @@ -113,6 +114,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.Facebook", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AspNet.Facebook.Test", "test\Microsoft.AspNet.Facebook.Test\Microsoft.AspNet.Facebook.Test.csproj", "{C3BEF382-C7C4-454D-B017-1EAC03E9A82C}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.Formatting.ns1_3", "src\System.Net.Http.Formatting.ns1_3\System.Net.Http.Formatting.ns1_3.csproj", "{5ABD9968-F3A3-4967-B768-A6142F69759E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.Formatting.ns2_0", "src\System.Net.Http.Formatting.ns2_0\System.Net.Http.Formatting.ns2_0.csproj", "{9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.Formatting.ns1_3.Test", "test\System.Net.Http.Formatting.ns1_3.Test\System.Net.Http.Formatting.ns1_3.Test.csproj", "{A1A20049-04C2-4676-93CF-92449C4BBAA9}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.Formatting.ns2_0.Test", "test\System.Net.Http.Formatting.ns2_0.Test\System.Net.Http.Formatting.ns2_0.Test.csproj", "{6C320AD9-F380-4F8B-85F9-0689F88766EC}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution CodeAnalysis|Any CPU = CodeAnalysis|Any CPU @@ -420,6 +429,30 @@ Global {C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Debug|Any CPU.Build.0 = Debug|Any CPU {C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Release|Any CPU.ActiveCfg = Release|Any CPU {C3BEF382-C7C4-454D-B017-1EAC03E9A82C}.Release|Any CPU.Build.0 = Release|Any CPU + {5ABD9968-F3A3-4967-B768-A6142F69759E}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {5ABD9968-F3A3-4967-B768-A6142F69759E}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {5ABD9968-F3A3-4967-B768-A6142F69759E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5ABD9968-F3A3-4967-B768-A6142F69759E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5ABD9968-F3A3-4967-B768-A6142F69759E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5ABD9968-F3A3-4967-B768-A6142F69759E}.Release|Any CPU.Build.0 = Release|Any CPU + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B}.Release|Any CPU.Build.0 = Release|Any CPU + {A1A20049-04C2-4676-93CF-92449C4BBAA9}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {A1A20049-04C2-4676-93CF-92449C4BBAA9}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {A1A20049-04C2-4676-93CF-92449C4BBAA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1A20049-04C2-4676-93CF-92449C4BBAA9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1A20049-04C2-4676-93CF-92449C4BBAA9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1A20049-04C2-4676-93CF-92449C4BBAA9}.Release|Any CPU.Build.0 = Release|Any CPU + {6C320AD9-F380-4F8B-85F9-0689F88766EC}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU + {6C320AD9-F380-4F8B-85F9-0689F88766EC}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU + {6C320AD9-F380-4F8B-85F9-0689F88766EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6C320AD9-F380-4F8B-85F9-0689F88766EC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6C320AD9-F380-4F8B-85F9-0689F88766EC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6C320AD9-F380-4F8B-85F9-0689F88766EC}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -475,6 +508,10 @@ Global {1E89A3E9-0A7F-418F-B4BE-6E38A6315373} = {C40883CD-366D-4534-8B58-3EA0D13136DF} {821A136C-7C6F-44C6-A9E6-C39B5BFB1483} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93} {C3BEF382-C7C4-454D-B017-1EAC03E9A82C} = {C40883CD-366D-4534-8B58-3EA0D13136DF} + {5ABD9968-F3A3-4967-B768-A6142F69759E} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93} + {9AAFB58C-B8C1-4D7F-80E6-7B95C94A829B} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93} + {A1A20049-04C2-4676-93CF-92449C4BBAA9} = {C40883CD-366D-4534-8B58-3EA0D13136DF} + {6C320AD9-F380-4F8B-85F9-0689F88766EC} = {C40883CD-366D-4534-8B58-3EA0D13136DF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {A855CFDC-9BEE-43A9-A3EA-4C4624A747DB} diff --git a/RuntimePortable.sln b/RuntimePortable.sln deleted file mode 100644 index f20623fd4..000000000 --- a/RuntimePortable.sln +++ /dev/null @@ -1,76 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27116.1 -MinimumVisualStudioVersion = 15.0 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{C40883CD-366D-4534-8B58-3EA0D13136DF}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.TestCommon", "test\Microsoft.TestCommon\Microsoft.TestCommon.csproj", "{FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting.NetCore", "src\System.Net.Http.Formatting.NetCore\System.Net.Http.Formatting.NetCore.csproj", "{C7060639-719B-4BD2-8A37-2F146B5A0668}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http.Formatting.NetCore.Test", "test\System.Net.Http.Formatting.NetCore.Test\System.Net.Http.Formatting.NetCore.Test.csproj", "{8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.Formatting.NetStandard", "src\System.Net.Http.Formatting.NetStandard\System.Net.Http.Formatting.NetStandard.csproj", "{636CA76A-C85C-42E2-B4AA-88046279B3CA}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "System.Net.Http.Formatting.NetStandard.Test", "test\System.Net.Http.Formatting.NetStandard.Test\System.Net.Http.Formatting.NetStandard.Test.csproj", "{DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A72045D4-B048-4697-9535-C3A6EDCA85B9}" - ProjectSection(SolutionItems) = preProject - global.json = global.json - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - CodeAnalysis|Any CPU = CodeAnalysis|Any CPU - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0}.Release|Any CPU.Build.0 = Release|Any CPU - {C7060639-719B-4BD2-8A37-2F146B5A0668}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {C7060639-719B-4BD2-8A37-2F146B5A0668}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {C7060639-719B-4BD2-8A37-2F146B5A0668}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C7060639-719B-4BD2-8A37-2F146B5A0668}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C7060639-719B-4BD2-8A37-2F146B5A0668}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C7060639-719B-4BD2-8A37-2F146B5A0668}.Release|Any CPU.Build.0 = Release|Any CPU - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08}.Release|Any CPU.Build.0 = Release|Any CPU - {636CA76A-C85C-42E2-B4AA-88046279B3CA}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {636CA76A-C85C-42E2-B4AA-88046279B3CA}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {636CA76A-C85C-42E2-B4AA-88046279B3CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {636CA76A-C85C-42E2-B4AA-88046279B3CA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {636CA76A-C85C-42E2-B4AA-88046279B3CA}.Release|Any CPU.ActiveCfg = Release|Any CPU - {636CA76A-C85C-42E2-B4AA-88046279B3CA}.Release|Any CPU.Build.0 = Release|Any CPU - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}.CodeAnalysis|Any CPU.ActiveCfg = CodeAnalysis|Any CPU - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}.CodeAnalysis|Any CPU.Build.0 = CodeAnalysis|Any CPU - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0} = {C40883CD-366D-4534-8B58-3EA0D13136DF} - {C7060639-719B-4BD2-8A37-2F146B5A0668} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93} - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08} = {C40883CD-366D-4534-8B58-3EA0D13136DF} - {636CA76A-C85C-42E2-B4AA-88046279B3CA} = {A9836F9E-6DB3-4D9F-ADCA-CF42D8C8BA93} - {DECB05DF-B33A-44A0-B5DE-B14A8CE0740F} = {C40883CD-366D-4534-8B58-3EA0D13136DF} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {2A542E86-4A12-4997-B307-DEA9C7EE6539} - EndGlobalSection -EndGlobal diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..edbf5411a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,9 @@ +# Security Policy + +## Reporting a Vulnerability + +Security issues and bugs should be reported privately to the Microsoft Security Response Center (MSRC), either by emailing secure@microsoft.com or via the portal at https://msrc.microsoft.com. +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your +original message. Further information, including the MSRC PGP key, can be found in the [MSRC Report an Issue FAQ](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue). + +Please do not open issues for anything you think might have a security implication. \ No newline at end of file diff --git a/azure-pipelines-public.yml b/azure-pipelines-public.yml new file mode 100644 index 000000000..7089d6acb --- /dev/null +++ b/azure-pipelines-public.yml @@ -0,0 +1,33 @@ +parameters: + # Test only the Release build by default. +- name: ReleaseBuildTarget + displayName: 'Build which target for Release?' + type: string + values: [ Build, Integration, UnitTest ] + default: UnitTest +- name: OtherBuildTarget + displayName: 'Build which target for Debug/CodeAnalysis?' + type: string + values: [ Build, Integration, UnitTest ] + default: Build + +variables: +- name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 +- name: DOTNET_NOLOGO + value: 1 + # Run CodeQL3000 tasks in a separate internal pipeline; not needed here. +- name: Codeql.SkipTaskAutoInjection + value: true + +trigger: [main] +pr: ['*'] + +stages: +- stage: build + displayName: Build + jobs: + - template: /eng/templates/default-build.yml + parameters: + ReleaseBuildTarget: ${{ parameters.ReleaseBuildTarget }} + OtherBuildTarget: ${{ parameters.OtherBuildTarget }} diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 000000000..d35adf3a1 --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,64 @@ +parameters: + # Test only the Release build by default. +- name: ReleaseBuildTarget + displayName: 'Build which target for Release?' + type: string + values: [ Build, Integration, UnitTest ] + default: Build +- name: OtherBuildTarget + displayName: 'Build which target for Debug/CodeAnalysis?' + type: string + values: [ Build, Integration, UnitTest ] + default: Build + +variables: +- name: DOTNET_CLI_TELEMETRY_OPTOUT + value: 1 +- name: DOTNET_NOLOGO + value: 1 + # Run CodeQL3000 tasks in a separate internal pipeline; not needed here. +- name: Codeql.SkipTaskAutoInjection + value: true + +trigger: [main] +pr: ['*'] + +schedules: +- cron: "0 9 1,15 * *" + displayName: "Twice-monthly official build" + branches: + include: + - main + always: true + +resources: + repositories: + # Repo: 1ESPipelineTemplates/1ESPipelineTemplates + - repository: 1esPipelines + type: git + name: 1ESPipelineTemplates/1ESPipelineTemplates + ref: refs/tags/release + +extends: + template: v1/1ES.Official.PipelineTemplate.yml@1esPipelines + parameters: + settings: + networkIsolationPolicy: Permissive, CFSClean, CFSClean2 + sdl: + policheck: + enabled: true + tsa: + enabled: true + pool: + name: NetCore1ESPool-Svc-Internal + demands: + - ImageOverride -equals windows.vs2019.amd64 + os: windows + stages: + - stage: build + displayName: Build + jobs: + - template: /eng/templates/default-build.yml@self + parameters: + ReleaseBuildTarget: ${{ parameters.ReleaseBuildTarget }} + OtherBuildTarget: ${{ parameters.OtherBuildTarget }} diff --git a/build.cmd b/build.cmd index e49e2cfb8..5e03011c7 100644 --- a/build.cmd +++ b/build.cmd @@ -1,18 +1,15 @@ @echo off -pushd %~dp0 setlocal -if exist bin goto build +if exist bin goto Build mkdir bin :Build -REM Find the most recent 32bit MSBuild.exe on the system. Require v15.0 (installed with VS2017) or later since .NET -REM Core projects are coming soon. -REM Use `vswhere` for the search since %ProgramFiles(x86)%\msbuild\15.0\Bin\MSBuild.exe almost never exists. +REM Require VS2019 (v16.0) on the system. Use `vswhere` for the search because it can find all VS installations. set vswhere="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" if not exist %vswhere% ( - set VsWhere="%ProgramFiles%\Microsoft Visual Studio\Installer\vswhere.exe" + set vswhere="%ProgramFiles%\Microsoft Visual Studio\Installer\vswhere.exe" ) if not exist %vswhere% ( REM vswhere.exe not in normal locations; check the Path. @@ -26,24 +23,69 @@ if not exist %vswhere% ( ) set InstallDir= -for /f "usebackq tokens=*" %%i in (`%vswhere% -version ^[15^,16^) -latest -prerelease -products * -requires Microsoft.Component.MSBuild -property installationPath`) do ( - set InstallDir=%%i +for /f "usebackq tokens=*" %%i in (`%vswhere% -version 16 -latest -prerelease -products * ^ + -requires Microsoft.Net.Component.4.5.TargetingPack ^ + -requires Microsoft.Net.Component.4.5.2.TargetingPack ^ + -requires Microsoft.Net.Component.4.6.2.TargetingPack ^ + -property installationPath`) do ( + set "InstallDir=%%i" ) -if exist "%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" ( - set MSBuild="%InstallDir%\MSBuild\15.0\Bin\MSBuild.exe" -) else ( - echo Could not find MSBuild.exe. Please install the VS2017 BuildTools component or a workload that includes it. + +if not DEFINED InstallDir ( + echo "Could not find a VS2019 installation with the necessary components (targeting packs for v4.5, v4.5.2, and v4.6.2)." + echo Please install VS2019 or the missing components. goto BuildFail ) +REM Find a 64bit MSBuild and add it to path. Require v17.8.3 or later due to our .NET SDK choice. +REM Check for VS2022 first. +set InstallDir= +for /f "usebackq tokens=*" %%i in (`%vswhere% -version 17.8.3 -latest -prerelease -products * ^ + -requires Microsoft.Component.MSBuild ^ + -property installationPath`) do ( + set "InstallDir=%%i" +) + +if DEFINED InstallDir ( + REM Add MSBuild to the path. + set "PATH=%InstallDir%\MSBuild\Current\Bin;%PATH%" + goto FoundMSBuild +) + +REM Otherwise find or install an xcopy-able MSBuild. +echo "Could not find a VS2022 installation with the necessary components (MSBuild). Falling back..." + +set "MSBuildVersion=17.8.5" +set "Command=[System.Threading.Thread]::CurrentThread.CurrentCulture = ''" +set "Command=%Command%; [System.Threading.Thread]::CurrentThread.CurrentUICulture = ''" +set "Command=%Command%; try { & '%~dp0eng\GetXCopyMSBuild.ps1' %MSBuildVersion%; exit $LASTEXITCODE }" +set "Command=%Command% catch { write-host $_; exit 1 }" +PowerShell -NoProfile -NoLogo -ExecutionPolicy Bypass -Command "%Command%" +if %ERRORLEVEL% neq 0 goto BuildFail + +REM Add MSBuild to the path. +set "PATH=%~dp0.msbuild\%MSBuildVersion%\tools\MSBuild\Current\Bin;%PATH%" + +:FoundMSBuild +REM Configure NuGet operations to work w/in this repo i.e. do not pollute system packages folder. +REM Note this causes two copies of packages restored using packages.config to land in this folder e.g. +REM StyleCpy.5.0.0/ and stylecop/5.0.0/. +set "NUGET_PACKAGES=%~dp0packages" + +REM Are we running in a local dev environment (not on CI)? +if DEFINED CI (set Desktop=false) else if DEFINED TEAMCITY_VERSION (set Desktop=false) else (set Desktop=true) + +pushd %~dp0 if "%1" == "" goto BuildDefaults -%MSBuild% Runtime.msbuild /m /nr:false /t:%* /p:Platform="Any CPU" /p:Desktop=true /v:M /fl /flp:LogFile=bin\msbuild.log;Verbosity=Normal +MSBuild "%~dp0Runtime.msbuild" /m /nr:false /p:Platform="Any CPU" /p:Desktop=%Desktop% /v:M ^ + /fl /fileLoggerParameters:LogFile=bin\msbuild.log;Verbosity=Normal /consoleLoggerParameters:Summary /t:%* if %ERRORLEVEL% neq 0 goto BuildFail goto BuildSuccess :BuildDefaults -%MSBuild% Runtime.msbuild /m /nr:false /p:Platform="Any CPU" /p:Desktop=true /v:M /fl /flp:LogFile=bin\msbuild.log;Verbosity=Normal +MSBuild "%~dp0Runtime.msbuild" /m /nr:false /p:Platform="Any CPU" /p:Desktop=%Desktop% /v:M ^ + /fl /fileLoggerParameters:LogFile=bin\msbuild.log;Verbosity=Normal /consoleLoggerParameters:Summary if %ERRORLEVEL% neq 0 goto BuildFail goto BuildSuccess diff --git a/eng/GetXCopyMSBuild.ps1 b/eng/GetXCopyMSBuild.ps1 new file mode 100644 index 000000000..667839289 --- /dev/null +++ b/eng/GetXCopyMSBuild.ps1 @@ -0,0 +1,43 @@ +# Lifted from https://github.com/dotnet/arcade/blob/main/eng/common/tools.ps1 + +[CmdletBinding(DefaultParameterSetName='Groups')] +param( + [string]$Version = '17.4.1' +) + +Set-StrictMode -Version 2 +$ErrorActionPreference = 'Stop' + +function Create-Directory ([string[]] $path) { + New-Item -Path $path -Force -ItemType 'Directory' | Out-Null +} + +function Unzip([string]$zipfile, [string]$outpath) { + Add-Type -AssemblyName System.IO.Compression.FileSystem + [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath) +} + +function InitializeXCopyMSBuild([string]$packageVersion, [bool]$install, [string]$ToolsDir) { + $packageName = 'RoslynTools.MSBuild' + $packageDir = Join-Path $ToolsDir $packageVersion + $packagePath = Join-Path $packageDir "$packageName.$packageVersion.nupkg" + + if (!(Test-Path $packageDir)) { + if (!$install) { + return $null + } + + Create-Directory $packageDir + + Write-Host "Downloading $packageName $packageVersion" + $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit + Invoke-WebRequest "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-eng/nuget/v3/flat2/$packageName/$packageVersion/$packageName.$packageVersion.nupkg" -OutFile $packagePath + + Unzip $packagePath $packageDir + } + + return Join-Path $packageDir 'tools' +} + +$RepoRoot = Resolve-Path (Join-Path $PSScriptRoot '..\') +InitializeXCopyMSBuild -packageVersion $Version -install $true -ToolsDir (join-path $RepoRoot .msbuild) diff --git a/eng/templates/default-build.yml b/eng/templates/default-build.yml new file mode 100644 index 000000000..d4041e8a0 --- /dev/null +++ b/eng/templates/default-build.yml @@ -0,0 +1,96 @@ +parameters: + ReleaseBuildTarget: '' + OtherBuildTarget: '' + +jobs: +- job: build + displayName: Build + ${{ if eq(variables['System.TeamProject'], 'public') }}: + pool: + name: NetCore-Svc-Public + demands: + - ImageOverride -equals windows.vs2019.amd64.open + timeoutInMinutes: 30 + + strategy: + matrix: + Release: + _BuildTarget: ${{ parameters.ReleaseBuildTarget }} + _Configuration: Release + _StyleCopEnabled: true + # Do CG work only in internal pipelines. + skipComponentGovernanceDetection: ${{ eq(variables['System.TeamProject'], 'public') }} + Debug: + _BuildTarget: ${{ parameters.OtherBuildTarget }} + _Configuration: Debug + _StyleCopEnabled: false + # Do not redo CG work. Configuration changes in this part of the matrix are not relevant to CG. + skipComponentGovernanceDetection: true + CodeAnalysis: + _BuildTarget: ${{ parameters.OtherBuildTarget }} + _Configuration: CodeAnalysis + _StyleCopEnabled: false + # Do not redo CG work. Configuration changes in this part of the matrix are not relevant to CG. + skipComponentGovernanceDetection: true + + steps: + - checkout: self + clean: true + displayName: Checkout + + - task: UseDotNet@2 + displayName: Get .NET SDK + inputs: + useGlobalJson: true + - task: UseDotNet@2 + displayName: Get .NET 2.1 runtime + inputs: + packageType: runtime + version: '2.1.x' + + - script: .\build.cmd EnableSkipStrongNames + displayName: Enable SkipStrongNames + - script: .\build.cmd $(_BuildTarget) ^ + /binaryLogger:artifacts/msbuild.binlog /p:Configuration=$(_Configuration) /p:StyleCopEnabled=$(_StyleCopEnabled) ^ + /fileLoggerParameters:LogFile=artifacts/msbuild.log;Summary;Verbosity=minimal + displayName: Build + + - ${{ if eq(variables['System.TeamProject'], 'public') }}: + - task: PublishBuildArtifacts@1 + displayName: Upload test results + condition: and(always(), ne(variables._BuildTarget, 'Build')) + continueOnError: true + inputs: + pathtoPublish: ./bin/$(_Configuration)/Test/TestResults/ + artifactName: $(_Configuration) Test Results $(System.JobId) + artifactType: Container + parallel: true + - task: PublishTestResults@2 + condition: and(always(), ne(variables._BuildTarget, 'Build')) + continueOnError: true + displayName: Publish test results + inputs: + mergeTestResults: true + searchFolder: ./bin/$(_Configuration)/Test/TestResults/ + testResultsFiles: '*.xml' + testRunner: xUnit + testRunTitle: $(_Configuration) + - task: PublishBuildArtifacts@1 + displayName: Upload logs + condition: always() + continueOnError: true + inputs: + pathtoPublish: ./artifacts/ + artifactName: $(_Configuration) Logs $(System.JobId) + artifactType: Container + parallel: true + - ${{ if eq(variables['System.TeamProject'], 'internal') }}: + - task: 1ES.PublishPipelineArtifact@1 + inputs: + condition: and(always(), ne(variables._BuildTarget, 'Build')) + path: ./bin/$(_Configuration)/Test/TestResults/ + artifact: $(_Configuration) Test Results $(System.JobId) + - task: 1ES.PublishPipelineArtifact@1 + inputs: + path: ./artifacts/ + artifact: $(_Configuration) Logs $(System.JobId) diff --git a/es-metadata.yml b/es-metadata.yml new file mode 100644 index 000000000..9061e1181 --- /dev/null +++ b/es-metadata.yml @@ -0,0 +1,8 @@ +schemaVersion: 0.0.1 +isProduction: true +accountableOwners: + service: 4db45fa9-fb0f-43ce-b523-ad1da773dfbc +routing: + defaultAreaPath: + org: devdiv + path: DevDiv\ASP.NET Core diff --git a/global.json b/global.json index ea2669b29..1fbb774c9 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,6 @@ { "sdk": { - "version": "2.1.403" + "version": "8.0.420", + "rollForward": "major" } -} \ No newline at end of file +} diff --git a/packages/repositories.config b/packages/repositories.config index 8bede8eeb..18d08a3de 100644 --- a/packages/repositories.config +++ b/packages/repositories.config @@ -3,7 +3,6 @@ - @@ -17,11 +16,9 @@ - - diff --git a/src/CodeAnalysisDictionary.xml b/src/CodeAnalysisDictionary.xml index fdd4e0ea7..26ab4a8af 100644 --- a/src/CodeAnalysisDictionary.xml +++ b/src/CodeAnalysisDictionary.xml @@ -55,6 +55,13 @@ ModelName BSON Untyped + Behavior + Callback + Canceled + Color + Fallback + Markup + Preflight WebPage diff --git a/src/Common/CollectionExtensions.cs b/src/Common/CollectionExtensions.cs index c89d4ad98..bfd1eb61d 100644 --- a/src/Common/CollectionExtensions.cs +++ b/src/Common/CollectionExtensions.cs @@ -27,7 +27,7 @@ public static T[] AppendAndReallocate(this T[] array, T value) } /// - /// Return the enumerable as an Array, copying if required. Optimized for common case where it is an Array. + /// Return the enumerable as an Array, copying if required. Optimized for common case where it is an Array. /// Avoid mutating the return value. /// public static T[] AsArray(this IEnumerable values) @@ -43,7 +43,7 @@ public static T[] AsArray(this IEnumerable values) } /// - /// Return the enumerable as a Collection of T, copying if required. Optimized for the common case where it is + /// Return the enumerable as a Collection of T, copying if required. Optimized for the common case where it is /// a Collection of T and avoiding a copy if it implements IList of T. Avoid mutating the return value. /// public static Collection AsCollection(this IEnumerable enumerable) @@ -78,9 +78,9 @@ public static IList AsIList(this IEnumerable enumerable) } return new List(enumerable); } - + /// - /// Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of T + /// Return the enumerable as a List of T, copying if required. Optimized for common case where it is an List of T /// or a ListWrapperCollection of T. Avoid mutating the return value. /// public static List AsList(this IEnumerable enumerable) diff --git a/src/Common/CommonWebApiResources.Designer.cs b/src/Common/CommonWebApiResources.Designer.cs index 4ceb3f115..6e1e476d6 100644 --- a/src/Common/CommonWebApiResources.Designer.cs +++ b/src/Common/CommonWebApiResources.Designer.cs @@ -24,15 +24,15 @@ namespace System.Web.Http.Properties { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class CommonWebApiResources { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CommonWebApiResources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// @@ -40,7 +40,7 @@ internal CommonWebApiResources() { internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { -#if NETFX_CORE +#if NETSTANDARD1_3 var assembly = typeof(CommonWebApiResources).GetTypeInfo().Assembly; #else var assembly = typeof(CommonWebApiResources).Assembly; @@ -59,7 +59,7 @@ internal CommonWebApiResources() { return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. @@ -73,7 +73,7 @@ internal CommonWebApiResources() { resourceCulture = value; } } - + /// /// Looks up a localized string similar to Relative URI values are not supported: '{0}'. The URI must be absolute.. /// @@ -82,7 +82,7 @@ internal static string ArgumentInvalidAbsoluteUri { return ResourceManager.GetString("ArgumentInvalidAbsoluteUri", resourceCulture); } } - + /// /// Looks up a localized string similar to Unsupported URI scheme: '{0}'. The URI scheme must be either '{1}' or '{2}'.. /// @@ -91,7 +91,7 @@ internal static string ArgumentInvalidHttpUriScheme { return ResourceManager.GetString("ArgumentInvalidHttpUriScheme", resourceCulture); } } - + /// /// Looks up a localized string similar to Value must be greater than or equal to {0}.. /// @@ -100,7 +100,7 @@ internal static string ArgumentMustBeGreaterThanOrEqualTo { return ResourceManager.GetString("ArgumentMustBeGreaterThanOrEqualTo", resourceCulture); } } - + /// /// Looks up a localized string similar to Value must be less than or equal to {0}.. /// @@ -109,7 +109,7 @@ internal static string ArgumentMustBeLessThanOrEqualTo { return ResourceManager.GetString("ArgumentMustBeLessThanOrEqualTo", resourceCulture); } } - + /// /// Looks up a localized string similar to The argument '{0}' is null or empty.. /// @@ -118,7 +118,7 @@ internal static string ArgumentNullOrEmpty { return ResourceManager.GetString("ArgumentNullOrEmpty", resourceCulture); } } - + /// /// Looks up a localized string similar to URI must not contain a query component or a fragment identifier.. /// @@ -127,7 +127,7 @@ internal static string ArgumentUriHasQueryOrFragment { return ResourceManager.GetString("ArgumentUriHasQueryOrFragment", resourceCulture); } } - + /// /// Looks up a localized string similar to The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.. /// diff --git a/src/Common/Error.cs b/src/Common/Error.cs index 0e8c83465..85449c142 100644 --- a/src/Common/Error.cs +++ b/src/Common/Error.cs @@ -74,7 +74,7 @@ internal static ArgumentException ArgumentUriNotAbsolute(string parameterName, U } /// - /// Creates an with a message saying that the argument must be an absolute URI + /// Creates an with a message saying that the argument must be an absolute URI /// without a query or fragment identifier and then logs it with . /// /// The name of the parameter that caused the current exception. @@ -225,11 +225,7 @@ internal static OperationCanceledException OperationCanceled(string messageForma /// The logged . internal static ArgumentException InvalidEnumArgument(string parameterName, int invalidValue, Type enumClass) { -#if NETFX_CORE - return new ArgumentException(Error.Format(CommonWebApiResources.InvalidEnumArgument, parameterName, invalidValue, enumClass.Name), parameterName); -#else return new InvalidEnumArgumentException(parameterName, invalidValue, enumClass); -#endif } /// @@ -265,5 +261,24 @@ internal static NotSupportedException NotSupported(string messageFormat, params { return new NotSupportedException(Error.Format(messageFormat, messageArgs)); } + +#if NETSTANDARD1_3 // InvalidEnumArgumentException not available in netstandard1.3. + internal class InvalidEnumArgumentException : ArgumentException + { + public InvalidEnumArgumentException() : this(null) + { } + + public InvalidEnumArgumentException(string message) : base(message) + { } + + public InvalidEnumArgumentException(string message, Exception innerException) : base(message, innerException) + { } + + public InvalidEnumArgumentException(string argumentName, int invalidValue, Type enumClass) : base( + Error.Format(CommonWebApiResources.InvalidEnumArgument, argumentName, invalidValue, enumClass.Name), + argumentName) + { } + } +#endif } } diff --git a/src/Common/UriQueryUtility.cs b/src/Common/UriQueryUtility.cs deleted file mode 100644 index 53675e11a..000000000 --- a/src/Common/UriQueryUtility.cs +++ /dev/null @@ -1,278 +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.Contracts; -using System.Net; -using System.Text; - -namespace System.Web.Http -{ - /// - /// Helpers for encoding, decoding, and parsing URI query components. In .Net 4.5 - /// please use the WebUtility class. - /// - internal static class UriQueryUtility - { - public static string UrlEncode(string str) - { - if (str == null) - { - return null; - } - -#if NETFX_CORE - return WebUtility.UrlEncode(str); -#else - byte[] bytes = Encoding.UTF8.GetBytes(str); - return Encoding.ASCII.GetString(UrlEncode(bytes, 0, bytes.Length, alwaysCreateNewReturnValue: false)); -#endif - } - - public static string UrlDecode(string str) - { - if (str == null) - { - return null; - } - -#if NETFX_CORE - return WebUtility.UrlDecode(str); -#else - return UrlDecodeInternal(str, Encoding.UTF8); -#endif - } - -#if !NETFX_CORE - private static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue) - { - byte[] encoded = UrlEncode(bytes, offset, count); - - return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes)) - ? (byte[])encoded.Clone() - : encoded; - } - - private static byte[] UrlEncode(byte[] bytes, int offset, int count) - { - if (!ValidateUrlEncodingParameters(bytes, offset, count)) - { - return null; - } - - int cSpaces = 0; - int cUnsafe = 0; - - // count them first - for (int i = 0; i < count; i++) - { - char ch = (char)bytes[offset + i]; - - if (ch == ' ') - cSpaces++; - else if (!IsUrlSafeChar(ch)) - cUnsafe++; - } - - // nothing to expand? - if (cSpaces == 0 && cUnsafe == 0) - return bytes; - - // expand not 'safe' characters into %XX, spaces to +s - byte[] expandedBytes = new byte[count + cUnsafe * 2]; - int pos = 0; - - for (int i = 0; i < count; i++) - { - byte b = bytes[offset + i]; - char ch = (char)b; - - if (IsUrlSafeChar(ch)) - { - expandedBytes[pos++] = b; - } - else if (ch == ' ') - { - expandedBytes[pos++] = (byte)'+'; - } - else - { - expandedBytes[pos++] = (byte)'%'; - expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf); - expandedBytes[pos++] = (byte)IntToHex(b & 0x0f); - } - } - - return expandedBytes; - } - - private static string UrlDecodeInternal(string value, Encoding encoding) - { - if (value == null) - { - return null; - } - - int count = value.Length; - UrlDecoder helper = new UrlDecoder(count, encoding); - - // go through the string's chars collapsing %XX and %uXXXX and - // appending each char as char, with exception of %XX constructs - // that are appended as bytes - - for (int pos = 0; pos < count; pos++) - { - char ch = value[pos]; - - if (ch == '+') - { - ch = ' '; - } - else if (ch == '%' && pos < count - 2) - { - int h1 = HexToInt(value[pos + 1]); - int h2 = HexToInt(value[pos + 2]); - - if (h1 >= 0 && h2 >= 0) - { - // valid 2 hex chars - byte b = (byte)((h1 << 4) | h2); - pos += 2; - - // don't add as char - helper.AddByte(b); - continue; - } - } - - if ((ch & 0xFF80) == 0) - helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode - else - helper.AddChar(ch); - } - - return helper.GetString(); - } - - private static int HexToInt(char h) - { - return (h >= '0' && h <= '9') ? h - '0' : - (h >= 'a' && h <= 'f') ? h - 'a' + 10 : - (h >= 'A' && h <= 'F') ? h - 'A' + 10 : - -1; - } - - private static char IntToHex(int n) - { - Contract.Assert(n < 0x10); - - if (n <= 9) - return (char)(n + (int)'0'); - else - return (char)(n - 10 + (int)'a'); - } - - // Set of safe chars, from RFC 1738.4 minus '+' - private static bool IsUrlSafeChar(char ch) - { - if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') - return true; - - switch (ch) - { - case '-': - case '_': - case '.': - case '!': - case '*': - case '(': - case ')': - return true; - } - - return false; - } - - private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) - { - if (bytes == null && count == 0) - return false; - if (bytes == null) - { - throw Error.ArgumentNull("bytes"); - } - if (offset < 0 || offset > bytes.Length) - { - throw new ArgumentOutOfRangeException("offset"); - } - if (count < 0 || offset + count > bytes.Length) - { - throw new ArgumentOutOfRangeException("count"); - } - - return true; - } - - // Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes - private class UrlDecoder - { - private int _bufferSize; - - // Accumulate characters in a special array - private int _numChars; - private char[] _charBuffer; - - // Accumulate bytes for decoding into characters in a special array - private int _numBytes; - private byte[] _byteBuffer; - - // Encoding to convert chars to bytes - private Encoding _encoding; - - private void FlushBytes() - { - if (_numBytes > 0) - { - _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); - _numBytes = 0; - } - } - - internal UrlDecoder(int bufferSize, Encoding encoding) - { - _bufferSize = bufferSize; - _encoding = encoding; - - _charBuffer = new char[bufferSize]; - // byte buffer created on demand - } - - internal void AddChar(char ch) - { - if (_numBytes > 0) - FlushBytes(); - - _charBuffer[_numChars++] = ch; - } - - internal void AddByte(byte b) - { - if (_byteBuffer == null) - _byteBuffer = new byte[_bufferSize]; - - _byteBuffer[_numBytes++] = b; - } - - internal String GetString() - { - if (_numBytes > 0) - FlushBytes(); - - if (_numChars > 0) - return new String(_charBuffer, 0, _numChars); - else - return String.Empty; - } - } -#endif - } -} \ No newline at end of file diff --git a/src/CommonAssemblyInfo.cs b/src/CommonAssemblyInfo.cs index aa130a34b..46325276e 100644 --- a/src/CommonAssemblyInfo.cs +++ b/src/CommonAssemblyInfo.cs @@ -24,12 +24,17 @@ // BUILD_GENERATED_VERSION will be set in any CI build. Versions below are not used. // =================================================================================== -#if (ASPNETMVC && (ASPNETWEBPAGES || ASPNETFACEBOOK)) || (ASPNETWEBPAGES && ASPNETFACEBOOK) -#error Runtime projects cannot define more than one of ASPNETMVC, ASPNETWEBPAGES or ASPNETFACEBOOK +#if (ASPNETMVC && (ASPNETWEBPAGES || ASPNETFACEBOOK || ASPNETHTTPFORMATTING)) || (ASPNETWEBPAGES && (ASPNETFACEBOOK || ASPNETHTTPFORMATTING)) || (ASPNETFACEBOOK && ASPNETHTTPFORMATTING) +#error Runtime projects cannot define more than one of ASPNETMVC, ASPNETWEBPAGES, ASPNETFACEBOOK, or ASPNETHTTPFORMATTING +#elif ASPNETHTTPFORMATTING +#if !BUILD_GENERATED_VERSION +[assembly: AssemblyVersion("6.0.1.0")] // ASPNETHTTPFORMATTING +[assembly: AssemblyFileVersion("6.0.1.0")] // ASPNETHTTPFORMATTING +#endif #elif ASPNETMVC #if !BUILD_GENERATED_VERSION -[assembly: AssemblyVersion("5.2.7.0")] // ASPNETMVC -[assembly: AssemblyFileVersion("5.2.7.0")] // ASPNETMVC +[assembly: AssemblyVersion("5.3.1.0")] // ASPNETMVC +[assembly: AssemblyFileVersion("5.3.1.0")] // ASPNETMVC #endif [assembly: AssemblyProduct("Microsoft ASP.NET MVC")] #elif ASPNETWEBPAGES diff --git a/src/CommonAssemblyInfo.vb b/src/CommonAssemblyInfo.vb index 8310810f3..7ba0e34bb 100644 --- a/src/CommonAssemblyInfo.vb +++ b/src/CommonAssemblyInfo.vb @@ -20,6 +20,6 @@ Imports System.Runtime.InteropServices ' Version numbers are automatically generated based on regular expressions. ' =========================================================================== - 'ASPNETMVC - 'ASPNETMVC + 'ASPNETMVC + 'ASPNETMVC \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index c81c39ff4..6785fd164 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -4,6 +4,6 @@ true false - v4.5 + v4.5 diff --git a/src/Microsoft.AspNet.Facebook/Microsoft.AspNet.Facebook.csproj b/src/Microsoft.AspNet.Facebook/Microsoft.AspNet.Facebook.csproj index 7e0f0f6ba..6667bfd80 100644 --- a/src/Microsoft.AspNet.Facebook/Microsoft.AspNet.Facebook.csproj +++ b/src/Microsoft.AspNet.Facebook/Microsoft.AspNet.Facebook.csproj @@ -22,14 +22,13 @@ TRACE;CODE_ANALYSIS;ASPNETFACEBOOK - - False - ..\..\packages\Facebook.6.4.2\lib\net45\Facebook.dll + + ..\..\packages\Facebook.6.8.0\lib\net45\Facebook.dll + True - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - False - False + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True diff --git a/src/Microsoft.AspNet.Facebook/packages.config b/src/Microsoft.AspNet.Facebook/packages.config index 613e222f9..140518fcd 100644 --- a/src/Microsoft.AspNet.Facebook/packages.config +++ b/src/Microsoft.AspNet.Facebook/packages.config @@ -1,6 +1,6 @@  - + - + \ No newline at end of file diff --git a/src/Microsoft.Web.Helpers/Microsoft.Web.Helpers.csproj b/src/Microsoft.Web.Helpers/Microsoft.Web.Helpers.csproj index c6be52d36..13e8f16e0 100644 --- a/src/Microsoft.Web.Helpers/Microsoft.Web.Helpers.csproj +++ b/src/Microsoft.Web.Helpers/Microsoft.Web.Helpers.csproj @@ -96,6 +96,7 @@ + @@ -105,7 +106,12 @@ - - + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + \ No newline at end of file diff --git a/src/Microsoft.Web.Helpers/packages.config b/src/Microsoft.Web.Helpers/packages.config index 98ba55d37..496abc735 100644 --- a/src/Microsoft.Web.Helpers/packages.config +++ b/src/Microsoft.Web.Helpers/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/Microsoft.Web.Helpers/razorgenerator.directives b/src/Microsoft.Web.Helpers/razorgenerator.directives new file mode 100644 index 000000000..2421be975 --- /dev/null +++ b/src/Microsoft.Web.Helpers/razorgenerator.directives @@ -0,0 +1 @@ +GeneratePrettyNames: true diff --git a/src/Microsoft.Web.WebPages.OAuth/Microsoft.Web.WebPages.OAuth.csproj b/src/Microsoft.Web.WebPages.OAuth/Microsoft.Web.WebPages.OAuth.csproj index dd376220f..9291b704d 100644 --- a/src/Microsoft.Web.WebPages.OAuth/Microsoft.Web.WebPages.OAuth.csproj +++ b/src/Microsoft.Web.WebPages.OAuth/Microsoft.Web.WebPages.OAuth.csproj @@ -16,33 +16,41 @@ - - False - ..\..\packages\DotNetOpenAuth.AspNet.4.0.3.12153\lib\net40-full\DotNetOpenAuth.AspNet.dll + + ..\..\packages\DotNetOpenAuth.AspNet.4.3.4.13329\lib\net45-full\DotNetOpenAuth.AspNet.dll + True - - False - ..\..\packages\DotNetOpenAuth.Core.4.0.3.12153\lib\net40-full\DotNetOpenAuth.Core.dll + + ..\..\packages\DotNetOpenAuth.Core.4.3.4.13329\lib\net45-full\DotNetOpenAuth.Core.dll + True - - False - ..\..\packages\DotNetOpenAuth.OAuth.Core.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OAuth.dll + + ..\..\packages\DotNetOpenAuth.OAuth.Core.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OAuth.dll + True - - False - ..\..\packages\DotNetOpenAuth.OAuth.Consumer.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OAuth.Consumer.dll + + ..\..\packages\DotNetOpenAuth.OAuth.Consumer.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OAuth.Consumer.dll + True - - False - ..\..\packages\DotNetOpenAuth.OpenId.Core.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OpenId.dll + + ..\..\packages\DotNetOpenAuth.OpenId.Core.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OpenId.dll + True - - False - ..\..\packages\DotNetOpenAuth.OpenId.RelyingParty.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OpenId.RelyingParty.dll + + ..\..\packages\DotNetOpenAuth.OpenId.RelyingParty.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OpenId.RelyingParty.dll + True + + ..\..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Extensions.dll + True + + + ..\..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Primitives.dll + True + @@ -119,4 +127,11 @@ --> + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + \ No newline at end of file diff --git a/src/Microsoft.Web.WebPages.OAuth/packages.config b/src/Microsoft.Web.WebPages.OAuth/packages.config index 1814071d6..eda693324 100644 --- a/src/Microsoft.Web.WebPages.OAuth/packages.config +++ b/src/Microsoft.Web.WebPages.OAuth/packages.config @@ -1,9 +1,12 @@  - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/src/Strict.ruleset b/src/Strict.ruleset index 5a2a69ba9..a0c61fcb5 100644 --- a/src/Strict.ruleset +++ b/src/Strict.ruleset @@ -6,5 +6,7 @@ + + \ No newline at end of file diff --git a/src/System.Net.Http.Formatting.NetCore/GlobalSuppressions.cs b/src/System.Net.Http.Formatting.NetCore/GlobalSuppressions.cs deleted file mode 100644 index 778d614cd..000000000 --- a/src/System.Net.Http.Formatting.NetCore/GlobalSuppressions.cs +++ /dev/null @@ -1,10 +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.CodeAnalysis; - -[assembly: SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames")] -[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Net.Http.Headers", Justification = "We follow the layout of System.Net.Http.")] -[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Net.Http.Handlers", Justification = "Handlers provide an extensibility hook which we want to keep in a separate namespace.")] -[assembly: SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant", Scope = "module", Target = "system.net.http.formatting.dll", Justification = "CLSCompliant is not applicable to the portable version of the assembly.")] -[assembly: SuppressMessage("Microsoft.Web.FxCop", "MW1000:UnusedResourceUsageRule", Scope = "module", Target = "system.net.http.formatting.dll", Justification = "The resources are only used in the non-portable version of the assembly.")] diff --git a/src/System.Net.Http.Formatting.NetCore/Internal/ConcurrentDictionary.cs b/src/System.Net.Http.Formatting.NetCore/Internal/ConcurrentDictionary.cs deleted file mode 100644 index 3df580802..000000000 --- a/src/System.Net.Http.Formatting.NetCore/Internal/ConcurrentDictionary.cs +++ /dev/null @@ -1,192 +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 NETFX_CORE // This file should only be included by the NetCore version of the formatting project, but adding a guard here just in case. -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace System.Net.Http.Internal -{ - // TODO: Remove this class after BCL makes their portable library version. - internal sealed class ConcurrentDictionary : IDictionary - { - private Dictionary _dictionary = new Dictionary(); - private object _lock = new object(); - - public ICollection Keys - { - get - { - throw new NotImplementedException(); - } - } - - public ICollection Values - { - get - { - throw new NotImplementedException(); - } - } - - public int Count - { - get - { - throw new NotImplementedException(); - } - } - - public bool IsReadOnly - { - get - { - return ((IDictionary)_dictionary).IsReadOnly; - } - } - - public TValue this[TKey key] - { - get - { - throw new NotImplementedException(); - } - set - { - throw new NotImplementedException(); - } - } - - public void Add(TKey key, TValue value) - { - throw new NotImplementedException(); - } - - public bool ContainsKey(TKey key) - { - lock (_lock) - { - return _dictionary.ContainsKey(key); - } - } - - public bool Remove(TKey key) - { - throw new NotImplementedException(); - } - - public bool TryGetValue(TKey key, out TValue value) - { - lock (_lock) - { - return _dictionary.TryGetValue(key, out value); - } - } - - public void Add(KeyValuePair item) - { - throw new NotImplementedException(); - } - - public void Clear() - { - throw new NotImplementedException(); - } - - public bool Contains(KeyValuePair item) - { - throw new NotImplementedException(); - } - - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - throw new NotImplementedException(); - } - - public bool Remove(KeyValuePair item) - { - throw new NotImplementedException(); - } - - public IEnumerator> GetEnumerator() - { - throw new NotImplementedException(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - throw new NotImplementedException(); - } - - // ConcurrentDictionary members - public bool TryRemove(TKey key, out TValue removedValue) - { - lock (_lock) - { - if (_dictionary.TryGetValue(key, out removedValue)) - { - return _dictionary.Remove(key); - } - - return false; - } - } - - public TValue GetOrAdd(TKey key, Func addValueFactory) - { - lock (_lock) - { - TValue value; - - if (!_dictionary.TryGetValue(key, out value)) - { - value = addValueFactory.Invoke(key); - _dictionary.Add(key, value); - } - - return value; - } - } - - public bool TryAdd(TKey key, TValue value) - { - lock (_lock) - { - if (_dictionary.ContainsKey(key)) - { - return false; - } - - _dictionary.Add(key, value); - return true; - } - } - - public TValue AddOrUpdate(TKey key, TValue addValue, Func updateValueFactory) - { - lock (_lock) - { - TValue value; - - // update - if (_dictionary.TryGetValue(key, out value)) - { - value = updateValueFactory.Invoke(key, value); - _dictionary[key] = value; - return value; - } - - // add - _dictionary.Add(key, addValue); - return addValue; - } - } - } -} -#endif \ No newline at end of file diff --git a/src/System.Net.Http.Formatting.NetCore/System.Net.Http.Formatting.NetCore.csproj b/src/System.Net.Http.Formatting.NetCore/System.Net.Http.Formatting.NetCore.csproj deleted file mode 100644 index 364d375d4..000000000 --- a/src/System.Net.Http.Formatting.NetCore/System.Net.Http.Formatting.NetCore.csproj +++ /dev/null @@ -1,278 +0,0 @@ - - - - - {C7060639-719B-4BD2-8A37-2F146B5A0668} - Library - Properties - System.Net.Http - System.Net.Http.Formatting - $(OutputPath)NetCore\ - $(OutputPath)$(AssemblyName).xml - $(CodeAnalysis) - ..\Strict.ruleset - /assemblycomparemode:StrongNameIgnoringVersion - false - $(DefineConstants);NETFX_CORE;ASPNETMVC;NOT_CLS_COMPLIANT - Profile259 - {786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - 1591 - - - - Properties\CommonAssemblyInfo.cs - - - Common\Error.cs - - - Common\TaskHelpers.cs - - - Common\TaskHelpersExtensions.cs - - - Common\UriQueryUtility.cs - - - Common\CollectionExtensions.cs - - - Common\ListWrapperCollection.cs - - - FormattingUtilities.cs - - - Formatting\BaseJsonMediaTypeFormatter.cs - - - Formatting\BsonMediaTypeFormatter.cs - - - Formatting\DelegatingEnumerable.cs - - - Formatting\FormDataCollection.cs - - - Formatting\FormUrlEncodedJson.cs - - - Formatting\FormUrlEncodedMediaTypeFormatter.cs - - - Formatting\IFormatterLogger.cs - - - Formatting\JsonMediaTypeFormatter.cs - - - Formatting\MediaTypeConstants.cs - - - Formatting\MediaTypeFormatter.cs - - - Formatting\MediaTypeFormatterCollection.cs - - - Formatting\MediaTypeHeaderValueExtensions.cs - - - Formatting\MediaTypeHeaderValueRange.cs - - - Formatting\ParsedMediaTypeHeaderValue.cs - - - Formatting\Parsers\FormUrlEncodedParser.cs - - - Formatting\Parsers\HttpRequestHeaderParser.cs - - - Formatting\Parsers\HttpRequestLineParser.cs - - - Formatting\Parsers\HttpResponseHeaderParser.cs - - - Formatting\Parsers\HttpStatusLineParser.cs - - - Formatting\Parsers\InternetMessageFormatHeaderParser.cs - - - Formatting\Parsers\MimeMultipartBodyPartParser.cs - - - Formatting\Parsers\MimeMultipartParser.cs - - - Formatting\Parsers\ParserState.cs - - - Formatting\StringComparisonHelper.cs - - - Formatting\XmlMediaTypeFormatter.cs - - - HttpContentFormDataExtensions.cs - - - HttpValueCollection.cs - - - UriExtensions.cs - - - - Handlers\HttpProgressEventArgs.cs - - - Handlers\ProgressContent.cs - - - Handlers\ProgressMessageHandler.cs - - - Handlers\ProgressStream.cs - - - HttpClientExtensions.cs - - - HttpClientFactory.cs - - - HttpContentExtensions.cs - - - HttpContentMessageExtensions.cs - - - HttpContentMultipartExtensions.cs - - - HttpHeaderExtensions.cs - - - HttpMessageContent.cs - - - HttpUnsortedHeaders.cs - - - HttpUnsortedRequest.cs - - - HttpUnsortedResponse.cs - - - Internal\AsyncResult.cs - - - Internal\DelegatingStream.cs - - - Internal\ReadOnlyStreamWithEncodingPreamble.cs - - - Internal\TypeExtensions.cs - - - MimeBodyPart.cs - - - MultipartFileData.cs - - - MultipartMemoryStreamProvider.cs - - - MultipartRelatedStreamProvider.cs - - - MultipartStreamProvider.cs - - - ObjectContent.cs - - - ObjectContentOfT.cs - - - PushStreamContent.cs - - - Properties\AssemblyInfo.cs - - - Properties\TransparentCommonAssemblyInfo.cs - True - True - Resources.resx - - - UnsupportedMediaTypeException.cs - - - - - - - Properties\CommonWebApiResources.Designer.cs - True - True - CommonWebApiResources.resx - - - - - Properties\CommonWebApiResources.resx - ResXFileCodeGenerator - CommonWebApiResources.Designer.cs - - - - - Properties\Resources.resx - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - - - CodeAnalysisDictionary.xml - - - - - - - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.Json.dll - - - ..\..\packages\Microsoft.Net.Http.2.2.13\lib\portable-net40+sl4+win8+wp71\System.Net.Http.dll - - - ..\..\packages\Microsoft.Net.Http.2.2.13\lib\portable-net40+sl4+win8+wp71\System.Net.Http.Extensions.dll - - - ..\..\packages\Microsoft.Net.Http.2.2.13\lib\portable-net40+sl4+win8+wp71\System.Net.Http.Primitives.dll - - - - - - \ No newline at end of file diff --git a/src/System.Net.Http.Formatting.NetCore/packages.config b/src/System.Net.Http.Formatting.NetCore/packages.config deleted file mode 100644 index 658b8185c..000000000 --- a/src/System.Net.Http.Formatting.NetCore/packages.config +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/src/System.Net.Http.Formatting.ns1_3/ICloneable.cs b/src/System.Net.Http.Formatting.ns1_3/ICloneable.cs new file mode 100644 index 000000000..1fc5b88c5 --- /dev/null +++ b/src/System.Net.Http.Formatting.ns1_3/ICloneable.cs @@ -0,0 +1,9 @@ +// No ICloneable interface in .NET Standard 1.3. + +namespace System +{ + internal interface ICloneable + { + object Clone(); + } +} diff --git a/src/System.Net.Http.Formatting.NetCore/MediaTypeHeaderValueExtensions.cs b/src/System.Net.Http.Formatting.ns1_3/MediaTypeHeaderValueExtensions.cs similarity index 100% rename from src/System.Net.Http.Formatting.NetCore/MediaTypeHeaderValueExtensions.cs rename to src/System.Net.Http.Formatting.ns1_3/MediaTypeHeaderValueExtensions.cs diff --git a/src/System.Net.Http.Formatting.ns1_3/System.Net.Http.Formatting.ns1_3.csproj b/src/System.Net.Http.Formatting.ns1_3/System.Net.Http.Formatting.ns1_3.csproj new file mode 100644 index 000000000..6ca330d34 --- /dev/null +++ b/src/System.Net.Http.Formatting.ns1_3/System.Net.Http.Formatting.ns1_3.csproj @@ -0,0 +1,73 @@ + + + + netstandard1.3 + System.Net.Http + System.Net.Http.Formatting + $(OutputPath)ns1_3\ + $(OutputPath)$(AssemblyName).xml + false + $(DefineConstants);ASPNETHTTPFORMATTING + 1591 + false + $(Configurations);CodeAnalysis + false + + + + + + + + + + + + + + + + + + + + + + + + + %(RecursiveDir)\%(Filename).cs + + + + True + CommonWebApiResources.resx + True + Properties\CommonWebApiResources.Designer.cs + + + ResXFileCodeGenerator + CommonWebApiResources.Designer.cs + Properties\CommonWebApiResources.resx + + + + True + Resources.resx + True + Properties\Resources.Designer.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Properties\Resources.resx + Designer + + + + + diff --git a/src/System.Net.Http.Formatting.NetStandard/System.Net.Http.Formatting.NetStandard.csproj b/src/System.Net.Http.Formatting.ns2_0/System.Net.Http.Formatting.ns2_0.csproj similarity index 57% rename from src/System.Net.Http.Formatting.NetStandard/System.Net.Http.Formatting.NetStandard.csproj rename to src/System.Net.Http.Formatting.ns2_0/System.Net.Http.Formatting.ns2_0.csproj index 0211316d3..823403310 100644 --- a/src/System.Net.Http.Formatting.NetStandard/System.Net.Http.Formatting.NetStandard.csproj +++ b/src/System.Net.Http.Formatting.ns2_0/System.Net.Http.Formatting.ns2_0.csproj @@ -1,79 +1,64 @@ - + netstandard2.0 System.Net.Http System.Net.Http.Formatting - $(OutputPath)NetStandard\ + $(OutputPath)ns2_0\ $(OutputPath)$(AssemblyName).xml false - $(DefineConstants);ASPNETMVC;NEWTONSOFTJSON10 + $(DefineConstants);ASPNETHTTPFORMATTING 1591 false $(Configurations);CodeAnalysis false + - - - - - - Properties\CommonAssemblyInfo.cs - + + - - Common\CollectionExtensions.cs - - - Common\Error.cs - - - Common\ListWrapperCollection.cs - - - Common\TaskHelpers.cs - - - Common\TaskHelpersExtensions.cs - - - Common\UriQueryUtility.cs - + + - + + + + + + + + %(RecursiveDir)\%(Filename).cs - - + - Properties\CommonWebApiResources.Designer.cs True - True CommonWebApiResources.resx + True + Properties\CommonWebApiResources.Designer.cs - Properties\CommonWebApiResources.resx ResXFileCodeGenerator CommonWebApiResources.Designer.cs + Properties\CommonWebApiResources.resx - - - + + True - True Resources.resx + True + Properties\Resources.Designer.cs - Properties\Resources.resx ResXFileCodeGenerator Resources.Designer.cs + Properties\Resources.resx Designer - - - - CodeAnalysisDictionary.xml - + + diff --git a/src/System.Net.Http.Formatting/ByteRangeStreamContent.cs b/src/System.Net.Http.Formatting/ByteRangeStreamContent.cs index 587a0fd7f..40edaddb8 100644 --- a/src/System.Net.Http.Formatting/ByteRangeStreamContent.cs +++ b/src/System.Net.Http.Formatting/ByteRangeStreamContent.cs @@ -13,8 +13,8 @@ namespace System.Net.Http { /// /// implementation which provides a byte range view over a stream used to generate HTTP - /// 206 (Partial Content) byte range responses. The supports one or more - /// byte ranges regardless of whether the ranges are consecutive or not. If there is only one range then a + /// 206 (Partial Content) byte range responses. The supports one or more + /// byte ranges regardless of whether the ranges are consecutive or not. If there is only one range then a /// single partial response body containing a Content-Range header is generated. If there are more than one /// ranges then a multipart/byteranges response is generated where each body part contains a range indicated /// by the associated Content-Range header field. @@ -33,9 +33,9 @@ public class ByteRangeStreamContent : HttpContent /// /// implementation which provides a byte range view over a stream used to generate HTTP - /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend - /// of the selected resource represented by the parameter then an - /// is thrown indicating the valid Content-Range of the content. + /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend + /// of the selected resource represented by the parameter then an + /// is thrown indicating the valid Content-Range of the content. /// /// The stream over which to generate a byte range view. /// The range or ranges, typically obtained from the Range HTTP request header field. @@ -47,9 +47,9 @@ public ByteRangeStreamContent(Stream content, RangeHeaderValue range, string med /// /// implementation which provides a byte range view over a stream used to generate HTTP - /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend - /// of the selected resource represented by the parameter then an - /// is thrown indicating the valid Content-Range of the content. + /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend + /// of the selected resource represented by the parameter then an + /// is thrown indicating the valid Content-Range of the content. /// /// The stream over which to generate a byte range view. /// The range or ranges, typically obtained from the Range HTTP request header field. @@ -62,9 +62,9 @@ public ByteRangeStreamContent(Stream content, RangeHeaderValue range, string med /// /// implementation which provides a byte range view over a stream used to generate HTTP - /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend - /// of the selected resource represented by the parameter then an - /// is thrown indicating the valid Content-Range of the content. + /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend + /// of the selected resource represented by the parameter then an + /// is thrown indicating the valid Content-Range of the content. /// /// The stream over which to generate a byte range view. /// The range or ranges, typically obtained from the Range HTTP request header field. @@ -76,9 +76,9 @@ public ByteRangeStreamContent(Stream content, RangeHeaderValue range, MediaTypeH /// /// implementation which provides a byte range view over a stream used to generate HTTP - /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend - /// of the selected resource represented by the parameter then an - /// is thrown indicating the valid Content-Range of the content. + /// 206 (Partial Content) byte range responses. If none of the requested ranges overlap with the current extend + /// of the selected resource represented by the parameter then an + /// is thrown indicating the valid Content-Range of the content. /// /// The stream over which to generate a byte range view. /// The range or ranges, typically obtained from the Range HTTP request header field. diff --git a/src/System.Net.Http.Formatting/Formatting/BaseJsonMediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/BaseJsonMediaTypeFormatter.cs index b30a22edf..c25bdba46 100644 --- a/src/System.Net.Http.Formatting/Formatting/BaseJsonMediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/BaseJsonMediaTypeFormatter.cs @@ -10,9 +10,7 @@ using System.Threading.Tasks; using System.Web.Http; using Newtonsoft.Json; -#if !NETFX_CORE using Newtonsoft.Json.Serialization; -#endif namespace System.Net.Http.Formatting { @@ -21,12 +19,10 @@ namespace System.Net.Http.Formatting /// public abstract class BaseJsonMediaTypeFormatter : MediaTypeFormatter { - // Though MaxDepth is not supported in portable library, we still override JsonReader's MaxDepth + // Though MaxDepth is not supported in netstandard1.3, we still override JsonReader's MaxDepth private int _maxDepth = FormattingUtilities.DefaultMaxDepth; -#if !NETFX_CORE // DataContractResolver is not supported in portable library private readonly IContractResolver _defaultContractResolver; -#endif private JsonSerializerSettings _jsonSerializerSettings; @@ -36,9 +32,7 @@ public abstract class BaseJsonMediaTypeFormatter : MediaTypeFormatter protected BaseJsonMediaTypeFormatter() { // Initialize serializer settings -#if !NETFX_CORE // DataContractResolver is not supported in portable library _defaultContractResolver = new JsonContractResolver(this); -#endif _jsonSerializerSettings = CreateDefaultSerializerSettings(); // Set default supported character encodings @@ -50,19 +44,15 @@ protected BaseJsonMediaTypeFormatter() /// Initializes a new instance of the class. /// /// The instance to copy settings from. -#if !NETFX_CORE [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "MaxDepth is sealed in existing subclasses and its documentation carries warnings.")] -#endif protected BaseJsonMediaTypeFormatter(BaseJsonMediaTypeFormatter formatter) : base(formatter) { Contract.Assert(formatter != null); SerializerSettings = formatter.SerializerSettings; -#if !NETFX_CORE // MaxDepth is not supported in portable library and so _maxDepth never changes there MaxDepth = formatter._maxDepth; -#endif } /// @@ -82,7 +72,6 @@ public JsonSerializerSettings SerializerSettings } } -#if !NETFX_CORE // MaxDepth is not supported in portable library /// /// Gets or sets the maximum depth allowed by this formatter. /// @@ -106,22 +95,15 @@ public virtual int MaxDepth _maxDepth = value; } } -#endif /// /// Creates a instance with the default settings used by the . /// -#if NETFX_CORE - [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "This could only be static half the time.")] -#endif public JsonSerializerSettings CreateDefaultSerializerSettings() { return new JsonSerializerSettings() { -#if !NETFX_CORE // DataContractResolver is not supported in portable library ContractResolver = _defaultContractResolver, -#endif - MissingMemberHandling = MissingMemberHandling.Ignore, // Do not change this setting diff --git a/src/System.Net.Http.Formatting/Formatting/BsonMediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/BsonMediaTypeFormatter.cs index cf2608de7..fe6fdef23 100644 --- a/src/System.Net.Http.Formatting/Formatting/BsonMediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/BsonMediaTypeFormatter.cs @@ -11,12 +11,7 @@ using System.Threading.Tasks; using System.Web.Http; using Newtonsoft.Json; -#if NEWTONSOFTJSON10 -using BsonReader = Newtonsoft.Json.Bson.BsonDataReader; -using BsonWriter = Newtonsoft.Json.Bson.BsonDataWriter; -#else using Newtonsoft.Json.Bson; -#endif namespace System.Net.Http.Formatting { @@ -65,7 +60,6 @@ public static MediaTypeHeaderValue DefaultMediaType } } -#if !NETFX_CORE // MaxDepth and DBNull not supported in portable library; no need to override there /// public sealed override int MaxDepth { @@ -106,7 +100,6 @@ public override Task ReadFromStreamAsync(Type type, Stream readStream, H return base.ReadFromStreamAsync(type, readStream, content, formatterLogger); } } -#endif /// public override object ReadFromStream(Type type, Stream readStream, Encoding effectiveEncoding, @@ -200,7 +193,7 @@ public override JsonReader CreateJsonReader(Type type, Stream readStream, Encodi throw Error.ArgumentNull("effectiveEncoding"); } - BsonReader reader = new BsonReader(new BinaryReader(readStream, effectiveEncoding)); + BsonDataReader reader = new BsonDataReader(new BinaryReader(readStream, effectiveEncoding)); try { @@ -239,14 +232,13 @@ public override void WriteToStream(Type type, object value, Stream writeStream, if (value == null) { - // Cannot serialize null at the top level. Json.Net throws Newtonsoft.Json.JsonWriterException : Error - // writing Null value. BSON must start with an Object or Array. Path ''. Fortunately + // Cannot serialize null at the top level. Json.Net throws Newtonsoft.Json.JsonWriterException : Error + // writing Null value. BSON must start with an Object or Array. Path ''. Fortunately // BaseJsonMediaTypeFormatter.ReadFromStream(Type, Stream, HttpContent, IFormatterLogger) treats zero- // length content as null or the default value of a struct. return; } -#if !NETFX_CORE // DBNull not supported in portable library if (value == DBNull.Value) { // ReadFromStreamAsync() override above converts null to DBNull.Value if given Type is DBNull; normally @@ -257,7 +249,6 @@ public override void WriteToStream(Type type, object value, Stream writeStream, // rather than null, and not meet the receiver's expectations. return; } -#endif // See comments in ReadFromStream() above about this special case and the need to include byte[] in it. // Using runtime type here because Json.Net will throw during serialization whenever it cannot handle the @@ -297,7 +288,7 @@ public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encod throw Error.ArgumentNull("effectiveEncoding"); } - return new BsonWriter(new BinaryWriter(writeStream, effectiveEncoding)); + return new BsonDataWriter(new BinaryWriter(writeStream, effectiveEncoding)); } // Return true if Json.Net will likely convert value of given type to a Json primitive, not JsonArray nor @@ -307,15 +298,10 @@ private static bool IsSimpleType(Type type) { Contract.Assert(type != null); - bool isSimpleType; -#if NETFX_CORE // TypeDescriptor is not supported in portable library - isSimpleType = type.IsValueType() || type == typeof(string); -#else // CanConvertFrom() check is similar to MVC / Web API ModelMetadata.IsComplexType getters. This is // sufficient for many cases but Json.Net uses JsonConverterAttribute and built-in converters, not type // descriptors. - isSimpleType = TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string)); -#endif + bool isSimpleType = TypeDescriptor.GetConverter(type).CanConvertFrom(typeof(string)); return isSimpleType; } diff --git a/src/System.Net.Http.Formatting/Formatting/BufferedMediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/BufferedMediaTypeFormatter.cs index 29554fd07..908ba6221 100644 --- a/src/System.Net.Http.Formatting/Formatting/BufferedMediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/BufferedMediaTypeFormatter.cs @@ -13,7 +13,7 @@ namespace System.Net.Http.Formatting { /// - /// Base class for writing a synchronous formatter on top of the asynchronous formatter infrastructure. + /// Base class for writing a synchronous formatter on top of the asynchronous formatter infrastructure. /// This does not guarantee non-blocking threads. The only way to guarantee that we don't block a thread on IO is /// to use the asynchronous . /// @@ -219,13 +219,13 @@ private static Stream GetBufferStream(Stream innerStream, int bufferSize) { Contract.Assert(innerStream != null); - // We wrap the inner stream in a non-closing delegating stream so that we allow the user + // We wrap the inner stream in a non-closing delegating stream so that we allow the user // to use the using (...) pattern yet not break the contract of formatters not closing // the inner stream. Stream nonClosingStream = new NonClosingDelegatingStream(innerStream); - // This uses a naive buffering. BufferedStream() will block the thread while it drains the buffer. - // We can explore a smarter implementation that async drains the buffer. + // This uses a naive buffering. BufferedStream() will block the thread while it drains the buffer. + // We can explore a smarter implementation that async drains the buffer. return new BufferedStream(nonClosingStream, bufferSize); } } diff --git a/src/System.Net.Http.Formatting/Formatting/DefaultContentNegotiator.cs b/src/System.Net.Http.Formatting/Formatting/DefaultContentNegotiator.cs index 94b0f9b99..0cf5c36d7 100644 --- a/src/System.Net.Http.Formatting/Formatting/DefaultContentNegotiator.cs +++ b/src/System.Net.Http.Formatting/Formatting/DefaultContentNegotiator.cs @@ -95,7 +95,7 @@ public virtual ContentNegotiationResult Negotiate(Type type, HttpRequestMessage /// /// Determine how well each formatter matches by associating a value - /// with the formatter. Then associate the quality of the match based on q-factors and other parameters. The result of this + /// with the formatter. Then associate the quality of the match based on q-factors and other parameters. The result of this /// method is a collection of the matches found categorized and assigned a quality value. /// /// The type to be serialized. @@ -123,7 +123,7 @@ protected virtual Collection ComputeFormatterMatches(Ty // Go through each formatter to find how well it matches. ListWrapperCollection matches = new ListWrapperCollection(); MediaTypeFormatter[] writingFormatters = GetWritingFormatters(formatters); - for (int i = 0; i < writingFormatters.Length; i++) + for (int i = 0; i < writingFormatters.Length; i++) { MediaTypeFormatter formatter = writingFormatters[i]; MediaTypeFormatterMatch match = null; @@ -161,7 +161,7 @@ protected virtual Collection ComputeFormatterMatches(Ty continue; } - // Check whether we should match on type or stop the matching process. + // Check whether we should match on type or stop the matching process. // The latter is used to generate 406 (Not Acceptable) status codes. bool shouldMatchOnType = ShouldMatchOnType(sortedAcceptValues); @@ -459,7 +459,7 @@ protected virtual MediaTypeFormatterMatch MatchRequestMediaType(HttpRequestMessa /// /// Determine whether to match on type or not. This is used to determine whether to /// generate a 406 response or use the default media type formatter in case there - /// is no match against anything in the request. If ExcludeMatchOnTypeOnly is true + /// is no match against anything in the request. If ExcludeMatchOnTypeOnly is true /// then we don't match on type unless there are no accept headers. /// /// The sorted accept header values to match. @@ -504,7 +504,7 @@ protected virtual MediaTypeFormatterMatch MatchType(Type type, MediaTypeFormatte } /// - /// Sort Accept header values and related header field values with similar syntax rules + /// Sort Accept header values and related header field values with similar syntax rules /// (if more than 1) in descending order based on q-factor. /// /// The header values to sort. @@ -529,7 +529,7 @@ protected virtual IEnumerable SortMediaTypeWith } /// - /// Sort Accept-Charset, Accept-Encoding, Accept-Language and related header field values with similar syntax rules + /// Sort Accept-Charset, Accept-Encoding, Accept-Language and related header field values with similar syntax rules /// (if more than 1) in descending order based on q-factor. /// /// The header values to sort. @@ -554,7 +554,7 @@ protected virtual IEnumerable SortStringWithQualit } /// - /// Evaluates whether a match is better than the current match and if so returns the replacement; otherwise returns the + /// Evaluates whether a match is better than the current match and if so returns the replacement; otherwise returns the /// current match. /// protected virtual MediaTypeFormatterMatch UpdateBestMatch(MediaTypeFormatterMatch current, MediaTypeFormatterMatch potentialReplacement) diff --git a/src/System.Net.Http.Formatting/Formatting/FormDataCollection.cs b/src/System.Net.Http.Formatting/Formatting/FormDataCollection.cs index 21504147b..74a5ea549 100644 --- a/src/System.Net.Http.Formatting/Formatting/FormDataCollection.cs +++ b/src/System.Net.Http.Formatting/Formatting/FormDataCollection.cs @@ -5,40 +5,29 @@ using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; -#if !NETFX_CORE using System.Net.Http.Formatting.Internal; -#endif using System.Net.Http.Formatting.Parsers; using System.Text; using System.Threading; using System.Web.Http; -#if NETFX_CORE -using NameValueCollection = System.Net.Http.Formatting.HttpValueCollection; -#endif - namespace System.Net.Http.Formatting { /// /// Represent the form data. - /// - This has 100% fidelity (including ordering, which is important for deserializing ordered array). - /// - using interfaces allows us to optimize the implementation. E.g., we can avoid eagerly string-splitting a 10gb file. - /// - This also provides a convenient place to put extension methods. + /// - This has 100% fidelity (including ordering, which is important for deserializing ordered array). + /// - using interfaces allows us to optimize the implementation. E.g., we can avoid eagerly string-splitting a 10gb file. + /// - This also provides a convenient place to put extension methods. /// -#if NETFX_CORE - internal -#else - public -#endif - class FormDataCollection : IEnumerable> + public class FormDataCollection : IEnumerable> { private readonly IEnumerable> _pairs; private NameValueCollection _nameValueCollection; /// - /// Initialize a form collection around incoming data. - /// The key value enumeration should be immutable. + /// Initialize a form collection around incoming data. + /// The key value enumeration should be immutable. /// /// incoming set of key value pairs. Ordering is preserved. [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is the convention for representing FormData")] @@ -52,8 +41,8 @@ public FormDataCollection(IEnumerable> pairs) } /// - /// Initialize a form collection from a query string. - /// Uri and FormURl body have the same schema. + /// Initialize a form collection from a query string. + /// Uri and FormURl body have the same schema. /// public FormDataCollection(Uri uri) { @@ -136,7 +125,7 @@ public NameValueCollection ReadAsNameValueCollection() } /// - /// Get values associated with a given key. If there are multiple values, they're concatenated. + /// Get values associated with a given key. If there are multiple values, they're concatenated. /// public string Get(string key) { @@ -144,7 +133,7 @@ public string Get(string key) } /// - /// Get a value associated with a given key. + /// Get a value associated with a given key. /// public string[] GetValues(string key) { diff --git a/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedJson.cs b/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedJson.cs index 6a295c72c..cb3d53917 100644 --- a/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedJson.cs +++ b/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedJson.cs @@ -13,9 +13,9 @@ namespace System.Net.Http.Formatting { /// - /// This class provides a low-level API for parsing HTML form URL-encoded data, also known as application/x-www-form-urlencoded - /// data. The output of the parser is a instance. - /// This is a low-level API intended for use by other APIs. It has been optimized for performance and + /// This class provides a low-level API for parsing HTML form URL-encoded data, also known as application/x-www-form-urlencoded + /// data. The output of the parser is a instance. + /// This is a low-level API intended for use by other APIs. It has been optimized for performance and /// is not intended to be called directly from user code. /// internal static class FormUrlEncodedJson @@ -31,7 +31,7 @@ internal static class FormUrlEncodedJson /// /// Parses a collection of query string values as a . /// - /// This is a low-level API intended for use by other APIs. It has been optimized for performance and + /// This is a low-level API intended for use by other APIs. It has been optimized for performance and /// is not intended to be called directly from user code. /// The collection of query string name-value pairs parsed in lexical order. Both names /// and values must be un-escaped so that they don't contain any encoding. @@ -44,7 +44,7 @@ public static JObject Parse(IEnumerable> nameValueP /// /// Parses a collection of query string values as a . /// - /// This is a low-level API intended for use by other APIs. It has been optimized for performance and + /// This is a low-level API intended for use by other APIs. It has been optimized for performance and /// is not intended to be called directly from user code. /// The collection of query string name-value pairs parsed in lexical order. Both names /// and values must be un-escaped so that they don't contain any encoding. @@ -58,7 +58,7 @@ public static JObject Parse(IEnumerable> nameValueP /// /// Parses a collection of query string values as a . /// - /// This is a low-level API intended for use by other APIs. It has been optimized for performance and + /// This is a low-level API intended for use by other APIs. It has been optimized for performance and /// is not intended to be called directly from user code. /// The collection of query string name-value pairs parsed in lexical order. Both names /// and values must be un-escaped so that they don't contain any encoding. @@ -72,7 +72,7 @@ public static bool TryParse(IEnumerable> nameValueP /// /// Parses a collection of query string values as a . /// - /// This is a low-level API intended for use by other APIs. It has been optimized for performance and + /// This is a low-level API intended for use by other APIs. It has been optimized for performance and /// is not intended to be called directly from user code. /// The collection of query string name-value pairs parsed in lexical order. Both names /// and values must be un-escaped so that they don't contain any encoding. @@ -87,7 +87,7 @@ public static bool TryParse(IEnumerable> nameValueP /// /// Parses a collection of query string values as a . /// - /// This is a low-level API intended for use by other APIs. It has been optimized for performance and + /// This is a low-level API intended for use by other APIs. It has been optimized for performance and /// is not intended to be called directly from user code. /// The collection of query string name-value pairs parsed in lexical order. Both names /// and values must be un-escaped so that they don't contain any encoding. @@ -112,7 +112,7 @@ private static JObject ParseInternal(IEnumerable> n string key = nameValuePair.Key; string value = nameValuePair.Value; - // value is preserved, even if it's null, "undefined", "null", String.Empty, etc when converting to JToken. + // value is preserved, even if it's null, "undefined", "null", String.Empty, etc when converting to JToken. if (key == null) { diff --git a/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedMediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedMediaTypeFormatter.cs index 994ab173b..5c8d883af 100644 --- a/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedMediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/FormUrlEncodedMediaTypeFormatter.cs @@ -13,7 +13,7 @@ namespace System.Net.Http.Formatting { /// - /// class for handling HTML form URL-ended data, also known as application/x-www-form-urlencoded. + /// class for handling HTML form URL-ended data, also known as application/x-www-form-urlencoded. /// public class FormUrlEncodedMediaTypeFormatter : MediaTypeFormatter { @@ -119,7 +119,7 @@ public override bool CanReadType(Type type) throw Error.ArgumentNull("type"); } - // Can't read arbitrary types. + // Can't read arbitrary types. return type == typeof(FormDataCollection) || FormattingUtilities.IsJTokenType(type); } @@ -193,7 +193,7 @@ private object ReadFromStream(Type type, Stream readStream) } /// - /// Reads all name-value pairs encoded as HTML Form URL encoded data and add them to + /// Reads all name-value pairs encoded as HTML Form URL encoded data and add them to /// a collection as UNescaped URI strings. /// /// Stream to read from. diff --git a/src/System.Net.Http.Formatting/Formatting/JsonContractResolver.cs b/src/System.Net.Http.Formatting/Formatting/JsonContractResolver.cs index 95543f96b..2dd063842 100644 --- a/src/System.Net.Http.Formatting/Formatting/JsonContractResolver.cs +++ b/src/System.Net.Http.Formatting/Formatting/JsonContractResolver.cs @@ -29,8 +29,11 @@ public JsonContractResolver(MediaTypeFormatter formatter) } _formatter = formatter; + +#if !NETSTANDARD1_3 // Need this setting to have [Serializable] types serialized correctly IgnoreSerializableAttribute = false; +#endif } // Determines whether a member is required or not and sets the appropriate JsonProperty settings diff --git a/src/System.Net.Http.Formatting/Formatting/JsonMediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/JsonMediaTypeFormatter.cs index 019c8feb2..a3bb36060 100644 --- a/src/System.Net.Http.Formatting/Formatting/JsonMediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/JsonMediaTypeFormatter.cs @@ -1,26 +1,20 @@ // 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 !NETFX_CORE using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; -#endif using System.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; -#if !NETFX_CORE +#if !NETSTANDARD1_3 // Unnecessary when targeting netstandard1.3. using System.Net.Http.Internal; -using System.Runtime.Serialization.Json; #endif +using System.Runtime.Serialization.Json; using System.Text; using System.Threading; -#if !NETFX_CORE using System.Threading.Tasks; -#endif using System.Web.Http; -#if !NETFX_CORE using System.Xml; -#endif using Newtonsoft.Json; namespace System.Net.Http.Formatting @@ -30,11 +24,9 @@ namespace System.Net.Http.Formatting /// public class JsonMediaTypeFormatter : BaseJsonMediaTypeFormatter { -#if !NETFX_CORE // DataContractJsonSerializer and MediaTypeMappings are not supported in portable library - private ConcurrentDictionary _dataContractSerializerCache = new ConcurrentDictionary(); - private XmlDictionaryReaderQuotas _readerQuotas = FormattingUtilities.CreateDefaultReaderQuotas(); - private RequestHeaderMapping _requestHeaderMapping; -#endif + private readonly ConcurrentDictionary _dataContractSerializerCache = new ConcurrentDictionary(); + private readonly XmlDictionaryReaderQuotas _readerQuotas = FormattingUtilities.CreateDefaultReaderQuotas(); + private readonly RequestHeaderMapping _requestHeaderMapping; /// /// Initializes a new instance of the class. @@ -45,10 +37,8 @@ public JsonMediaTypeFormatter() SupportedMediaTypes.Add(MediaTypeConstants.ApplicationJsonMediaType); SupportedMediaTypes.Add(MediaTypeConstants.TextJsonMediaType); -#if !NETFX_CORE // MediaTypeMappings are not supported in portable library _requestHeaderMapping = new XmlHttpRequestHeaderMapping(); MediaTypeMappings.Add(_requestHeaderMapping); -#endif } /// @@ -60,10 +50,7 @@ protected JsonMediaTypeFormatter(JsonMediaTypeFormatter formatter) { Contract.Assert(formatter != null); -#if !NETFX_CORE // UseDataContractJsonSerializer is not supported in portable library UseDataContractJsonSerializer = formatter.UseDataContractJsonSerializer; -#endif - Indent = formatter.Indent; } @@ -84,7 +71,6 @@ public static MediaTypeHeaderValue DefaultMediaType get { return MediaTypeConstants.ApplicationJsonMediaType; } } -#if !NETFX_CORE // DataContractJsonSerializer is not supported in portable library /// /// Gets or sets a value indicating whether to use by default. /// @@ -92,14 +78,12 @@ public static MediaTypeHeaderValue DefaultMediaType /// true if use by default; otherwise, false. The default is false. /// public bool UseDataContractJsonSerializer { get; set; } -#endif /// - /// Gets or sets a value indicating whether to indent elements when writing data. + /// Gets or sets a value indicating whether to indent elements when writing data. /// public bool Indent { get; set; } -#if !NETFX_CORE // MaxDepth not supported in portable library; no need to override there /// public sealed override int MaxDepth { @@ -113,7 +97,6 @@ public sealed override int MaxDepth _readerQuotas.MaxDepth = value; } } -#endif /// public override JsonReader CreateJsonReader(Type type, Stream readStream, Encoding effectiveEncoding) @@ -163,7 +146,6 @@ public override JsonWriter CreateJsonWriter(Type type, Stream writeStream, Encod return jsonWriter; } -#if !NETFX_CORE // DataContractJsonSerializer not supported in portable library; no need to override there /// public override bool CanReadType(Type type) { @@ -233,10 +215,21 @@ public override object ReadFromStream(Type type, Stream readStream, Encoding eff if (UseDataContractJsonSerializer) { DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type); - using (XmlReader reader = JsonReaderWriterFactory.CreateJsonReader(new NonClosingDelegatingStream(readStream), effectiveEncoding, _readerQuotas, null)) - { - return dataContractSerializer.ReadObject(reader); - } + +#if NETSTANDARD1_3 // Unreachable when targeting netstandard1.3. Return just to satisfy the compiler. + return null; +#else + // DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. Convert to UTF8 as we read. + Stream innerStream = + string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase) ? + new NonClosingDelegatingStream(readStream) : + new TranscodingStream(readStream, effectiveEncoding, Utf8Encoding, leaveOpen: true); + + // XmlDictionaryReader will always dispose of innerStream when we dispose of the reader. + using XmlDictionaryReader reader = + JsonReaderWriterFactory.CreateJsonReader(innerStream, Utf8Encoding, _readerQuotas, onClose: null); + return dataContractSerializer.ReadObject(reader); +#endif } else { @@ -294,10 +287,18 @@ public override void WriteToStream(Type type, object value, Stream writeStream, } } - DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type); - using (XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(writeStream, effectiveEncoding, ownsStream: false)) + WritePreamble(writeStream, effectiveEncoding); + if (string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase)) { - dataContractSerializer.WriteObject(writer, value); + WriteObject(writeStream, type, value); + } + else + { + // JsonReaderWriterFactory is internal and DataContractJsonSerializer only writes UTF8 for the + // netstandard1.3 project. In addition, DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. + // Convert to UTF8 as we write. + using var innerStream = new TranscodingStream(writeStream, effectiveEncoding, Utf8Encoding, leaveOpen: true); + WriteObject(innerStream, type, value); } } else @@ -306,11 +307,35 @@ public override void WriteToStream(Type type, object value, Stream writeStream, } } + private void WriteObject(Stream stream, Type type, object value) + { + DataContractJsonSerializer dataContractSerializer = GetDataContractSerializer(type); + +#if !NETSTANDARD1_3 // Unreachable when targeting netstandard1.3. + // Do not dispose of the stream. WriteToStream handles that where it's needed. + using XmlWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, Utf8Encoding, ownsStream: false); + dataContractSerializer.WriteObject(writer, value); +#endif + } + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Catch all is around an extensibile method")] private DataContractJsonSerializer CreateDataContractSerializer(Type type, bool throwOnError) { Contract.Assert(type != null); +#if NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3 + if (throwOnError) + { + throw new PlatformNotSupportedException(Error.Format( + Properties.Resources.JsonMediaTypeFormatter_DCS_NotSupported, + nameof(UseDataContractJsonSerializer))); + } + else + { + return null; + } +#else + DataContractJsonSerializer serializer = null; Exception exception = null; @@ -318,6 +343,7 @@ private DataContractJsonSerializer CreateDataContractSerializer(Type type, bool { // Verify that type is a valid data contract by forcing the serializer to try to create a data contract FormattingUtilities.XsdDataContractExporter.GetRootElementName(type); + serializer = CreateDataContractSerializer(type); } catch (Exception caught) @@ -342,6 +368,7 @@ private DataContractJsonSerializer CreateDataContractSerializer(Type type, bool } return serializer; +#endif } /// @@ -378,6 +405,5 @@ private DataContractJsonSerializer GetDataContractSerializer(Type type) return serializer; } -#endif } } diff --git a/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatter.cs index dd7731e1d..20eace069 100644 --- a/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatter.cs @@ -1,17 +1,12 @@ // 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 !NETFX_CORE // In portable library we have our own implementation of Concurrent Dictionary which is in the internal namespace using System.Collections.Concurrent; -#endif using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Net.Http.Headers; -#if NETFX_CORE // In portable library we have our own implementation of Concurrent Dictionary which is in the internal namespace -using System.Net.Http.Internal; -#endif using System.Reflection; using System.Text; using System.Threading; @@ -25,6 +20,8 @@ namespace System.Net.Http.Formatting /// public abstract class MediaTypeFormatter { + private protected static readonly Encoding Utf8Encoding = + new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private const int DefaultMinHttpCollectionKeys = 1; private const int DefaultMaxHttpCollectionKeys = 1000; // same default as ASPNET private const string IWellKnownComparerTypeName = "System.IWellKnownStringEqualityComparer, mscorlib, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089"; @@ -36,10 +33,8 @@ public abstract class MediaTypeFormatter private readonly List _supportedMediaTypes; private readonly List _supportedEncodings; -#if !NETFX_CORE // No MediaTypeMappings in portable library or IRequiredMemberSelector (no model state on client) private readonly List _mediaTypeMappings; private IRequiredMemberSelector _requiredMemberSelector; -#endif /// /// Initializes a new instance of the class. @@ -50,10 +45,8 @@ protected MediaTypeFormatter() SupportedMediaTypes = new MediaTypeHeaderValueCollection(_supportedMediaTypes); _supportedEncodings = new List(); SupportedEncodings = new Collection(_supportedEncodings); -#if !NETFX_CORE // No MediaTypeMappings in portable library _mediaTypeMappings = new List(); MediaTypeMappings = new Collection(_mediaTypeMappings); -#endif } /// @@ -71,15 +64,13 @@ protected MediaTypeFormatter(MediaTypeFormatter formatter) SupportedMediaTypes = formatter.SupportedMediaTypes; _supportedEncodings = formatter._supportedEncodings; SupportedEncodings = formatter.SupportedEncodings; -#if !NETFX_CORE // No MediaTypeMappings in portable library or IRequiredMemberSelector (no model state on client) _mediaTypeMappings = formatter._mediaTypeMappings; MediaTypeMappings = formatter.MediaTypeMappings; _requiredMemberSelector = formatter._requiredMemberSelector; -#endif } /// - /// Gets or sets the maximum number of keys stored in a NameValueCollection. + /// Gets or sets the maximum number of keys stored in a NameValueCollection. /// public static int MaxHttpCollectionKeys { @@ -117,7 +108,7 @@ internal List SupportedMediaTypesInternal /// /// Gets the mutable collection of character encodings supported by /// this instance. The encodings are - /// used when reading or writing data. + /// used when reading or writing data. /// public Collection SupportedEncodings { get; private set; } @@ -126,7 +117,6 @@ internal List SupportedEncodingsInternal get { return _supportedEncodings; } } -#if !NETFX_CORE // No MediaTypeMappings in portable library /// /// Gets the mutable collection of elements used /// by this instance to determine the @@ -138,9 +128,7 @@ internal List MediaTypeMappingsInternal { get { return _mediaTypeMappings; } } -#endif -#if !NETFX_CORE // IRequiredMemberSelector is not in portable libraries because there is no model state on the client. /// /// Gets or sets the used to determine required members. /// @@ -155,7 +143,6 @@ public virtual IRequiredMemberSelector RequiredMemberSelector _requiredMemberSelector = value; } } -#endif internal virtual bool CanWriteAnyTypes { @@ -504,6 +491,15 @@ public static object GetDefaultValueForType(Type type) return null; } + private protected static void WritePreamble(Stream stream, Encoding encoding) + { + byte[] bytes = encoding.GetPreamble(); + if (bytes.Length > 0) + { + stream.Write(bytes, 0, bytes.Length); + } + } + /// /// Collection class that validates it contains only instances /// that are not null and not media ranges. diff --git a/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterCollection.cs b/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterCollection.cs index 17a4959ba..864eacded 100644 --- a/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterCollection.cs +++ b/src/System.Net.Http.Formatting/Formatting/MediaTypeFormatterCollection.cs @@ -198,9 +198,7 @@ public MediaTypeFormatter FindWriter(Type type, MediaTypeHeaderValue mediaType) public static bool IsTypeExcludedFromValidation(Type type) { return -#if !NETFX_CORE typeof(XmlNode).IsAssignableFrom(type) || -#endif typeof(FormDataCollection).IsAssignableFrom(type) || FormattingUtilities.IsJTokenType(type) || typeof(XObject).IsAssignableFrom(type) || @@ -257,7 +255,11 @@ private static IEnumerable CreateDefaultFormatters() return new MediaTypeFormatter[] { new JsonMediaTypeFormatter(), - new XmlMediaTypeFormatter(), + new XmlMediaTypeFormatter() +#if NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3. Cannot use DCS. + { UseXmlSerializer = true } +#endif + , new FormUrlEncodedMediaTypeFormatter() }; } diff --git a/src/System.Net.Http.Formatting/Formatting/MediaTypeHeaderValueExtensions.cs b/src/System.Net.Http.Formatting/Formatting/MediaTypeHeaderValueExtensions.cs index a0cae45d0..7f58a0d18 100644 --- a/src/System.Net.Http.Formatting/Formatting/MediaTypeHeaderValueExtensions.cs +++ b/src/System.Net.Http.Formatting/Formatting/MediaTypeHeaderValueExtensions.cs @@ -17,8 +17,8 @@ internal static class MediaTypeHeaderValueExtensions /// /// Determines whether two instances match. The instance /// is said to match if and only if - /// is a strict subset of the values and parameters of . - /// That is, if the media type and media type parameters of are all present + /// is a strict subset of the values and parameters of . + /// That is, if the media type and media type parameters of are all present /// and match those of then it is a match even though may have additional /// parameters. /// @@ -34,8 +34,8 @@ public static bool IsSubsetOf(this MediaTypeHeaderValue mediaType1, MediaTypeHea /// /// Determines whether two instances match. The instance /// is said to match if and only if - /// is a strict subset of the values and parameters of . - /// That is, if the media type and media type parameters of are all present + /// is a strict subset of the values and parameters of . + /// That is, if the media type and media type parameters of are all present /// and match those of then it is a match even though may have additional /// parameters. /// @@ -75,12 +75,12 @@ public static bool IsSubsetOf(this MediaTypeHeaderValue mediaType1, MediaTypeHea } } - // So far we either have a full match or a subset match. Now check that all of + // So far we either have a full match or a subset match. Now check that all of // mediaType1's parameters are present and equal in mediatype2 // Optimize for the common case where the parameters inherit from Collection and cache the count which is faster for Collection. Collection parameters1 = mediaType1.Parameters.AsCollection(); int parameterCount1 = parameters1.Count; - Collection parameters2 = mediaType2.Parameters.AsCollection(); + Collection parameters2 = mediaType2.Parameters.AsCollection(); int parameterCount2 = parameters2.Count; for (int i = 0; i < parameterCount1; i++) { diff --git a/src/System.Net.Http.Formatting/Formatting/MediaTypeWithQualityHeaderValueComparer.cs b/src/System.Net.Http.Formatting/Formatting/MediaTypeWithQualityHeaderValueComparer.cs index 549d2272f..277759254 100644 --- a/src/System.Net.Http.Formatting/Formatting/MediaTypeWithQualityHeaderValueComparer.cs +++ b/src/System.Net.Http.Formatting/Formatting/MediaTypeWithQualityHeaderValueComparer.cs @@ -8,7 +8,7 @@ namespace System.Net.Http.Formatting { /// Implementation of that can compare accept media type header fields - /// based on their quality values (a.k.a q-values). See + /// based on their quality values (a.k.a q-values). See /// for a comparer for other content negotiation /// header field q-values. internal class MediaTypeWithQualityHeaderValueComparer : IComparer @@ -26,8 +26,8 @@ public static MediaTypeWithQualityHeaderValueComparer QualityComparer /// /// Compares two based on their quality value (a.k.a their "q-value"). - /// Values with identical q-values are considered equal (i.e the result is 0) with the exception that sub-type wild-cards are - /// considered less than specific media types and full wild-cards are considered less than sub-type wild-cards. This allows to + /// Values with identical q-values are considered equal (i.e the result is 0) with the exception that sub-type wild-cards are + /// considered less than specific media types and full wild-cards are considered less than sub-type wild-cards. This allows to /// sort a sequence of following their q-values in the order of specific media types, /// sub-type wildcards, and last any full wild-cards. /// diff --git a/src/System.Net.Http.Formatting/Formatting/ParsedMediaTypeHeaderValue.cs b/src/System.Net.Http.Formatting/Formatting/ParsedMediaTypeHeaderValue.cs index 057730391..fa1e4c259 100644 --- a/src/System.Net.Http.Formatting/Formatting/ParsedMediaTypeHeaderValue.cs +++ b/src/System.Net.Http.Formatting/Formatting/ParsedMediaTypeHeaderValue.cs @@ -40,14 +40,14 @@ public ParsedMediaTypeHeaderValue(MediaTypeHeaderValue mediaTypeHeaderValue) } } - public bool IsAllMediaRange - { - get { return _isAllMediaRange; } + public bool IsAllMediaRange + { + get { return _isAllMediaRange; } } - public bool IsSubtypeMediaRange - { - get { return _isSubtypeMediaRange; } + public bool IsSubtypeMediaRange + { + get { return _isSubtypeMediaRange; } } public bool TypesEqual(ref ParsedMediaTypeHeaderValue other) diff --git a/src/System.Net.Http.Formatting/Formatting/Parsers/FormUrlEncodedParser.cs b/src/System.Net.Http.Formatting/Formatting/Parsers/FormUrlEncodedParser.cs index d7f248d16..90754c123 100644 --- a/src/System.Net.Http.Formatting/Formatting/Parsers/FormUrlEncodedParser.cs +++ b/src/System.Net.Http.Formatting/Formatting/Parsers/FormUrlEncodedParser.cs @@ -11,7 +11,7 @@ namespace System.Net.Http.Formatting.Parsers { /// - /// Buffer-oriented parsing of HTML form URL-ended, also known as application/x-www-form-urlencoded, data. + /// Buffer-oriented parsing of HTML form URL-ended, also known as application/x-www-form-urlencoded, data. /// internal class FormUrlEncodedParser { @@ -54,7 +54,7 @@ private enum NameValueState /// /// Parse a buffer of URL form-encoded name-value pairs and add them to the collection. - /// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be + /// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be /// present in the buffer. /// /// Buffer from where data is read @@ -243,7 +243,7 @@ private ParserState CopyCurrent(ParserState parseState) } /// - /// Maintains information about the current header field being parsed. + /// Maintains information about the current header field being parsed. /// private class CurrentNameValuePair { @@ -275,9 +275,9 @@ public StringBuilder Value /// The collection to copy into. public void CopyTo(ICollection> nameValuePairs) { - string unescapedName = UriQueryUtility.UrlDecode(_name.ToString()); + string unescapedName = WebUtility.UrlDecode(_name.ToString()); string escapedValue = _value.ToString(); - string value = UriQueryUtility.UrlDecode(escapedValue); + string value = WebUtility.UrlDecode(escapedValue); nameValuePairs.Add(new KeyValuePair(unescapedName, value)); @@ -290,7 +290,7 @@ public void CopyTo(ICollection> nameValuePairs) /// The collection to copy into. public void CopyNameOnlyTo(ICollection> nameValuePairs) { - string unescapedName = UriQueryUtility.UrlDecode(_name.ToString()); + string unescapedName = WebUtility.UrlDecode(_name.ToString()); string value = String.Empty; nameValuePairs.Add(new KeyValuePair(unescapedName, value)); Clear(); diff --git a/src/System.Net.Http.Formatting/Formatting/Parsers/HttpRequestLineParser.cs b/src/System.Net.Http.Formatting/Formatting/Parsers/HttpRequestLineParser.cs index 027270150..b89189f8a 100644 --- a/src/System.Net.Http.Formatting/Formatting/Parsers/HttpRequestLineParser.cs +++ b/src/System.Net.Http.Formatting/Formatting/Parsers/HttpRequestLineParser.cs @@ -56,8 +56,8 @@ private enum HttpRequestLineState } /// - /// Parse an HTTP request line. - /// Bytes are parsed in a consuming manner from the beginning of the request buffer meaning that the same bytes can not be + /// Parse an HTTP request line. + /// Bytes are parsed in a consuming manner from the beginning of the request buffer meaning that the same bytes can not be /// present in the request buffer. /// /// Request buffer from where request is read diff --git a/src/System.Net.Http.Formatting/Formatting/Parsers/HttpStatusLineParser.cs b/src/System.Net.Http.Formatting/Formatting/Parsers/HttpStatusLineParser.cs index e64677e94..86f00f77d 100644 --- a/src/System.Net.Http.Formatting/Formatting/Parsers/HttpStatusLineParser.cs +++ b/src/System.Net.Http.Formatting/Formatting/Parsers/HttpStatusLineParser.cs @@ -58,8 +58,8 @@ private enum HttpStatusLineState } /// - /// Parse an HTTP status line. - /// Bytes are parsed in a consuming manner from the beginning of the response buffer meaning that the same bytes can not be + /// Parse an HTTP status line. + /// Bytes are parsed in a consuming manner from the beginning of the response buffer meaning that the same bytes can not be /// present in the response buffer. /// /// Response buffer from where response is read diff --git a/src/System.Net.Http.Formatting/Formatting/Parsers/InternetMessageFormatHeaderParser.cs b/src/System.Net.Http.Formatting/Formatting/Parsers/InternetMessageFormatHeaderParser.cs index aebfa8c29..ebf22b9ba 100644 --- a/src/System.Net.Http.Formatting/Formatting/Parsers/InternetMessageFormatHeaderParser.cs +++ b/src/System.Net.Http.Formatting/Formatting/Parsers/InternetMessageFormatHeaderParser.cs @@ -10,8 +10,8 @@ namespace System.Net.Http.Formatting.Parsers { /// - /// Buffer-oriented RFC 5322 style Internet Message Format parser which can be used to pass header - /// fields used in HTTP and MIME message entities. + /// Buffer-oriented RFC 5322 style Internet Message Format parser which can be used to pass header + /// fields used in HTTP and MIME message entities. /// internal class InternetMessageFormatHeaderParser { @@ -76,7 +76,7 @@ private enum HeaderFieldState /// /// Parse a buffer of RFC 5322 style header fields and add them to the collection. - /// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be + /// Bytes are parsed in a consuming manner from the beginning of the buffer meaning that the same bytes can not be /// present in the buffer. /// /// Request buffer from where request is read @@ -283,7 +283,7 @@ private static ParserState ParseHeaderFields( } /// - /// Maintains information about the current header field being parsed. + /// Maintains information about the current header field being parsed. /// private class CurrentHeaderFieldStore { @@ -320,6 +320,10 @@ public void CopyTo(HttpHeaders headers, bool ignoreHeaderValidation) { var name = _name.ToString(); var value = _value.ToString().Trim(CurrentHeaderFieldStore._linearWhiteSpace); + if (string.Equals("expires", name, StringComparison.OrdinalIgnoreCase)) + { + ignoreHeaderValidation = true; + } if (ignoreHeaderValidation) { diff --git a/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartBodyPartParser.cs b/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartBodyPartParser.cs index 24981c209..4f135c6ed 100644 --- a/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartBodyPartParser.cs +++ b/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartBodyPartParser.cs @@ -11,7 +11,7 @@ namespace System.Net.Http.Formatting.Parsers { /// - /// Complete MIME multipart parser that combines for parsing the MIME message into individual body parts + /// Complete MIME multipart parser that combines for parsing the MIME message into individual body parts /// and for parsing each body part into a MIME header and a MIME body. The caller of the parser is returned /// the resulting MIME bodies which can then be written to some output. /// @@ -104,7 +104,7 @@ public void Dispose() } /// - /// Parses the data provided and generates parsed MIME body part bodies in the form of which are ready to + /// Parses the data provided and generates parsed MIME body part bodies in the form of which are ready to /// write to the output stream. /// /// The data to parse @@ -116,11 +116,11 @@ public IEnumerable ParseBuffer(byte[] data, int bytesRead) bool isFinal = false; // There's a special case here - if we've reached the end of the message and there's no optional - // CRLF, then we're out of bytes to read, but we have finished the message. + // CRLF, then we're out of bytes to read, but we have finished the message. // - // If IsWaitingForEndOfMessage is true and we're at the end of the stream, then we're going to - // call into the parser again with an empty array as the buffer to signal the end of the parse. - // Then the final boundary segment will be marked as complete. + // If IsWaitingForEndOfMessage is true and we're at the end of the stream, then we're going to + // call into the parser again with an empty array as the buffer to signal the end of the parse. + // Then the final boundary segment will be marked as complete. if (bytesRead == 0 && !_mimeParser.IsWaitingForEndOfMessage) { CleanupCurrentBodyPart(); @@ -195,7 +195,7 @@ public IEnumerable ParseBuffer(byte[] data, int bytesRead) } else { - // Otherwise return what we have + // Otherwise return what we have yield return _currentBodyPart; } } diff --git a/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartParser.cs b/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartParser.cs index 734124566..40b83e617 100644 --- a/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartParser.cs +++ b/src/System.Net.Http.Formatting/Formatting/Parsers/MimeMultipartParser.cs @@ -122,7 +122,7 @@ public enum State /// DataTooBig, } - + public bool CanParseMore(int bytesRead, int bytesConsumed) { if (bytesConsumed < bytesRead) @@ -147,7 +147,7 @@ public bool CanParseMore(int bytesRead, int bytesConsumed) /// /// Parse a MIME multipart message. Bytes are parsed in a consuming - /// manner from the beginning of the request buffer meaning that the same bytes can not be + /// manner from the beginning of the request buffer meaning that the same bytes can not be /// present in the request buffer. /// /// Request buffer from where request is read @@ -156,7 +156,7 @@ public bool CanParseMore(int bytesRead, int bytesConsumed) /// Any body part that was considered as a potential MIME multipart boundary but which was in fact part of the body. /// The bulk of the body part. /// Indicates whether the final body part has been found. - /// In order to get the complete body part, the caller is responsible for concatenating the contents of the + /// In order to get the complete body part, the caller is responsible for concatenating the contents of the /// and out parameters. /// State of the parser. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception is translated to parse state.")] @@ -375,7 +375,7 @@ private static State ParseBodyPart( goto quit; } } - + if (bytesConsumed > segmentStart) { if (!currentBodyPart.AppendBoundary(buffer, segmentStart, bytesConsumed - segmentStart)) @@ -391,7 +391,7 @@ private static State ParseBodyPart( case BodyPartState.AfterBoundary: // This state means that we just saw the end of a boundary. It might by a 'normal' boundary, in which - // case it's followed by optional whitespace and a CRLF. Or it might be the 'final' boundary and will + // case it's followed by optional whitespace and a CRLF. Or it might be the 'final' boundary and will // be followed by '--', optional whitespace and an optional CRLF. if (buffer[bytesConsumed] == MimeMultipartParser.Dash && !currentBodyPart.IsFinal) { @@ -456,13 +456,13 @@ private static State ParseBodyPart( { currentBodyPart.AppendBoundary(MimeMultipartParser.Dash); bytesConsumed++; - + if (currentBodyPart.IsBoundaryComplete()) { Debug.Assert(currentBodyPart.IsFinal); - // If we get in here, it means we've see the trailing '--' of the last boundary - in order to consume all of the - // remaining bytes, we don't mark the parse as complete again - wait until this method is called again with the + // If we get in here, it means we've see the trailing '--' of the last boundary - in order to consume all of the + // remaining bytes, we don't mark the parse as complete again - wait until this method is called again with the // empty buffer to do that. bodyPartState = BodyPartState.AfterBoundary; parseStatus = State.NeedMoreData; @@ -658,9 +658,9 @@ public void AppendBoundary(byte data) /// The number of bytes to append. public bool AppendBoundary(byte[] data, int offset, int count) { - // Check that potential boundary is not bigger than our reference boundary. - // Allow for 2 extra characters to include the final boundary which ends with - // an additional "--" sequence + plus up to 4 LWS characters (which are allowed). + // Check that potential boundary is not bigger than our reference boundary. + // Allow for 2 extra characters to include the final boundary which ends with + // an additional "--" sequence + plus up to 4 LWS characters (which are allowed). if (_boundaryLength + count > _referenceBoundaryLength + 6) { return false; @@ -753,7 +753,7 @@ public bool IsBoundaryComplete() { return false; } - + if (_boundaryLength < _referenceBoundaryLength) { return false; @@ -797,9 +797,9 @@ private string DebuggerToString() var boundary = Encoding.UTF8.GetString(_boundary, 0, _boundaryLength); return String.Format( - CultureInfo.InvariantCulture, - "Expected: {0} *** Current: {1}", - referenceBoundary, + CultureInfo.InvariantCulture, + "Expected: {0} *** Current: {1}", + referenceBoundary, boundary); } } diff --git a/src/System.Net.Http.Formatting/Formatting/RequestHeaderMapping.cs b/src/System.Net.Http.Formatting/Formatting/RequestHeaderMapping.cs index 3deee8ca3..845d8903d 100644 --- a/src/System.Net.Http.Formatting/Formatting/RequestHeaderMapping.cs +++ b/src/System.Net.Http.Formatting/Formatting/RequestHeaderMapping.cs @@ -23,9 +23,9 @@ public class RequestHeaderMapping : MediaTypeMapping /// Name of the header to match. /// The header value to match. /// The value comparison to use when matching . - /// if set to true then is + /// if set to true then is /// considered a match if it matches a substring of the actual header value. - /// The media type to use if and + /// The media type to use if and /// is considered a match. public RequestHeaderMapping(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring, string mediaType) : base(mediaType) @@ -39,9 +39,9 @@ public RequestHeaderMapping(string headerName, string headerValue, StringCompari /// Name of the header to match. /// The header value to match. /// The to use when matching . - /// if set to true then is + /// if set to true then is /// considered a match if it matches a substring of the actual header value. - /// The to use if and + /// The to use if and /// is considered a match. public RequestHeaderMapping(string headerName, string headerValue, StringComparison valueComparison, bool isValueSubstring, MediaTypeHeaderValue mediaType) : base(mediaType) @@ -65,7 +65,7 @@ public RequestHeaderMapping(string headerName, string headerValue, StringCompari public StringComparison HeaderValueComparison { get; private set; } /// - /// Gets a value indicating whether is + /// Gets a value indicating whether is /// a matched as a substring of the actual header value. /// this instance is value substring. /// diff --git a/src/System.Net.Http.Formatting/Formatting/StringComparisonHelper.cs b/src/System.Net.Http.Formatting/Formatting/StringComparisonHelper.cs index 8dade6d2d..8f45ee70c 100644 --- a/src/System.Net.Http.Formatting/Formatting/StringComparisonHelper.cs +++ b/src/System.Net.Http.Formatting/Formatting/StringComparisonHelper.cs @@ -23,7 +23,7 @@ public static bool IsDefined(StringComparison value) { return value == StringComparison.CurrentCulture || value == StringComparison.CurrentCultureIgnoreCase || -#if !NETFX_CORE +#if !NETSTANDARD1_3 value == StringComparison.InvariantCulture || value == StringComparison.InvariantCultureIgnoreCase || #endif diff --git a/src/System.Net.Http.Formatting/Formatting/StringWithQualityHeaderValueComparer.cs b/src/System.Net.Http.Formatting/Formatting/StringWithQualityHeaderValueComparer.cs index c10caf277..6ded7c717 100644 --- a/src/System.Net.Http.Formatting/Formatting/StringWithQualityHeaderValueComparer.cs +++ b/src/System.Net.Http.Formatting/Formatting/StringWithQualityHeaderValueComparer.cs @@ -9,9 +9,9 @@ namespace System.Net.Http.Formatting { /// /// Implementation of that can compare content negotiation header fields - /// based on their quality values (a.k.a q-values). This applies to values used in accept-charset, - /// accept-encoding, accept-language and related header fields with similar syntax rules. See - /// for a comparer for media type + /// based on their quality values (a.k.a q-values). This applies to values used in accept-charset, + /// accept-encoding, accept-language and related header fields with similar syntax rules. See + /// for a comparer for media type /// q-values. /// internal class StringWithQualityHeaderValueComparer : IComparer diff --git a/src/System.Net.Http.Formatting/Formatting/XmlMediaTypeFormatter.cs b/src/System.Net.Http.Formatting/Formatting/XmlMediaTypeFormatter.cs index bec831de8..76ee18f3d 100644 --- a/src/System.Net.Http.Formatting/Formatting/XmlMediaTypeFormatter.cs +++ b/src/System.Net.Http.Formatting/Formatting/XmlMediaTypeFormatter.cs @@ -1,9 +1,7 @@ // 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 !NETFX_CORE // In portable library we have our own implementation of Concurrent Dictionary which is in the internal namespace using System.Collections.Concurrent; -#endif using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; @@ -57,9 +55,7 @@ protected XmlMediaTypeFormatter(XmlMediaTypeFormatter formatter) { UseXmlSerializer = formatter.UseXmlSerializer; WriterSettings = formatter.WriterSettings; -#if !NETFX_CORE // MaxDepth is not supported in portable libraries MaxDepth = formatter.MaxDepth; -#endif } /// @@ -67,8 +63,8 @@ protected XmlMediaTypeFormatter(XmlMediaTypeFormatter formatter) /// /// /// - /// The default media type does not have any charset parameter as - /// the can be configured on a per + /// The default media type does not have any charset parameter as + /// the can be configured on a per /// instance basis. /// /// Because is mutable, the value @@ -89,7 +85,7 @@ public static MediaTypeHeaderValue DefaultMediaType public bool UseXmlSerializer { get; set; } /// - /// Gets or sets a value indicating whether to indent elements when writing data. + /// Gets or sets a value indicating whether to indent elements when writing data. /// public bool Indent { @@ -108,7 +104,6 @@ public bool Indent /// public XmlWriterSettings WriterSettings { get; private set; } -#if !NETFX_CORE // MaxDepth is not supported in portable libraries /// /// Gets or sets the maximum depth allowed by this formatter. /// @@ -128,7 +123,6 @@ public int MaxDepth _readerQuotas.MaxDepth = value; } } -#endif /// /// Registers the to use to read or write @@ -343,12 +337,14 @@ protected internal virtual XmlReader CreateXmlReader(Stream readStream, HttpCont { // Get the character encoding for the content Encoding effectiveEncoding = SelectCharacterEncoding(content == null ? null : content.Headers); -#if NETFX_CORE - // Force a preamble into the stream, since CreateTextReader in WinRT only supports auto-detecting encoding. - return XmlDictionaryReader.CreateTextReader(new ReadOnlyStreamWithEncodingPreamble(readStream, effectiveEncoding), _readerQuotas); -#else - return XmlDictionaryReader.CreateTextReader(new NonClosingDelegatingStream(readStream), effectiveEncoding, _readerQuotas, null); -#endif + + // DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. Convert to UTF8 as we read. + Stream innerStream = string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase) ? + new NonClosingDelegatingStream(readStream) : + new TranscodingStream(readStream, effectiveEncoding, Utf8Encoding, leaveOpen: true); + + // XmlDictionaryReader will always dispose of innerStream when caller disposes of the reader. + return XmlDictionaryReader.CreateTextReader(innerStream, Utf8Encoding, _readerQuotas, onClose: null); } /// @@ -439,9 +435,20 @@ protected internal virtual object GetSerializer(Type type, object value, HttpCon protected internal virtual XmlWriter CreateXmlWriter(Stream writeStream, HttpContent content) { Encoding effectiveEncoding = SelectCharacterEncoding(content != null ? content.Headers : null); + WritePreamble(writeStream, effectiveEncoding); + + // DCS encodings are limited to UTF8, UTF16BE, and UTF16LE. Convert to UTF8 as we read. + Stream innerStream = string.Equals(effectiveEncoding.WebName, Utf8Encoding.WebName, StringComparison.OrdinalIgnoreCase) ? + writeStream : + new TranscodingStream(writeStream, effectiveEncoding, Utf8Encoding, leaveOpen: true); + XmlWriterSettings writerSettings = WriterSettings.Clone(); - writerSettings.Encoding = effectiveEncoding; - return XmlWriter.Create(writeStream, writerSettings); + writerSettings.Encoding = Utf8Encoding; + + // Have XmlWriter dispose of innerStream when caller disposes of the writer if using a TranscodingStream. + writerSettings.CloseOutput = writeStream != innerStream; + + return XmlWriter.Create(innerStream, writerSettings); } /// @@ -504,6 +511,23 @@ public object InvokeGetSerializer(Type type, object value, HttpContent content) private object CreateDefaultSerializer(Type type, bool throwOnError) { Contract.Assert(type != null, "type cannot be null."); + +#if NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3 + if (!UseXmlSerializer) + { + if (throwOnError) + { + throw new PlatformNotSupportedException(Error.Format( + Properties.Resources.XmlMediaTypeFormatter_DCS_NotSupported, + nameof(UseXmlSerializer))); + } + else + { + return null; + } + } +#endif + Exception exception = null; object serializer = null; @@ -515,12 +539,12 @@ private object CreateDefaultSerializer(Type type, bool throwOnError) } else { -#if !NETFX_CORE - // REVIEW: Is there something comparable in WinRT? +#if !NETSTANDARD1_3 // Unreachable when targeting netstandard1.3. // Verify that type is a valid data contract by forcing the serializer to try to create a data contract FormattingUtilities.XsdDataContractExporter.GetRootElementName(type); -#endif + serializer = CreateDataContractSerializer(type); +#endif } } catch (Exception caught) diff --git a/src/System.Net.Http.Formatting/FormattingUtilities.cs b/src/System.Net.Http.Formatting/FormattingUtilities.cs index 220ce1d89..2d296a18c 100644 --- a/src/System.Net.Http.Formatting/FormattingUtilities.cs +++ b/src/System.Net.Http.Formatting/FormattingUtilities.cs @@ -18,7 +18,7 @@ namespace System.Net.Http internal static class FormattingUtilities { // Supported date formats for input. - private static readonly string[] dateFormats = new string[] + private static readonly string[] dateFormats = new string[] { // "r", // RFC 1123, required output format but too strict for input "ddd, d MMM yyyy H:m:s 'GMT'", // RFC 1123 (r, except it allows both 1 and 01 for date and time) @@ -114,7 +114,7 @@ internal static class FormattingUtilities /// public static readonly Type QueryableInterfaceGenericType = typeof(IQueryable<>); -#if !NETFX_CORE // XsdDataContractExporter is not supported in portable libraries +#if !NETSTANDARD1_3 // XsdDataContractExporter is not supported in netstandard1.3 /// /// An instance of . /// @@ -134,7 +134,7 @@ public static bool IsJTokenType(Type type) } /// - /// Creates an empty instance. The only way is to get it from a dummy + /// Creates an empty instance. The only way is to get it from a dummy /// instance. /// /// The created instance. @@ -166,9 +166,6 @@ public static HttpContentHeaders CreateEmptyContentHeaders() /// public static XmlDictionaryReaderQuotas CreateDefaultReaderQuotas() { -#if NETFX_CORE // MaxDepth is a DOS mitigation. We don't support MaxDepth in portable libraries because it is strictly client side. - return XmlDictionaryReaderQuotas.Max; -#else return new XmlDictionaryReaderQuotas() { MaxArrayLength = Int32.MaxValue, @@ -177,7 +174,6 @@ public static XmlDictionaryReaderQuotas CreateDefaultReaderQuotas() MaxNameTableCharCount = Int32.MaxValue, MaxStringContentLength = Int32.MaxValue }; -#endif } /// diff --git a/src/System.Net.Http.Formatting/GlobalSuppressions.cs b/src/System.Net.Http.Formatting/GlobalSuppressions.cs index deefc5652..d815e56e6 100644 --- a/src/System.Net.Http.Formatting/GlobalSuppressions.cs +++ b/src/System.Net.Http.Formatting/GlobalSuppressions.cs @@ -6,3 +6,5 @@ [assembly: SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames")] [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Net.Http.Headers", Justification = "We follow the layout of System.Net.Http.")] [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Net.Http.Handlers", Justification = "Handlers provide an extensibility hook which we want to keep in a separate namespace.")] +// Some resources are specific to the netstandard1.3 assembly +[assembly: SuppressMessage("Microsoft.Web.FxCop", "MW1000:UnusedResourceUsageRule", Justification = "There are a few unused resources due to missing netstandard1.3 features.")] diff --git a/src/System.Net.Http.Formatting/Handlers/ProgressStream.cs b/src/System.Net.Http.Formatting/Handlers/ProgressStream.cs index fe545f9a2..eff766608 100644 --- a/src/System.Net.Http.Formatting/Handlers/ProgressStream.cs +++ b/src/System.Net.Http.Formatting/Handlers/ProgressStream.cs @@ -10,7 +10,7 @@ namespace System.Net.Http.Handlers { /// - /// This implementation of registers how much data has been + /// This implementation of registers how much data has been /// read (received) versus written (sent) for a particular HTTP operation. The implementation /// is client side in that the total bytes to send is taken from the request and the total /// bytes to read is taken from the response. In a server side scenario, it would be the @@ -67,7 +67,8 @@ public override async Task ReadAsync(byte[] buffer, int offset, int count, ReportBytesReceived(readCount, userState: null); return readCount; } -#if !NETFX_CORE // BeginX and EndX are not supported on streams in portable libraries + +#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return InnerStream.BeginRead(buffer, offset, count, callback, state); @@ -99,7 +100,7 @@ public override async Task WriteAsync(byte[] buffer, int offset, int count, Canc ReportBytesSent(count, userState: null); } -#if !NETFX_CORE // BeginX and EndX are not supported on streams in portable libraries +#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return new ProgressWriteAsyncResult(InnerStream, this, buffer, offset, count, callback, state); diff --git a/src/System.Net.Http.Formatting/HttpContentFormDataExtensions.cs b/src/System.Net.Http.Formatting/HttpContentFormDataExtensions.cs index 19f5b9bc3..72ebb40c7 100644 --- a/src/System.Net.Http.Formatting/HttpContentFormDataExtensions.cs +++ b/src/System.Net.Http.Formatting/HttpContentFormDataExtensions.cs @@ -8,14 +8,11 @@ using System.Threading; using System.Threading.Tasks; using System.Web.Http; -#if NETFX_CORE -using NameValueCollection = System.Net.Http.Formatting.HttpValueCollection; -#endif namespace System.Net.Http { /// - /// Extension methods to allow HTML form URL-encoded data, also known as application/x-www-form-urlencoded, + /// Extension methods to allow HTML form URL-encoded data, also known as application/x-www-form-urlencoded, /// to be read from instances. /// [EditorBrowsable(EditorBrowsableState.Never)] diff --git a/src/System.Net.Http.Formatting/HttpContentMessageExtensions.cs b/src/System.Net.Http.Formatting/HttpContentMessageExtensions.cs index dd801b604..fdc518c54 100644 --- a/src/System.Net.Http.Formatting/HttpContentMessageExtensions.cs +++ b/src/System.Net.Http.Formatting/HttpContentMessageExtensions.cs @@ -126,7 +126,7 @@ public static Task ReadAsHttpRequestMessageAsync(this HttpCo /// Read the as an . /// /// The content to read. - /// The URI scheme to use for the request URI (the + /// The URI scheme to use for the request URI (the /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally). /// Size of the buffer. /// A task object representing reading the content as an . @@ -140,7 +140,7 @@ public static Task ReadAsHttpRequestMessageAsync(this HttpCo /// Read the as an . /// /// The content to read. - /// The URI scheme to use for the request URI (the + /// The URI scheme to use for the request URI (the /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally). /// Size of the buffer. /// The token to monitor for cancellation requests. @@ -157,7 +157,7 @@ public static Task ReadAsHttpRequestMessageAsync(this HttpCo /// Read the as an . /// /// The content to read. - /// The URI scheme to use for the request URI (the + /// The URI scheme to use for the request URI (the /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally). /// Size of the buffer. /// The max length of the HTTP header. @@ -174,7 +174,7 @@ public static Task ReadAsHttpRequestMessageAsync(this HttpCo /// Read the as an . /// /// The content to read. - /// The URI scheme to use for the request URI (the + /// The URI scheme to use for the request URI (the /// URI scheme is not actually part of the HTTP Request URI and so must be provided externally). /// Size of the buffer. /// The max length of the HTTP header. @@ -223,7 +223,7 @@ private static async Task ReadAsHttpRequestMessageAsyncCore( HttpUnsortedRequest httpRequest = new HttpUnsortedRequest(); HttpRequestHeaderParser parser = new HttpRequestHeaderParser(httpRequest, - HttpRequestHeaderParser.DefaultMaxRequestLineSize, maxHeaderSize); + Math.Max(HttpRequestHeaderParser.DefaultMaxRequestLineSize, maxHeaderSize), maxHeaderSize); ParserState parseStatus; byte[] buffer = new byte[bufferSize]; @@ -451,7 +451,7 @@ private static HttpContent CreateHeaderFields(HttpHeaders source, HttpHeaders de Contract.Assert(destination != null, "destination headers cannot be null"); Contract.Assert(contentStream != null, "contentStream must be non null"); HttpContentHeaders contentHeaders = null; - HttpContent content = null; + HttpContent content; // Set the header fields foreach (KeyValuePair> header in source) @@ -467,7 +467,8 @@ private static HttpContent CreateHeaderFields(HttpHeaders source, HttpHeaders de } } - // If we have content headers then create an HttpContent for this Response + // If we have content headers then create an HttpContent for this request or response. Otherwise, + // provide a HttpContent instance to overwrite the null or EmptyContent value. if (contentHeaders != null) { // Need to rewind the input stream to be at the position right after the HTTP header @@ -481,6 +482,10 @@ private static HttpContent CreateHeaderFields(HttpHeaders source, HttpHeaders de content = new StreamContent(contentStream); contentHeaders.CopyTo(content.Headers); } + else + { + content = new StreamContent(Stream.Null); + } return content; } diff --git a/src/System.Net.Http.Formatting/HttpContentMultipartExtensions.cs b/src/System.Net.Http.Formatting/HttpContentMultipartExtensions.cs index dce8ce8fa..e9671d5b2 100644 --- a/src/System.Net.Http.Formatting/HttpContentMultipartExtensions.cs +++ b/src/System.Net.Http.Formatting/HttpContentMultipartExtensions.cs @@ -41,9 +41,9 @@ public static bool IsMimeMultipartContent(this HttpContent content) } /// - /// Determines whether the specified content is MIME multipart content with the + /// Determines whether the specified content is MIME multipart content with the /// specified subtype. For example, the subtype mixed would match content - /// with a content type of multipart/mixed. + /// with a content type of multipart/mixed. /// /// The content. /// The MIME multipart subtype to match. @@ -91,7 +91,7 @@ public static Task ReadAsMultipartAsync(this Http /// /// Reads all body parts within a MIME multipart message using the provided instance - /// to determine where the contents of each body part is written. + /// to determine where the contents of each body part is written. /// /// The with which to process the data. /// An existing instance to use for the object's content. @@ -104,7 +104,7 @@ public static Task ReadAsMultipartAsync(this HttpContent content, T stream /// /// Reads all body parts within a MIME multipart message using the provided instance - /// to determine where the contents of each body part is written. + /// to determine where the contents of each body part is written. /// /// The with which to process the data. /// An existing instance to use for the object's content. diff --git a/src/System.Net.Http.Formatting/HttpMessageContent.cs b/src/System.Net.Http.Formatting/HttpMessageContent.cs index 1d90b16d8..c182d40c8 100644 --- a/src/System.Net.Http.Formatting/HttpMessageContent.cs +++ b/src/System.Net.Http.Formatting/HttpMessageContent.cs @@ -205,6 +205,7 @@ protected override async Task SerializeToStreamAsync(Stream stream, TransportCon protected override bool TryComputeLength(out long length) { // We have four states we could be in: + // 0. We have content and it knows its ContentLength. // 1. We have content, but the task is still running or finished without success // 2. We have content, the task has finished successfully, and the stream came back as a null or non-seekable // 3. We have content, the task has finished successfully, and the stream is seekable, so we know its length @@ -214,11 +215,13 @@ protected override bool TryComputeLength(out long length) // For #3, we return true & the size of our headers + the content length // For #4, we return true & the size of our headers - bool hasContent = _streamTask.Value != null; length = 0; - // Cases #1, #2, #3 - if (hasContent) + if (Content?.Headers.ContentLength is not null) + { + length = (long)Content.Headers.ContentLength; // Case #0 + } + else if (_streamTask.Value is not null) { Stream readStream; if (!_streamTask.Value.TryGetResult(out readStream) // Case #1 @@ -356,12 +359,21 @@ private byte[] SerializeHeader() private void ValidateStreamForReading(Stream stream) { + // Stream is null case should be an extreme, incredibly unlikely corner case. Every HttpContent from + // the framework (see dotnet/runtime or .NET Framework reference source) provides a non-null Stream + // in the ReadAsStreamAsync task's return value. Likely need a poorly-designed derived HttpContent + // to hit this. Mostly ignoring the fact this message doesn't make much sense for the case. + if (stream is null || !stream.CanRead) + { + throw Error.NotSupported(Properties.Resources.NotSupported_UnreadableStream); + } + // If the content needs to be written to a target stream a 2nd time, then the stream must support - // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target + // seeking (e.g. a FileStream), otherwise the stream can't be copied a second time to a target // stream (e.g. a NetworkStream). if (_contentConsumed) { - if (stream != null && stream.CanRead) + if (stream.CanSeek) { stream.Position = 0; } diff --git a/src/System.Net.Http.Formatting/HttpRequestMessageExtensions.cs b/src/System.Net.Http.Formatting/HttpRequestMessageExtensions.cs index a503f148b..b2e568eaa 100644 --- a/src/System.Net.Http.Formatting/HttpRequestMessageExtensions.cs +++ b/src/System.Net.Http.Formatting/HttpRequestMessageExtensions.cs @@ -3,6 +3,7 @@ using System.ComponentModel; using System.Diagnostics.CodeAnalysis; +using System.IO; using System.Web.Http; namespace System.Net.Http @@ -29,6 +30,7 @@ public static HttpResponseMessage CreateResponse(this HttpRequestMessage request return new HttpResponseMessage { + Content = new StreamContent(Stream.Null), StatusCode = statusCode, RequestMessage = request }; @@ -49,6 +51,7 @@ public static HttpResponseMessage CreateResponse(this HttpRequestMessage request return new HttpResponseMessage { + Content = new StreamContent(Stream.Null), RequestMessage = request }; } diff --git a/src/System.Net.Http.Formatting/Internal/ByteRangeStream.cs b/src/System.Net.Http.Formatting/Internal/ByteRangeStream.cs index 33325d4f4..a4fce9a3f 100644 --- a/src/System.Net.Http.Formatting/Internal/ByteRangeStream.cs +++ b/src/System.Net.Http.Formatting/Internal/ByteRangeStream.cs @@ -111,10 +111,12 @@ public override long Position } } +#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return base.BeginRead(buffer, offset, PrepareStreamForRangeRead(count), callback, state); } +#endif public override int Read(byte[] buffer, int offset, int count) { @@ -172,6 +174,7 @@ public override void Write(byte[] buffer, int offset, int count) throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly); } +#if !NETSTANDARD1_3 // BeginX and EndX are not supported on Streams in netstandard1.3 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly); @@ -181,6 +184,7 @@ public override void EndWrite(IAsyncResult asyncResult) { throw Error.NotSupported(Properties.Resources.ByteRangeStreamReadOnly); } +#endif public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { diff --git a/src/System.Net.Http.Formatting/Internal/DelegatingStream.cs b/src/System.Net.Http.Formatting/Internal/DelegatingStream.cs index ee0c51bde..0e713fdfd 100644 --- a/src/System.Net.Http.Formatting/Internal/DelegatingStream.cs +++ b/src/System.Net.Http.Formatting/Internal/DelegatingStream.cs @@ -97,7 +97,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !NETSTANDARD1_3 // BeginX and EndX not supported on Streams in netstandard1.3 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return _innerStream.BeginRead(buffer, offset, count, callback, state); @@ -139,7 +139,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati return _innerStream.WriteAsync(buffer, offset, count, cancellationToken); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !NETSTANDARD1_3 // BeginX and EndX not supported on Streams in netstandard1.3 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return _innerStream.BeginWrite(buffer, offset, count, callback, state); diff --git a/src/System.Net.Http.Formatting/Internal/HttpValueCollection.cs b/src/System.Net.Http.Formatting/Internal/HttpValueCollection.cs index 1af77650e..082b33319 100644 --- a/src/System.Net.Http.Formatting/Internal/HttpValueCollection.cs +++ b/src/System.Net.Http.Formatting/Internal/HttpValueCollection.cs @@ -1,14 +1,6 @@ // 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 NETFX_CORE -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Text; -using System.Web.Http; -#else using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.Contracts; @@ -17,45 +9,29 @@ using System.Runtime.Serialization; using System.Text; using System.Web.Http; -#endif -#if NETFX_CORE -namespace System.Net.Http.Formatting -#else namespace System.Net.Http.Formatting.Internal -#endif { /// /// NameValueCollection to represent form data and to generate form data output. /// -#if NETFX_CORE - public class HttpValueCollection : IEnumerable> -#else +#if !NETSTANDARD1_3 // NameValueCollection is not serializable in netstandard1.3. [Serializable] - internal class HttpValueCollection : NameValueCollection #endif + internal class HttpValueCollection : NameValueCollection { -#if NETFX_CORE - internal readonly HashSet Names = new HashSet(StringComparer.OrdinalIgnoreCase); - internal readonly List> List = new List>(); - - /// - /// Creates a new instance - /// - public HttpValueCollection() - { - } -#else +#if !NETSTANDARD1_3 // NameValueCollection is not serializable in netstandard1.3. protected HttpValueCollection(SerializationInfo info, StreamingContext context) : base(info, context) { } +#endif private HttpValueCollection() : base(StringComparer.OrdinalIgnoreCase) // case-insensitive keys { } -#endif + // Use a builder function instead of a ctor to avoid virtual calls from the ctor. // The above condition is only important in the Full .NET fx implementation. internal static HttpValueCollection Create() @@ -75,9 +51,8 @@ internal static HttpValueCollection Create(IEnumerable /// The name to be added as a case insensitive string. /// The value to be added. - public -#if !NETFX_CORE - override -#endif - void Add(string name, string value) + public override void Add(string name, string value) { ThrowIfMaxHttpCollectionKeysExceeded(Count); name = name ?? String.Empty; value = value ?? String.Empty; -#if NETFX_CORE - Names.Add(name); - List.Add(new KeyValuePair(name, value)); -#else base.Add(name, value); -#endif } /// @@ -131,11 +97,7 @@ private string ToString(bool urlEncode) StringBuilder builder = new StringBuilder(); bool first = true; -#if NETFX_CORE - foreach (string name in Names) -#else foreach (string name in this) -#endif { string[] values = GetValues(name); if (values == null || values.Length == 0) @@ -157,10 +119,10 @@ private string ToString(bool urlEncode) private static bool AppendNameValuePair(StringBuilder builder, bool first, bool urlEncode, string name, string value) { string effectiveName = name ?? String.Empty; - string encodedName = urlEncode ? UriQueryUtility.UrlEncode(effectiveName) : effectiveName; + string encodedName = urlEncode ? WebUtility.UrlEncode(effectiveName) : effectiveName; string effectiveValue = value ?? String.Empty; - string encodedValue = urlEncode ? UriQueryUtility.UrlEncode(effectiveValue) : effectiveValue; + string encodedValue = urlEncode ? WebUtility.UrlEncode(effectiveValue) : effectiveValue; if (first) { @@ -179,104 +141,5 @@ private static bool AppendNameValuePair(StringBuilder builder, bool first, bool } return first; } - -#if NETFX_CORE - /// - /// Gets the values associated with the specified name - /// combined into one comma-separated list. - /// - /// The name of the entry that contains the values to get. The name can be null. - /// A that contains a comma-separated list of url encoded values associated - /// with the specified name if found; otherwise, null. The values are Url encoded. - public string this[string name] - { - get - { - return Get(name); - } - } - - /// - /// Gets the number of names in the collection. - /// - public int Count - { - get - { - return Names.Count; - } - } - - /// - /// Gets the values associated with the specified name - /// combined into one comma-separated list. - /// - /// The name of the entry that contains the values to get. The name can be null. - /// - /// A that contains a comma-separated list of url encoded values associated - /// with the specified name if found; otherwise, null. The values are Url encoded. - /// - public string Get(string name) - { - name = name ?? String.Empty; - - if (!Names.Contains(name)) - { - return null; - } - - List values = GetValuesInternal(name); - Contract.Assert(values != null && values.Count > 0); - - return String.Join(",", values); - } - - /// - /// Gets the values associated with the specified name. - /// - /// The - /// A that contains url encoded values associated with the name, or null if the name does not exist. - public string[] GetValues(string name) - { - name = name ?? String.Empty; - - if (!Names.Contains(name)) - { - return null; - } - - return GetValuesInternal(name).ToArray(); - } - - // call this when only when there are values available. - private List GetValuesInternal(string name) - { - List values = new List(); - - for (int i = 0; i < List.Count; i++) - { - KeyValuePair kvp = List[i]; - - if (String.Equals(kvp.Key, name, StringComparison.OrdinalIgnoreCase)) - { - values.Add(kvp.Value); - } - } - - return values; - } - - /// - public IEnumerator> GetEnumerator() - { - return List.GetEnumerator(); - } - - /// - IEnumerator IEnumerable.GetEnumerator() - { - return List.GetEnumerator(); - } -#endif } } diff --git a/src/System.Net.Http.Formatting/Internal/NonClosingDelegatingStream.cs b/src/System.Net.Http.Formatting/Internal/NonClosingDelegatingStream.cs index 5af2385b0..1d7599654 100644 --- a/src/System.Net.Http.Formatting/Internal/NonClosingDelegatingStream.cs +++ b/src/System.Net.Http.Formatting/Internal/NonClosingDelegatingStream.cs @@ -8,8 +8,8 @@ namespace System.Net.Http.Internal /// /// Stream that doesn't close the inner stream when closed. This is to work around a limitation /// in the insisting of closing the inner stream. - /// The regular does allow for not closing the inner stream but that - /// doesn't have the quota that we need for security reasons. Implementations of + /// The regular does allow for not closing the inner stream but that + /// doesn't have the quota that we need for security reasons. Implementations of /// /// should not close the input stream when reading or writing so hence this workaround. /// @@ -20,8 +20,14 @@ public NonClosingDelegatingStream(Stream innerStream) { } +#if NETSTANDARD1_3 + protected override void Dispose(bool disposing) + { + } +#else public override void Close() { } +#endif } } diff --git a/src/System.Net.Http.Formatting/Internal/NullableAttributes.cs b/src/System.Net.Http.Formatting/Internal/NullableAttributes.cs new file mode 100644 index 000000000..2344a2994 --- /dev/null +++ b/src/System.Net.Http.Formatting/Internal/NullableAttributes.cs @@ -0,0 +1,198 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/tools/illink/src/ILLink.RoslynAnalyzer/NullableAttributes.cs + +namespace System.Diagnostics.CodeAnalysis +{ +#if !NETSTANDARD2_1 + /// Specifies that null is allowed as an input even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class AllowNullAttribute : Attribute { } + + /// Specifies that null is disallowed as an input even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class DisallowNullAttribute : Attribute { } + + /// Specifies that an output may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MaybeNullAttribute : Attribute { } + + /// Specifies that an output will not be null even if the corresponding type allows it. Specifies that an input argument was not null when the call returns. + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class NotNullAttribute : Attribute { } + + /// Specifies that when a method returns , the parameter may be null even if the corresponding type disallows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MaybeNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter may be null. + /// + public MaybeNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that when a method returns , the parameter will not be null even if the corresponding type allows it. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class NotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue; + + /// Gets the return value condition. + public bool ReturnValue { get; } + } + + /// Specifies that the output will be non-null if the named parameter is non-null. + [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class NotNullIfNotNullAttribute : Attribute + { + /// Initializes the attribute with the associated parameter name. + /// + /// The associated parameter name. The output will be non-null if the argument to the parameter specified is non-null. + /// + public NotNullIfNotNullAttribute(string parameterName) => ParameterName = parameterName; + + /// Gets the associated parameter name. + public string ParameterName { get; } + } + + /// Applied to a method that will never return under any circumstance. + [AttributeUsage(AttributeTargets.Method, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class DoesNotReturnAttribute : Attribute { } + + /// Specifies that the method will not return if the associated Boolean parameter is passed the specified value. + [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class DoesNotReturnIfAttribute : Attribute + { + /// Initializes the attribute with the specified parameter value. + /// + /// The condition parameter value. Code after the method will be considered unreachable by diagnostics if the argument to + /// the associated parameter matches this value. + /// + public DoesNotReturnIfAttribute(bool parameterValue) => ParameterValue = parameterValue; + + /// Gets the condition parameter value. + public bool ParameterValue { get; } + } +#endif + + /// Specifies that the method or property will ensure that the listed field and property members have not-null values. + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MemberNotNullAttribute : Attribute + { + /// Initializes the attribute with a field or property member. + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullAttribute(string member) => Members = new[] { member }; + + /// Initializes the attribute with the list of field and property members. + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullAttribute(params string[] members) => Members = members; + + /// Gets field or property member names. + public string[] Members { get; } + } + + /// Specifies that the method or property will ensure that the listed field and property members have not-null values when returning with the specified return value condition. + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] +#if SYSTEM_PRIVATE_CORELIB + public +#else + internal +#endif + sealed class MemberNotNullWhenAttribute : Attribute + { + /// Initializes the attribute with the specified return value condition and a field or property member. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + /// + /// The field or property member that is promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, string member) + { + ReturnValue = returnValue; + Members = new[] { member }; + } + + /// Initializes the attribute with the specified return value condition and list of field and property members. + /// + /// The return value condition. If the method returns this value, the associated parameter will not be null. + /// + /// + /// The list of field and property members that are promised to be not-null. + /// + public MemberNotNullWhenAttribute(bool returnValue, params string[] members) + { + ReturnValue = returnValue; + Members = members; + } + + /// Gets the return value condition. + public bool ReturnValue { get; } + + /// Gets field or property member names. + public string[] Members { get; } + } +} diff --git a/src/System.Net.Http.Formatting/Internal/ReadOnlyStreamWithEncodingPreamble.cs b/src/System.Net.Http.Formatting/Internal/ReadOnlyStreamWithEncodingPreamble.cs deleted file mode 100644 index 923e4bd37..000000000 --- a/src/System.Net.Http.Formatting/Internal/ReadOnlyStreamWithEncodingPreamble.cs +++ /dev/null @@ -1,175 +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.Contracts; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace System.Net.Http.Internal -{ - /// - /// This implements a read-only, forward-only stream around another readable stream, to ensure - /// that there is an appropriate encoding preamble in the stream. - /// - internal class ReadOnlyStreamWithEncodingPreamble : Stream - { - private static Task _cancelledTask = GetCancelledTask(); - private Stream _innerStream; - private ArraySegment _remainingBytes; - - public ReadOnlyStreamWithEncodingPreamble(Stream innerStream, Encoding encoding) - { - Contract.Assert(innerStream != null); - Contract.Assert(innerStream.CanRead); - Contract.Assert(encoding != null); - - _innerStream = innerStream; - - // Determine whether we even have a preamble to be concerned about - byte[] preamble = encoding.GetPreamble(); - int preambleLength = preamble.Length; - if (preambleLength <= 0) - { - return; - } - - // Create a double sized buffer, and read enough bytes from the stream to know - // whether we have a preamble present already or not. - int finalBufferLength = preambleLength * 2; - byte[] finalBuffer = new byte[finalBufferLength]; - int finalCount = preambleLength; - preamble.CopyTo(finalBuffer, 0); - - // Read the first bytes of the stream and see if they already contain a preamble - for (; finalCount < finalBufferLength; finalCount++) - { - int b = innerStream.ReadByte(); - if (b == -1) - { - break; - } - finalBuffer[finalCount] = (byte)b; - } - - // Did we read enough bytes to do the comparison? - if (finalCount == finalBufferLength) - { - bool foundPreamble = true; - for (int idx = 0; idx < preambleLength; idx++) - { - if (finalBuffer[idx] != finalBuffer[idx + preambleLength]) - { - foundPreamble = false; - break; - } - } - - // If we found the preamble, then just exclude it from the data that we return - if (foundPreamble) - { - finalCount = preambleLength; - } - } - - _remainingBytes = new ArraySegment(finalBuffer, 0, finalCount); - } - - public override bool CanRead - { - get { return true; } - } - - public override bool CanSeek - { - get { return false; } - } - - public override bool CanWrite - { - get { return false; } - } - - public override long Length - { - get { throw new NotImplementedException(); } - } - - public override long Position - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - public override void Flush() - { - throw new NotImplementedException(); - } - - private static Task GetCancelledTask() - { - var tcs = new TaskCompletionSource(); - tcs.SetCanceled(); - return tcs.Task; - } - - public override int Read(byte[] buffer, int offset, int count) - { - byte[] remainingArray = _remainingBytes.Array; - if (remainingArray == null) - { - return _innerStream.Read(buffer, offset, count); - } - - int remainingCount = _remainingBytes.Count; - int remainingOffset = _remainingBytes.Offset; - int result = Math.Min(count, remainingCount); - - for (int idx = 0; idx < result; ++idx) - { - buffer[offset + idx] = remainingArray[remainingOffset + idx]; - } - - if (result == remainingCount) - { - _remainingBytes = default(ArraySegment); - } - else - { - _remainingBytes = new ArraySegment(remainingArray, remainingOffset + result, remainingCount - result); - } - - return result; - } - - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - if (_remainingBytes.Array == null) - { - return _innerStream.ReadAsync(buffer, offset, count, cancellationToken); - } - if (cancellationToken.IsCancellationRequested) - { - return _cancelledTask; - } - - return Task.FromResult(Read(buffer, offset, count)); - } - - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotImplementedException(); - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - } -} diff --git a/src/System.Net.Http.Formatting/Internal/TranscodingStream.cs b/src/System.Net.Http.Formatting/Internal/TranscodingStream.cs new file mode 100644 index 000000000..f279b73ad --- /dev/null +++ b/src/System.Net.Http.Formatting/Internal/TranscodingStream.cs @@ -0,0 +1,828 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/libraries/System.Private.CoreLib/src/System/Text/TranscodingStream.cs + +using System.Buffers; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using System.Web.Http; +using Properties = System.Net.Http.Properties; + +#nullable enable + +namespace System.Text +{ + internal sealed class TranscodingStream : Stream + { + private const int DefaultReadByteBufferSize = 4 * 1024; // lifted from StreamReader.cs (FileStream) + + // We optimistically assume 1 byte ~ 1 char during transcoding. This is a good rule of thumb + // but isn't always appropriate: transcoding between single-byte and multi-byte encodings + // will violate this, as will any invalid data fixups performed by the transcoder itself. + // To account for these unknowns we have a minimum scratch buffer size we use during the + // transcoding process. This should be generous enough to account for even the largest + // fallback mechanism we're likely to see in the real world. + + private const int MinWriteRentedArraySize = 4 * 1024; + private const int MaxWriteRentedArraySize = 1024 * 1024; + + private static readonly byte[] EmptyByteBuffer = new byte[0]; + private static readonly char[] EmptyCharBuffer = new char[0]; + + private readonly Encoding _innerEncoding; + private readonly Encoding _thisEncoding; + private Stream _innerStream; // null if the wrapper has been disposed + private readonly bool _leaveOpen; + private readonly byte[] _singleByteBuffer = new byte[1]; + + /* + * Fields used for writing bytes [this] -> chars -> bytes [inner] + * Lazily initialized the first time we need to write + */ + + private Encoder? _innerEncoder; + private Decoder? _thisDecoder; + + /* + * Fields used for reading bytes [inner] -> chars -> bytes [this] + * Lazily initialized the first time we need to read + */ + + private Encoder? _thisEncoder; + private Decoder? _innerDecoder; + private int _readCharBufferMaxSize; // the maximum number of characters _innerDecoder.ReadChars can return + private byte[]? _readBuffer; // contains the data that Read() should return + private int _readBufferOffset; + private int _readBufferCount; + + internal TranscodingStream(Stream innerStream, Encoding innerEncoding, Encoding thisEncoding, bool leaveOpen = false) + { + _innerStream = innerStream ?? throw Error.ArgumentNull(nameof(innerStream)); + _leaveOpen = leaveOpen; + + _innerEncoding = innerEncoding ?? throw Error.ArgumentNull(nameof(innerEncoding)); + _thisEncoding = thisEncoding ?? throw Error.ArgumentNull(nameof(thisEncoding)); + } + + /* + * Most CanXyz methods delegate to the inner stream, returning false + * if this instance has been disposed. CanSeek is always false. + */ + + public override bool CanRead => _innerStream?.CanRead ?? false; + + public override bool CanSeek => false; + + public override bool CanWrite => _innerStream?.CanWrite ?? false; + + public override long Length => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream); + + public override long Position + { + get => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream); + set => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream); + } + + protected override void Dispose(bool disposing) + { + Debug.Assert(disposing, "This type isn't finalizable."); + base.Dispose(disposing); + + if (_innerStream is null) + { + return; // dispose called multiple times, ignore + } + + // First, flush any pending data to the inner stream. + + ArraySegment pendingData = FinalFlushWriteBuffers(); + if (pendingData.Count != 0) + { + _innerStream.Write(pendingData.Array, pendingData.Offset, pendingData.Count); + } + + // Mark our object as disposed + + Stream innerStream = _innerStream; + _innerStream = null!; + + // And dispose the inner stream if needed + + if (!_leaveOpen) + { + innerStream.Dispose(); + } + } + +#if NETCOREAPP3_1_OR_GREATER || NETSTANDARD2_1 + public override ValueTask DisposeAsync() + { + if (_innerStream is null) + { + return default; // dispose called multiple times, ignore + } + + // First, get any pending data destined for the inner stream. + + ArraySegment pendingData = FinalFlushWriteBuffers(); + + if (pendingData.Count == 0) + { + // Fast path: just dispose of the object graph. + // No need to write anything to the stream first. + + Stream innerStream = _innerStream; + _innerStream = null!; + + return (_leaveOpen) + ? default /* no work to do */ + : innerStream.DisposeAsync(); + } + + // Slower path; need to perform an async write followed by an async dispose. + + return DisposeAsyncCore(pendingData); + async ValueTask DisposeAsyncCore(ArraySegment pendingData) + { + Debug.Assert(pendingData.Count != 0); + + Stream innerStream = _innerStream; + _innerStream = null!; + + await innerStream.WriteAsync(pendingData.AsMemory()).ConfigureAwait(false); + + if (!_leaveOpen) + { + await innerStream.DisposeAsync().ConfigureAwait(false); + } + } + } +#endif + +#pragma warning disable CS3016 // Arrays as attribute arguments is not CLS-compliant +#pragma warning disable CS8774 // Member must have a non-null value when exiting. + + // Sets up the data structures that are necessary before any read operation takes place, + // throwing if the object is in a state where reads are not possible. + [MemberNotNull(nameof(_innerDecoder), nameof(_thisEncoder), nameof(_readBuffer))] + private void EnsurePreReadConditions() + { + ThrowIfDisposed(); + if (_innerDecoder is null) + { + InitializeReadDataStructures(); + } + + void InitializeReadDataStructures() + { + if (!CanRead) + { + throw Error.NotSupported(Properties.Resources.NotSupported_UnreadableStream); + } + + _innerDecoder = _innerEncoding.GetDecoder(); + _thisEncoder = _thisEncoding.GetEncoder(); + _readCharBufferMaxSize = _innerEncoding.GetMaxCharCount(DefaultReadByteBufferSize); + + // Can't use ArrayPool for the below array since it's an instance field of this object. + // But since we never expose the raw array contents to our callers we can get away + // with skipping the array zero-init during allocation. The segment points to the + // data which we haven't yet read; however, we own the entire backing array and can + // re-create the segment as needed once the array is repopulated. + +#if NET5_0_OR_GREATER + _readBuffer = GC.AllocateUninitializedArray(_thisEncoding.GetMaxByteCount(_readCharBufferMaxSize)); +#else + _readBuffer = new byte[_thisEncoding.GetMaxByteCount(_readCharBufferMaxSize)]; +#endif + } + } + + // Sets up the data structures that are necessary before any write operation takes place, + // throwing if the object is in a state where writes are not possible. + [MemberNotNull(nameof(_thisDecoder), nameof(_innerEncoder))] + private void EnsurePreWriteConditions() + { + ThrowIfDisposed(); + if (_innerEncoder is null) + { + InitializeReadDataStructures(); + } + + void InitializeReadDataStructures() + { + if (!CanWrite) + { + throw Error.NotSupported(Properties.Resources.NotSupported_UnwritableStream); + } + + _innerEncoder = _innerEncoding.GetEncoder(); + _thisDecoder = _thisEncoding.GetDecoder(); + } + } + +#pragma warning restore CS8774 // Member must have a non-null value when exiting. +#pragma warning restore CS3016 // Arrays as attribute arguments is not CLS-compliant + + // returns any pending data that needs to be flushed to the inner stream before disposal + private ArraySegment FinalFlushWriteBuffers() + { + // If this stream was never used for writing, no-op. + + if (_thisDecoder is null || _innerEncoder is null) + { + return default; + } + + // convert bytes [this] -> chars + // Having leftover data in our buffers should be very rare since it should only + // occur if the end of the stream contains an incomplete multi-byte sequence. + // Let's not bother complicating this logic with array pool rentals or allocation- + // avoiding loops. + + char[] chars = EmptyCharBuffer; + int charCount = _thisDecoder.GetCharCount(EmptyByteBuffer, 0, 0, flush: true); + if (charCount > 0) + { + chars = new char[charCount]; + charCount = _thisDecoder.GetChars(EmptyByteBuffer, 0, 0, chars, 0, flush: true); + } + + // convert chars -> bytes [inner] + // It's possible that _innerEncoder might need to perform some end-of-text fixup + // (due to flush: true), even if _thisDecoder didn't need to do so. + + byte[] bytes = EmptyByteBuffer; + int byteCount = _innerEncoder.GetByteCount(chars, 0, charCount, flush: true); + if (byteCount > 0) + { + bytes = new byte[byteCount]; + byteCount = _innerEncoder.GetBytes(chars, 0, charCount, bytes, 0, flush: true); + } + + return new ArraySegment(bytes, 0, byteCount); + } + + public override void Flush() + { + // Don't pass flush: true to our inner decoder + encoder here, since it could cause data + // corruption if a flush occurs mid-stream. Wait until the stream is being closed. + + ThrowIfDisposed(); + _innerStream.Flush(); + } + + public override Task FlushAsync(CancellationToken cancellationToken) + { + // Don't pass flush: true to our inner decoder + encoder here, since it could cause data + // corruption if a flush occurs mid-stream. Wait until the stream is being closed. + + ThrowIfDisposed(); + return _innerStream.FlushAsync(cancellationToken); + } + + public override int Read(byte[] buffer, int offset, int count) + { + ValidateBufferArguments(buffer, offset, count); + + return Read(new Span(buffer, offset, count)); + } + +#if NETCOREAPP || NETSTANDARD2_1 + public override +#else + private +#endif + int Read(Span buffer) + { + EnsurePreReadConditions(); + + // If there's no data in our pending read buffer, we'll need to populate it from + // the inner stream. We read the inner stream's bytes, decode that to chars using + // the 'inner' encoding, then re-encode those chars under the 'this' encoding. + // We've already calculated the worst-case expansions for the intermediate buffers, + // so we use GetChars / GetBytes instead of Convert to simplify the below code + // and to ensure an exception is thrown if the Encoding reported an incorrect + // worst-case expansion. + + if (_readBufferCount == 0) + { + byte[] rentedBytes = ArrayPool.Shared.Rent(DefaultReadByteBufferSize); + char[] rentedChars = ArrayPool.Shared.Rent(_readCharBufferMaxSize); + + try + { + int pendingReadDataPopulatedJustNow; + bool isEofReached; + + do + { + // Beware: Use our constant value instead of 'rentedBytes.Length' for the count + // parameter below. The reason for this is that the array pool could've returned + // a larger-than-expected array, but our worst-case expansion calculations + // performed earlier didn't take that into account. + + int innerBytesReadJustNow = _innerStream.Read(rentedBytes, 0, DefaultReadByteBufferSize); + isEofReached = (innerBytesReadJustNow == 0); + + // Convert bytes [inner] -> chars, then convert chars -> bytes [this]. + // We can't return 0 to our caller until inner stream EOF has been reached. But if the + // inner stream returns a non-empty but incomplete buffer, GetBytes may return 0 anyway + // since it can't yet make forward progress on the input data. If this happens, we'll + // loop so that we don't return 0 to our caller until we truly see inner stream EOF. + + int charsDecodedJustNow = _innerDecoder.GetChars(rentedBytes, 0, innerBytesReadJustNow, rentedChars, 0, flush: isEofReached); + pendingReadDataPopulatedJustNow = _thisEncoder.GetBytes(rentedChars, 0, charsDecodedJustNow, _readBuffer, 0, flush: isEofReached); + } while (!isEofReached && pendingReadDataPopulatedJustNow == 0); + + _readBufferOffset = 0; + _readBufferCount = pendingReadDataPopulatedJustNow; + } + finally + { + ArrayPool.Shared.Return(rentedBytes); + ArrayPool.Shared.Return(rentedChars); + } + } + + // At this point: (a) we've populated our pending read buffer and there's + // useful data to return to our caller; or (b) the pending read buffer is + // empty because the inner stream has reached EOF and all pending read data + // has already been flushed, and we should return 0. + + int bytesToReturn = Math.Min(_readBufferCount, buffer.Length); + _readBuffer.AsSpan(_readBufferOffset, bytesToReturn).CopyTo(buffer); + _readBufferOffset += bytesToReturn; + _readBufferCount -= bytesToReturn; + return bytesToReturn; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + ValidateBufferArguments(buffer, offset, count); + + return ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); + } + +#if NETCOREAPP || NETSTANDARD2_1 + public override +#else + private +#endif + ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + EnsurePreReadConditions(); + + if (cancellationToken.IsCancellationRequested) + { +#if NETCOREAPP || NETSTANDARD + return new ValueTask(Task.FromCanceled(cancellationToken)); +#else + // Lose track of the CancellationToken in this case. + return new ValueTask(TaskHelpers.Canceled()); +#endif + } + + return ReadAsyncCore(buffer, cancellationToken); + async ValueTask ReadAsyncCore(Memory buffer, CancellationToken cancellationToken) + { + // If there's no data in our pending read buffer, we'll need to populate it from + // the inner stream. We read the inner stream's bytes, decode that to chars using + // the 'inner' encoding, then re-encode those chars under the 'this' encoding. + // We've already calculated the worst-case expansions for the intermediate buffers, + // so we use GetChars / GetBytes instead of Convert to simplify the below code + // and to ensure an exception is thrown if the Encoding reported an incorrect + // worst-case expansion. + + if (_readBufferCount == 0) + { + byte[] rentedBytes = ArrayPool.Shared.Rent(DefaultReadByteBufferSize); + char[] rentedChars = ArrayPool.Shared.Rent(_readCharBufferMaxSize); + + try + { + int pendingReadDataPopulatedJustNow; + bool isEofReached; + + do + { + // Beware: Use our constant value instead of 'rentedBytes.Length' when creating + // the Mem struct. The reason for this is that the array pool could've returned + // a larger-than-expected array, but our worst-case expansion calculations + // performed earlier didn't take that into account. + + int innerBytesReadJustNow = await _innerStream.ReadAsync(rentedBytes, 0, DefaultReadByteBufferSize, cancellationToken).ConfigureAwait(false); + isEofReached = (innerBytesReadJustNow == 0); + + // Convert bytes [inner] -> chars, then convert chars -> bytes [this]. + // We can't return 0 to our caller until inner stream EOF has been reached. But if the + // inner stream returns a non-empty but incomplete buffer, GetBytes may return 0 anyway + // since it can't yet make forward progress on the input data. If this happens, we'll + // loop so that we don't return 0 to our caller until we truly see inner stream EOF. + + int charsDecodedJustNow = _innerDecoder.GetChars(rentedBytes, 0, innerBytesReadJustNow, rentedChars, 0, flush: isEofReached); + pendingReadDataPopulatedJustNow = _thisEncoder.GetBytes(rentedChars, 0, charsDecodedJustNow, _readBuffer, 0, flush: isEofReached); + } while (!isEofReached && pendingReadDataPopulatedJustNow == 0); + + _readBufferOffset = 0; + _readBufferCount = pendingReadDataPopulatedJustNow; + } + finally + { + ArrayPool.Shared.Return(rentedBytes); + ArrayPool.Shared.Return(rentedChars); + } + } + + // At this point: (a) we've populated our pending read buffer and there's + // useful data to return to our caller; or (b) the pending read buffer is + // empty because the inner stream has reached EOF and all pending read data + // has already been flushed, and we should return 0. + + int bytesToReturn = Math.Min(_readBufferCount, buffer.Length); + _readBuffer.AsSpan(_readBufferOffset, bytesToReturn).CopyTo(buffer.Span); + _readBufferOffset += bytesToReturn; + _readBufferCount -= bytesToReturn; + return bytesToReturn; + } + } + + public override int ReadByte() + { + return Read(_singleByteBuffer, offset: 0, count: 1) != 0 ? _singleByteBuffer[0] : -1; + } + + public override long Seek(long offset, SeekOrigin origin) + => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream); + + public override void SetLength(long value) + => throw Error.NotSupported(Properties.Resources.NotSupported_UnseekableStream); + +#if NET6_0_OR_GREATER + [StackTraceHidden] +#endif + private void ThrowIfDisposed() + { + if (_innerStream is null) + { + ThrowObjectDisposedException(); + } + } + + [DoesNotReturn] +#if NET6_0_OR_GREATER + [StackTraceHidden] +#endif + private void ThrowObjectDisposedException() + { + throw new ObjectDisposedException(GetType().Name, Properties.Resources.ObjectDisposed_StreamClosed); + } + + public override void Write(byte[] buffer, int offset, int count) + { + ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP || NETSTANDARD2_1 + Write(new ReadOnlySpan(buffer, offset, count)); +#else + WriteCore(buffer, offset, count); +#endif + } + +#if NETCOREAPP || NETSTANDARD2_1 + public override void Write(ReadOnlySpan buffer) + { + EnsurePreWriteConditions(); + + if (buffer.IsEmpty) + { + return; + } + + int rentalLength = buffer.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize : + buffer.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize : + buffer.Length; + + char[] scratchChars = ArrayPool.Shared.Rent(rentalLength); + byte[] scratchBytes = ArrayPool.Shared.Rent(rentalLength); + + try + { + bool decoderFinished, encoderFinished; + do + { + // convert bytes [this] -> chars + + _thisDecoder.Convert( + bytes: buffer, + chars: scratchChars, + flush: false, + out int bytesConsumed, + out int charsWritten, + out decoderFinished); + + buffer = buffer.Slice(bytesConsumed); + + // convert chars -> bytes [inner] + + Span decodedChars = scratchChars.AsSpan(0, charsWritten); + + do + { + _innerEncoder.Convert( + chars: decodedChars, + bytes: scratchBytes, + flush: false, + out int charsConsumed, + out int bytesWritten, + out encoderFinished); + + decodedChars = decodedChars.Slice(charsConsumed); + + // It's more likely that the inner stream provides an optimized implementation of + // Write(byte[], ...) over Write(ROS), so we'll prefer the byte[]-based overloads. + + _innerStream.Write(scratchBytes, 0, bytesWritten); + } while (!encoderFinished); + } while (!decoderFinished); + } + finally + { + ArrayPool.Shared.Return(scratchChars); + ArrayPool.Shared.Return(scratchBytes); + } + } +#else + private void WriteCore(byte[] buffer, int offset, int count) + { + EnsurePreWriteConditions(); + + if (count == 0) + { + return; + } + + int rentalLength = buffer.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize : + buffer.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize : + buffer.Length; + + char[] scratchChars = ArrayPool.Shared.Rent(rentalLength); + byte[] scratchBytes = ArrayPool.Shared.Rent(rentalLength); + + try + { + bool decoderFinished, encoderFinished; + do + { + // convert bytes [this] -> chars + + _thisDecoder.Convert( + bytes: buffer, + byteIndex: offset, + byteCount: count, + chars: scratchChars, + charIndex: 0, + charCount: rentalLength, + flush: false, + out int bytesConsumed, + out int charsWritten, + out decoderFinished); + + offset += bytesConsumed; + count -= bytesConsumed; + + // convert chars -> bytes [inner] + + int scratchOffset = 0; + do + { + _innerEncoder.Convert( + chars: scratchChars, + charIndex: scratchOffset, + charCount: charsWritten, + bytes: scratchBytes, + byteIndex: 0, + byteCount: rentalLength, + flush: false, + out int charsConsumed, + out int bytesWritten, + out encoderFinished); + + scratchOffset += charsConsumed; + charsWritten -= charsConsumed; + + // It's more likely that the inner stream provides an optimized implementation of + // Write(byte[], ...) over Write(ROS), so we'll prefer the byte[]-based overloads. + + _innerStream.Write(scratchBytes, 0, bytesWritten); + } while (!encoderFinished); + } while (!decoderFinished); + } + finally + { + ArrayPool.Shared.Return(scratchChars); + ArrayPool.Shared.Return(scratchBytes); + } + } +#endif + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + ValidateBufferArguments(buffer, offset, count); + +#if NETCOREAPP || NETSTANDARD2_1 + return WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken).AsTask(); +#else + return WriteAsyncCore(buffer, offset, count, cancellationToken).AsTask(); +#endif + } + +#if NETCOREAPP || NETSTANDARD2_1 + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + EnsurePreWriteConditions(); + + if (cancellationToken.IsCancellationRequested) + { + return new ValueTask(Task.FromCanceled(cancellationToken)); + } + + if (buffer.IsEmpty) + { + // ValueTask.CompletedTask + return default; + } + + return WriteAsyncCore(buffer, cancellationToken); + async ValueTask WriteAsyncCore(ReadOnlyMemory remainingOuterEncodedBytes, CancellationToken cancellationToken) + { + int rentalLength = remainingOuterEncodedBytes.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize : + remainingOuterEncodedBytes.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize: + remainingOuterEncodedBytes.Length; + + char[] scratchChars = ArrayPool.Shared.Rent(rentalLength); + byte[] scratchBytes = ArrayPool.Shared.Rent(rentalLength); + + try + { + bool decoderFinished, encoderFinished; + do + { + // convert bytes [this] -> chars + + _thisDecoder.Convert( + bytes: buffer, + chars: scratchChars, + flush: false, + out int bytesConsumed, + out int charsWritten, + out decoderFinished); + + buffer = buffer.Slice(bytesConsumed); + + // convert chars -> bytes [inner] + + Span decodedChars = scratchChars.AsSpan(0, charsWritten); + + do + { + _innerEncoder.Convert( + chars: decodedChars, + bytes: scratchBytes, + flush: false, + out int charsConsumed, + out int bytesWritten, + out encoderFinished); + + decodedChars = decodedChars.Slice(charsConsumed); + + await _innerStream.WriteAsync(scratchBytes, 0, bytesWritten, cancellationToken).ConfigureAwait(false); + } while (!encoderFinished); + } while (!decoderFinished); + } + finally + { + ArrayPool.Shared.Return(scratchChars); + ArrayPool.Shared.Return(scratchBytes); + } + } + } +#else + private ValueTask WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + EnsurePreWriteConditions(); + + if (cancellationToken.IsCancellationRequested) + { +#if NETSTANDARD + return new ValueTask(Task.FromCanceled(cancellationToken)); +#else + // Lose track of the CancellationToken in this case. + return new ValueTask(TaskHelpers.Canceled()); +#endif + } + + if (count == 0) + { + // ValueTask.CompletedTask + return default; + } + + return WriteAsyncCore(buffer, cancellationToken); + async ValueTask WriteAsyncCore(ReadOnlyMemory remainingOuterEncodedBytes, CancellationToken cancellationToken) + { + int rentalLength = remainingOuterEncodedBytes.Length < MinWriteRentedArraySize ? MinWriteRentedArraySize : + remainingOuterEncodedBytes.Length > MaxWriteRentedArraySize ? MaxWriteRentedArraySize : + remainingOuterEncodedBytes.Length; + + char[] scratchChars = ArrayPool.Shared.Rent(rentalLength); + byte[] scratchBytes = ArrayPool.Shared.Rent(rentalLength); + + try + { + bool decoderFinished, encoderFinished; + do + { + // convert bytes [this] -> chars + + _thisDecoder.Convert( + bytes: buffer, + byteIndex: offset, + byteCount: count, + chars: scratchChars, + charIndex: 0, + charCount: rentalLength, + flush: false, + out int bytesConsumed, + out int charsWritten, + out decoderFinished); + + offset += bytesConsumed; + count -= bytesConsumed; + + // convert chars -> bytes [inner] + + int scratchOffset = 0; + do + { + _innerEncoder.Convert( + chars: scratchChars, + charIndex: scratchOffset, + charCount: charsWritten, + bytes: scratchBytes, + byteIndex: 0, + byteCount: rentalLength, + flush: false, + out int charsConsumed, + out int bytesWritten, + out encoderFinished); + + scratchOffset += charsConsumed; + charsWritten -= charsConsumed; + + await _innerStream.WriteAsync(scratchBytes, 0, bytesWritten, cancellationToken).ConfigureAwait(false); + } while (!encoderFinished); + } while (!decoderFinished); + } + finally + { + ArrayPool.Shared.Return(scratchChars); + ArrayPool.Shared.Return(scratchBytes); + } + } + } +#endif + + public override void WriteByte(byte value) + { + _singleByteBuffer[0] = value; + Write(_singleByteBuffer, offset: 0, count: 1); + } + + // From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void ValidateBufferArguments(byte[] buffer, int offset, int count) + { + if (buffer is null) + { + throw Error.ArgumentNull(nameof(buffer)); + } + + if (offset < 0) + { + throw Error.ArgumentMustBeGreaterThanOrEqualTo(nameof(offset), offset, minValue: 0); + } + + if ((uint)count > buffer.Length - offset) + { + throw Error.ArgumentOutOfRange(nameof(count), count, Properties.Resources.Argument_InvalidOffLen); + } + } + } +} diff --git a/src/System.Net.Http.Formatting/Internal/TypeExtensions.cs b/src/System.Net.Http.Formatting/Internal/TypeExtensions.cs index 0f22bfcea..aab7ca05c 100644 --- a/src/System.Net.Http.Formatting/Internal/TypeExtensions.cs +++ b/src/System.Net.Http.Formatting/Internal/TypeExtensions.cs @@ -8,7 +8,7 @@ namespace System.Net.Http { internal static class TypeExtensions { -#if NETFX_CORE +#if NETSTANDARD1_3 private static bool EqualTo(this Type[] t1, Type[] t2) { if (t1.Length != t2.Length) @@ -42,7 +42,7 @@ public static Type ExtractGenericInterface(this Type queryType, Type interfaceTy return (matchesInterface(queryType)) ? queryType : queryType.GetInterfaces().FirstOrDefault(matchesInterface); } -#if NETFX_CORE +#if NETSTANDARD1_3 public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; @@ -54,7 +54,7 @@ public static Type[] GetInterfaces(this Type type) } #endif -#if NETFX_CORE +#if NETSTANDARD1_3 public static bool IsAssignableFrom(this Type type, Type c) { return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo()); @@ -63,7 +63,7 @@ public static bool IsAssignableFrom(this Type type, Type c) public static bool IsGenericType(this Type type) { -#if NETFX_CORE +#if NETSTANDARD1_3 return type.GetTypeInfo().IsGenericType; #else return type.IsGenericType; @@ -72,7 +72,7 @@ public static bool IsGenericType(this Type type) public static bool IsInterface(this Type type) { -#if NETFX_CORE +#if NETSTANDARD1_3 return type.GetTypeInfo().IsInterface; #else return type.IsInterface; @@ -81,7 +81,7 @@ public static bool IsInterface(this Type type) public static bool IsValueType(this Type type) { -#if NETFX_CORE +#if NETSTANDARD1_3 return type.GetTypeInfo().IsValueType; #else return type.IsValueType; diff --git a/src/System.Net.Http.Formatting/InvalidByteRangeException.cs b/src/System.Net.Http.Formatting/InvalidByteRangeException.cs index 230564dbd..ef6175208 100644 --- a/src/System.Net.Http.Formatting/InvalidByteRangeException.cs +++ b/src/System.Net.Http.Formatting/InvalidByteRangeException.cs @@ -9,7 +9,7 @@ namespace System.Net.Http { /// - /// An exception thrown by in case none of the requested ranges + /// An exception thrown by in case none of the requested ranges /// overlap with the current extend of the selected resource. The current extend of the resource /// is indicated in the ContentRange property. /// @@ -35,11 +35,13 @@ public InvalidByteRangeException(ContentRangeHeaderValue contentRange, string me Initialize(contentRange); } +#if !NETSTANDARD1_3 // Exception is not serializable in netstandard1.3. public InvalidByteRangeException(ContentRangeHeaderValue contentRange, SerializationInfo info, StreamingContext context) : base(info, context) { Initialize(contentRange); } +#endif /// /// The current extend of the resource indicated in terms of a ContentRange header field. diff --git a/src/System.Net.Http.Formatting/MimeBodyPart.cs b/src/System.Net.Http.Formatting/MimeBodyPart.cs index aa14f5dc6..cd07e8bba 100644 --- a/src/System.Net.Http.Formatting/MimeBodyPart.cs +++ b/src/System.Net.Http.Formatting/MimeBodyPart.cs @@ -39,8 +39,8 @@ public MimeBodyPart(MultipartStreamProvider streamProvider, int maxBodyPartHeade Segments = new List>(2); _headers = FormattingUtilities.CreateEmptyContentHeaders(); HeaderParser = new InternetMessageFormatHeaderParser( - _headers, - maxBodyPartHeaderSize, + _headers, + maxBodyPartHeaderSize, ignoreHeaderValidation: true); } @@ -190,7 +190,7 @@ private void CleanupOutputStream() } else { -#if NETFX_CORE +#if NETSTANDARD1_3 _outputStream.Dispose(); #else _outputStream.Close(); diff --git a/src/System.Net.Http.Formatting/MultipartFormDataStreamProvider.cs b/src/System.Net.Http.Formatting/MultipartFormDataStreamProvider.cs index f2c997e92..1e012106b 100644 --- a/src/System.Net.Http.Formatting/MultipartFormDataStreamProvider.cs +++ b/src/System.Net.Http.Formatting/MultipartFormDataStreamProvider.cs @@ -11,12 +11,12 @@ namespace System.Net.Http { /// - /// A implementation suited for use with HTML file uploads for writing file - /// content to a . The stream provider looks at the Content-Disposition header + /// A implementation suited for use with HTML file uploads for writing file + /// content to a . The stream provider looks at the Content-Disposition header /// field and determines an output based on the presence of a filename parameter. - /// If a filename parameter is present in the Content-Disposition header field then the body + /// If a filename parameter is present in the Content-Disposition header field then the body /// part is written to a , otherwise it is written to a . - /// This makes it convenient to process MIME Multipart HTML Form data which is a combination of form + /// This makes it convenient to process MIME Multipart HTML Form data which is a combination of form /// data and file content. /// public class MultipartFormDataStreamProvider : MultipartFileStreamProvider @@ -52,7 +52,7 @@ public MultipartFormDataStreamProvider(string rootPath, int bufferSize) /// /// This body part stream provider examines the headers provided by the MIME multipart parser - /// and decides whether it should return a file stream or a memory stream for the body part to be + /// and decides whether it should return a file stream or a memory stream for the body part to be /// written to. /// /// The parent MIME multipart HttpContent instance. diff --git a/src/System.Net.Http.Formatting/MultipartRelatedStreamProvider.cs b/src/System.Net.Http.Formatting/MultipartRelatedStreamProvider.cs index 464f891e7..68b5a6034 100644 --- a/src/System.Net.Http.Formatting/MultipartRelatedStreamProvider.cs +++ b/src/System.Net.Http.Formatting/MultipartRelatedStreamProvider.cs @@ -24,7 +24,7 @@ public class MultipartRelatedStreamProvider : MultipartStreamProvider private HttpContent _parent; /// - /// Gets the instance that has been marked as the root content in the + /// Gets the instance that has been marked as the root content in the /// MIME multipart related message using the start parameter. If no start parameter is /// present then pick the first of the children. /// @@ -71,7 +71,7 @@ private static HttpContent FindRootContent(HttpContent parent, IEnumerable /// A strongly-typed resource class, for looking up localized strings, etc. /// @@ -19,19 +20,19 @@ namespace System.Net.Http.Properties { // 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.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { - + private static global::System.Resources.ResourceManager resourceMan; - + private static global::System.Globalization.CultureInfo resourceCulture; - + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } - + /// /// Returns the cached ResourceManager instance used by this class. /// @@ -39,7 +40,7 @@ internal Resources() { internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { -#if NETFX_CORE +#if NETSTANDARD1_3 var assembly = typeof(Resources).GetTypeInfo().Assembly; #else var assembly = typeof(Resources).Assembly; @@ -50,7 +51,7 @@ internal Resources() { return resourceMan; } } - + /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. @@ -64,7 +65,16 @@ internal Resources() { resourceCulture = value; } } - + + /// + /// Looks up a localized string similar to Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.. + /// + internal static string Argument_InvalidOffLen { + get { + return ResourceManager.GetString("Argument_InvalidOffLen", resourceCulture); + } + } + /// /// Looks up a localized string similar to Async Callback threw an exception.. /// @@ -73,7 +83,7 @@ internal static string AsyncResult_CallbackThrewException { return ResourceManager.GetString("AsyncResult_CallbackThrewException", resourceCulture); } } - + /// /// Looks up a localized string similar to The IAsyncResult implementation '{0}' tried to complete a single operation multiple times. This could be caused by an incorrect application IAsyncResult implementation or other extensibility code, such as an IAsyncResult that returns incorrect CompletedSynchronously values or invokes the AsyncCallback multiple times.. /// @@ -82,7 +92,7 @@ internal static string AsyncResult_MultipleCompletes { return ResourceManager.GetString("AsyncResult_MultipleCompletes", resourceCulture); } } - + /// /// Looks up a localized string similar to End cannot be called twice on an AsyncResult.. /// @@ -91,7 +101,7 @@ internal static string AsyncResult_MultipleEnds { return ResourceManager.GetString("AsyncResult_MultipleEnds", resourceCulture); } } - + /// /// Looks up a localized string similar to An incorrect IAsyncResult was provided to an 'End' method. The IAsyncResult object passed to 'End' must be the one returned from the matching 'Begin' or passed to the callback provided to 'Begin'.. /// @@ -100,7 +110,7 @@ internal static string AsyncResult_ResultMismatch { return ResourceManager.GetString("AsyncResult_ResultMismatch", resourceCulture); } } - + /// /// Looks up a localized string similar to Found zero byte ranges. There must be at least one byte range provided.. /// @@ -109,7 +119,7 @@ internal static string ByteRangeStreamContentNoRanges { return ResourceManager.GetString("ByteRangeStreamContentNoRanges", resourceCulture); } } - + /// /// Looks up a localized string similar to The range unit '{0}' is not valid. The range must have a unit of '{1}'.. /// @@ -118,7 +128,7 @@ internal static string ByteRangeStreamContentNotBytesRange { return ResourceManager.GetString("ByteRangeStreamContentNotBytesRange", resourceCulture); } } - + /// /// Looks up a localized string similar to The stream over which '{0}' provides a range view must have a length greater than or equal to 1.. /// @@ -127,7 +137,7 @@ internal static string ByteRangeStreamEmpty { return ResourceManager.GetString("ByteRangeStreamEmpty", resourceCulture); } } - + /// /// Looks up a localized string similar to The 'From' value of the range must be less than or equal to {0}.. /// @@ -136,7 +146,7 @@ internal static string ByteRangeStreamInvalidFrom { return ResourceManager.GetString("ByteRangeStreamInvalidFrom", resourceCulture); } } - + /// /// Looks up a localized string similar to An attempt was made to move the position before the beginning of the stream.. /// @@ -145,7 +155,7 @@ internal static string ByteRangeStreamInvalidOffset { return ResourceManager.GetString("ByteRangeStreamInvalidOffset", resourceCulture); } } - + /// /// Looks up a localized string similar to None of the requested ranges ({0}) overlap with the current extent of the selected resource.. /// @@ -154,7 +164,7 @@ internal static string ByteRangeStreamNoneOverlap { return ResourceManager.GetString("ByteRangeStreamNoneOverlap", resourceCulture); } } - + /// /// Looks up a localized string similar to The requested range ({0}) does not overlap with the current extent of the selected resource.. /// @@ -163,7 +173,7 @@ internal static string ByteRangeStreamNoOverlap { return ResourceManager.GetString("ByteRangeStreamNoOverlap", resourceCulture); } } - + /// /// Looks up a localized string similar to The stream over which '{0}' provides a range view must be seekable.. /// @@ -172,7 +182,7 @@ internal static string ByteRangeStreamNotSeekable { return ResourceManager.GetString("ByteRangeStreamNotSeekable", resourceCulture); } } - + /// /// Looks up a localized string similar to This is a read-only stream.. /// @@ -181,7 +191,7 @@ internal static string ByteRangeStreamReadOnly { return ResourceManager.GetString("ByteRangeStreamReadOnly", resourceCulture); } } - + /// /// Looks up a localized string similar to A null '{0}' is not valid.. /// @@ -190,7 +200,7 @@ internal static string CannotHaveNullInList { return ResourceManager.GetString("CannotHaveNullInList", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' of '{1}' cannot be used as a supported media type because it is a media range.. /// @@ -199,7 +209,7 @@ internal static string CannotUseMediaRangeForSupportedMediaType { return ResourceManager.GetString("CannotUseMediaRangeForSupportedMediaType", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' type cannot accept a null value for the value type '{1}'.. /// @@ -208,7 +218,7 @@ internal static string CannotUseNullValueType { return ResourceManager.GetString("CannotUseNullValueType", resourceCulture); } } - + /// /// Looks up a localized string similar to The specified value is not a valid cookie name.. /// @@ -217,7 +227,7 @@ internal static string CookieInvalidName { return ResourceManager.GetString("CookieInvalidName", resourceCulture); } } - + /// /// Looks up a localized string similar to Cookie cannot be null.. /// @@ -226,7 +236,7 @@ internal static string CookieNull { return ResourceManager.GetString("CookieNull", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' list is invalid because it contains one or more null items.. /// @@ -235,7 +245,7 @@ internal static string DelegatingHandlerArrayContainsNullItem { return ResourceManager.GetString("DelegatingHandlerArrayContainsNullItem", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' list is invalid because the property '{1}' of '{2}' is not null.. /// @@ -244,7 +254,7 @@ internal static string DelegatingHandlerArrayHasNonNullInnerHandler { return ResourceManager.GetString("DelegatingHandlerArrayHasNonNullInnerHandler", resourceCulture); } } - + /// /// Looks up a localized string similar to Error reading HTML form URL-encoded data stream.. /// @@ -253,7 +263,7 @@ internal static string ErrorReadingFormUrlEncodedStream { return ResourceManager.GetString("ErrorReadingFormUrlEncodedStream", resourceCulture); } } - + /// /// Looks up a localized string similar to Mismatched types at node '{0}'.. /// @@ -262,7 +272,7 @@ internal static string FormUrlEncodedMismatchingTypes { return ResourceManager.GetString("FormUrlEncodedMismatchingTypes", resourceCulture); } } - + /// /// Looks up a localized string similar to Error parsing HTML form URL-encoded data, byte {0}.. /// @@ -271,7 +281,7 @@ internal static string FormUrlEncodedParseError { return ResourceManager.GetString("FormUrlEncodedParseError", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid HTTP status code: '{0}'. The status code must be between {1} and {2}.. /// @@ -280,7 +290,7 @@ internal static string HttpInvalidStatusCode { return ResourceManager.GetString("HttpInvalidStatusCode", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid HTTP version: '{0}'. The version must start with the characters '{1}'.. /// @@ -289,7 +299,7 @@ internal static string HttpInvalidVersion { return ResourceManager.GetString("HttpInvalidVersion", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' of the '{1}' has already been read.. /// @@ -298,7 +308,7 @@ internal static string HttpMessageContentAlreadyRead { return ResourceManager.GetString("HttpMessageContentAlreadyRead", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' must be seekable in order to create an '{1}' instance containing an entity body. . /// @@ -307,7 +317,7 @@ internal static string HttpMessageContentStreamMustBeSeekable { return ResourceManager.GetString("HttpMessageContentStreamMustBeSeekable", resourceCulture); } } - + /// /// Looks up a localized string similar to Error reading HTTP message.. /// @@ -316,7 +326,7 @@ internal static string HttpMessageErrorReading { return ResourceManager.GetString("HttpMessageErrorReading", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid '{0}' instance provided. It does not have a content type header with a value of '{1}'.. /// @@ -325,7 +335,7 @@ internal static string HttpMessageInvalidMediaType { return ResourceManager.GetString("HttpMessageInvalidMediaType", resourceCulture); } } - + /// /// Looks up a localized string similar to HTTP Request URI cannot be an empty string.. /// @@ -334,7 +344,7 @@ internal static string HttpMessageParserEmptyUri { return ResourceManager.GetString("HttpMessageParserEmptyUri", resourceCulture); } } - + /// /// Looks up a localized string similar to Error parsing HTTP message header byte {0} of message {1}.. /// @@ -343,7 +353,7 @@ internal static string HttpMessageParserError { return ResourceManager.GetString("HttpMessageParserError", resourceCulture); } } - + /// /// Looks up a localized string similar to An invalid number of '{0}' header fields were present in the HTTP Request. It must contain exactly one '{0}' header field but found {1}.. /// @@ -352,7 +362,7 @@ internal static string HttpMessageParserInvalidHostCount { return ResourceManager.GetString("HttpMessageParserInvalidHostCount", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid URI scheme: '{0}'. The URI scheme must be a valid '{1}' scheme.. /// @@ -361,7 +371,7 @@ internal static string HttpMessageParserInvalidUriScheme { return ResourceManager.GetString("HttpMessageParserInvalidUriScheme", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid array at node '{0}'.. /// @@ -370,7 +380,7 @@ internal static string InvalidArrayInsert { return ResourceManager.GetString("InvalidArrayInsert", resourceCulture); } } - + /// /// Looks up a localized string similar to Traditional style array without '[]' is not supported with nested object at location {0}.. /// @@ -379,7 +389,16 @@ internal static string JQuery13CompatModeNotSupportNestedJson { return ResourceManager.GetString("JQuery13CompatModeNotSupportNestedJson", resourceCulture); } } - + + /// + /// Looks up a localized string similar to Unable to validate types on this platform when {0} is 'true'. Please reset {0} or move to a supported platform, one where the 'netstandard2.0' assembly is usable.. + /// + internal static string JsonMediaTypeFormatter_DCS_NotSupported { + get { + return ResourceManager.GetString("JsonMediaTypeFormatter_DCS_NotSupported", resourceCulture); + } + } + /// /// Looks up a localized string similar to The '{0}' method returned null. It must return a JSON serializer instance.. /// @@ -388,7 +407,7 @@ internal static string JsonSerializerFactoryReturnedNull { return ResourceManager.GetString("JsonSerializerFactoryReturnedNull", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' method threw an exception when attempting to create a JSON serializer.. /// @@ -397,7 +416,7 @@ internal static string JsonSerializerFactoryThrew { return ResourceManager.GetString("JsonSerializerFactoryThrew", resourceCulture); } } - + /// /// Looks up a localized string similar to The maximum read depth ({0}) has been exceeded because the form url-encoded data being read has more levels of nesting than is allowed.. /// @@ -406,7 +425,7 @@ internal static string MaxDepthExceeded { return ResourceManager.GetString("MaxDepthExceeded", resourceCulture); } } - + /// /// Looks up a localized string similar to The number of keys in a NameValueCollection has exceeded the limit of '{0}'. You can adjust it by modifying the MaxHttpCollectionKeys property on the '{1}' class.. /// @@ -415,7 +434,7 @@ internal static string MaxHttpCollectionKeyLimitReached { return ResourceManager.GetString("MaxHttpCollectionKeyLimitReached", resourceCulture); } } - + /// /// Looks up a localized string similar to Error parsing BSON data; unable to read content as a {0}.. /// @@ -424,7 +443,7 @@ internal static string MediaTypeFormatter_BsonParseError_MissingData { return ResourceManager.GetString("MediaTypeFormatter_BsonParseError_MissingData", resourceCulture); } } - + /// /// Looks up a localized string similar to Error parsing BSON data; unexpected dictionary content: {0} entries, first key '{1}'.. /// @@ -433,7 +452,7 @@ internal static string MediaTypeFormatter_BsonParseError_UnexpectedData { return ResourceManager.GetString("MediaTypeFormatter_BsonParseError_UnexpectedData", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' method returned null. It must return a JSON reader instance.. /// @@ -442,7 +461,7 @@ internal static string MediaTypeFormatter_JsonReaderFactoryReturnedNull { return ResourceManager.GetString("MediaTypeFormatter_JsonReaderFactoryReturnedNull", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' method returned null. It must return a JSON writer instance.. /// @@ -451,7 +470,7 @@ internal static string MediaTypeFormatter_JsonWriterFactoryReturnedNull { return ResourceManager.GetString("MediaTypeFormatter_JsonWriterFactoryReturnedNull", resourceCulture); } } - + /// /// Looks up a localized string similar to The media type formatter of type '{0}' does not support reading because it does not implement the ReadFromStreamAsync method.. /// @@ -460,7 +479,7 @@ internal static string MediaTypeFormatterCannotRead { return ResourceManager.GetString("MediaTypeFormatterCannotRead", resourceCulture); } } - + /// /// Looks up a localized string similar to The media type formatter of type '{0}' does not support reading because it does not implement the ReadFromStream method.. /// @@ -469,7 +488,7 @@ internal static string MediaTypeFormatterCannotReadSync { return ResourceManager.GetString("MediaTypeFormatterCannotReadSync", resourceCulture); } } - + /// /// Looks up a localized string similar to The media type formatter of type '{0}' does not support writing because it does not implement the WriteToStreamAsync method.. /// @@ -478,7 +497,7 @@ internal static string MediaTypeFormatterCannotWrite { return ResourceManager.GetString("MediaTypeFormatterCannotWrite", resourceCulture); } } - + /// /// Looks up a localized string similar to The media type formatter of type '{0}' does not support writing because it does not implement the WriteToStream method.. /// @@ -487,7 +506,7 @@ internal static string MediaTypeFormatterCannotWriteSync { return ResourceManager.GetString("MediaTypeFormatterCannotWriteSync", resourceCulture); } } - + /// /// Looks up a localized string similar to No encoding found for media type formatter '{0}'. There must be at least one supported encoding registered in order for the media type formatter to read or write content.. /// @@ -496,7 +515,7 @@ internal static string MediaTypeFormatterNoEncoding { return ResourceManager.GetString("MediaTypeFormatterNoEncoding", resourceCulture); } } - + /// /// Looks up a localized string similar to MIME multipart boundary cannot end with an empty space.. /// @@ -505,7 +524,7 @@ internal static string MimeMultipartParserBadBoundary { return ResourceManager.GetString("MimeMultipartParserBadBoundary", resourceCulture); } } - + /// /// Looks up a localized string similar to Did not find required '{0}' header field in MIME multipart body part.. /// @@ -514,7 +533,7 @@ internal static string MultipartFormDataStreamProviderNoContentDisposition { return ResourceManager.GetString("MultipartFormDataStreamProviderNoContentDisposition", resourceCulture); } } - + /// /// Looks up a localized string similar to Could not determine a valid local file name for the multipart body part.. /// @@ -523,7 +542,7 @@ internal static string MultipartStreamProviderInvalidLocalFileName { return ResourceManager.GetString("MultipartStreamProviderInvalidLocalFileName", resourceCulture); } } - + /// /// Looks up a localized string similar to Nested bracket is not valid for '{0}' data at position {1}.. /// @@ -532,7 +551,7 @@ internal static string NestedBracketNotValid { return ResourceManager.GetString("NestedBracketNotValid", resourceCulture); } } - + /// /// Looks up a localized string similar to A non-null request URI must be provided to determine if a '{0}' matches a given request or response message.. /// @@ -541,7 +560,7 @@ internal static string NonNullUriRequiredForMediaTypeMapping { return ResourceManager.GetString("NonNullUriRequiredForMediaTypeMapping", resourceCulture); } } - + /// /// Looks up a localized string similar to No MediaTypeFormatter is available to read an object of type '{0}' from content with media type '{1}'.. /// @@ -550,7 +569,34 @@ internal static string NoReadSerializerAvailable { return ResourceManager.GetString("NoReadSerializerAvailable", resourceCulture); } } - + + /// + /// Looks up a localized string similar to Stream does not support reading.. + /// + internal static string NotSupported_UnreadableStream { + get { + return ResourceManager.GetString("NotSupported_UnreadableStream", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stream does not support seeking.. + /// + internal static string NotSupported_UnseekableStream { + get { + return ResourceManager.GetString("NotSupported_UnseekableStream", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stream does not support writing.. + /// + internal static string NotSupported_UnwritableStream { + get { + return ResourceManager.GetString("NotSupported_UnwritableStream", resourceCulture); + } + } + /// /// Looks up a localized string similar to An object of type '{0}' cannot be used with a type parameter of '{1}'.. /// @@ -559,7 +605,7 @@ internal static string ObjectAndTypeDisagree { return ResourceManager.GetString("ObjectAndTypeDisagree", resourceCulture); } } - + /// /// Looks up a localized string similar to The configured formatter '{0}' cannot write an object of type '{1}'.. /// @@ -568,7 +614,16 @@ internal static string ObjectContent_FormatterCannotWriteType { return ResourceManager.GetString("ObjectContent_FormatterCannotWriteType", resourceCulture); } } - + + /// + /// Looks up a localized string similar to Cannot access a closed stream.. + /// + internal static string ObjectDisposed_StreamClosed { + get { + return ResourceManager.GetString("ObjectDisposed_StreamClosed", resourceCulture); + } + } + /// /// Looks up a localized string similar to Query string name cannot be null.. /// @@ -577,7 +632,7 @@ internal static string QueryStringNameShouldNotNull { return ResourceManager.GetString("QueryStringNameShouldNotNull", resourceCulture); } } - + /// /// Looks up a localized string similar to Unexpected end of HTTP message stream. HTTP message is not complete.. /// @@ -586,7 +641,7 @@ internal static string ReadAsHttpMessageUnexpectedTermination { return ResourceManager.GetString("ReadAsHttpMessageUnexpectedTermination", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid '{0}' instance provided. It does not have a '{1}' content-type header with a '{2}' parameter.. /// @@ -595,7 +650,7 @@ internal static string ReadAsMimeMultipartArgumentNoBoundary { return ResourceManager.GetString("ReadAsMimeMultipartArgumentNoBoundary", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid '{0}' instance provided. It does not have a content-type header value. '{0}' instances must have a content-type header starting with '{1}'.. /// @@ -604,7 +659,7 @@ internal static string ReadAsMimeMultipartArgumentNoContentType { return ResourceManager.GetString("ReadAsMimeMultipartArgumentNoContentType", resourceCulture); } } - + /// /// Looks up a localized string similar to Invalid '{0}' instance provided. It does not have a content type header starting with '{1}'.. /// @@ -613,7 +668,7 @@ internal static string ReadAsMimeMultipartArgumentNoMultipart { return ResourceManager.GetString("ReadAsMimeMultipartArgumentNoMultipart", resourceCulture); } } - + /// /// Looks up a localized string similar to Error reading MIME multipart body part.. /// @@ -622,7 +677,7 @@ internal static string ReadAsMimeMultipartErrorReading { return ResourceManager.GetString("ReadAsMimeMultipartErrorReading", resourceCulture); } } - + /// /// Looks up a localized string similar to Error writing MIME multipart body part to output stream.. /// @@ -631,7 +686,7 @@ internal static string ReadAsMimeMultipartErrorWriting { return ResourceManager.GetString("ReadAsMimeMultipartErrorWriting", resourceCulture); } } - + /// /// Looks up a localized string similar to Error parsing MIME multipart body part header byte {0} of data segment {1}.. /// @@ -640,7 +695,7 @@ internal static string ReadAsMimeMultipartHeaderParseError { return ResourceManager.GetString("ReadAsMimeMultipartHeaderParseError", resourceCulture); } } - + /// /// Looks up a localized string similar to Error parsing MIME multipart message byte {0} of data segment {1}.. /// @@ -649,7 +704,7 @@ internal static string ReadAsMimeMultipartParseError { return ResourceManager.GetString("ReadAsMimeMultipartParseError", resourceCulture); } } - + /// /// Looks up a localized string similar to The stream provider of type '{0}' threw an exception.. /// @@ -658,7 +713,7 @@ internal static string ReadAsMimeMultipartStreamProviderException { return ResourceManager.GetString("ReadAsMimeMultipartStreamProviderException", resourceCulture); } } - + /// /// Looks up a localized string similar to The stream provider of type '{0}' returned null. It must return a writable '{1}' instance.. /// @@ -667,7 +722,7 @@ internal static string ReadAsMimeMultipartStreamProviderNull { return ResourceManager.GetString("ReadAsMimeMultipartStreamProviderNull", resourceCulture); } } - + /// /// Looks up a localized string similar to The stream provider of type '{0}' returned a read-only stream. It must return a writable '{1}' instance.. /// @@ -676,7 +731,7 @@ internal static string ReadAsMimeMultipartStreamProviderReadOnly { return ResourceManager.GetString("ReadAsMimeMultipartStreamProviderReadOnly", resourceCulture); } } - + /// /// Looks up a localized string similar to Unexpected end of MIME multipart stream. MIME multipart message is not complete.. /// @@ -685,7 +740,7 @@ internal static string ReadAsMimeMultipartUnexpectedTermination { return ResourceManager.GetString("ReadAsMimeMultipartUnexpectedTermination", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' method in '{1}' returned null. It must return a RemoteStreamResult instance containing a writable stream and a valid URL.. /// @@ -694,7 +749,7 @@ internal static string RemoteStreamInfoCannotBeNull { return ResourceManager.GetString("RemoteStreamInfoCannotBeNull", resourceCulture); } } - + /// /// Looks up a localized string similar to The '{0}' serializer cannot serialize the type '{1}'.. /// @@ -703,7 +758,7 @@ internal static string SerializerCannotSerializeType { return ResourceManager.GetString("SerializerCannotSerializeType", resourceCulture); } } - + /// /// Looks up a localized string similar to There is an unmatched opened bracket for the '{0}' at position {1}.. /// @@ -712,7 +767,7 @@ internal static string UnMatchedBracketNotValid { return ResourceManager.GetString("UnMatchedBracketNotValid", resourceCulture); } } - + /// /// Looks up a localized string similar to Indentation is not supported by '{0}'.. /// @@ -721,7 +776,16 @@ internal static string UnsupportedIndent { return ResourceManager.GetString("UnsupportedIndent", resourceCulture); } } - + + /// + /// Looks up a localized string similar to Unable to validate types on this platform when {0} is 'false'. Please set {0} or move to a supported platform, one where the 'netstandard2.0' assembly is usable.. + /// + internal static string XmlMediaTypeFormatter_DCS_NotSupported { + get { + return ResourceManager.GetString("XmlMediaTypeFormatter_DCS_NotSupported", resourceCulture); + } + } + /// /// Looks up a localized string similar to The object of type '{0}' returned by {1} must be an instance of either XmlObjectSerializer or XmlSerializer.. /// @@ -730,7 +794,7 @@ internal static string XmlMediaTypeFormatter_InvalidSerializerType { return ResourceManager.GetString("XmlMediaTypeFormatter_InvalidSerializerType", resourceCulture); } } - + /// /// Looks up a localized string similar to The object returned by {0} must not be a null value.. /// diff --git a/src/System.Net.Http.Formatting/Properties/Resources.resx b/src/System.Net.Http.Formatting/Properties/Resources.resx index d20156c5a..82d90e68c 100644 --- a/src/System.Net.Http.Formatting/Properties/Resources.resx +++ b/src/System.Net.Http.Formatting/Properties/Resources.resx @@ -1,17 +1,17 @@  - @@ -342,4 +342,25 @@ An attempt was made to move the position before the beginning of the stream. + + Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection. + + + Stream does not support reading. + + + Stream does not support seeking. + + + Stream does not support writing. + + + Cannot access a closed stream. + + + Unable to validate types on this platform when {0} is 'true'. Please reset {0} or move to a supported platform, one where the .NET Standard 2.0 assembly is usable. + + + Unable to validate types on this platform when {0} is 'false'. Please set {0} or move to a supported platform, one where the .NET Standard 2.0 assembly is usable. + \ No newline at end of file diff --git a/src/System.Net.Http.Formatting/PushStreamContent.cs b/src/System.Net.Http.Formatting/PushStreamContent.cs index a8df4f262..8b4a72b3c 100644 --- a/src/System.Net.Http.Formatting/PushStreamContent.cs +++ b/src/System.Net.Http.Formatting/PushStreamContent.cs @@ -14,7 +14,7 @@ namespace System.Net.Http { /// /// Provides an implementation that exposes an output - /// which can be written to directly. The ability to push data to the output stream differs from the + /// which can be written to directly. The ability to push data to the output stream differs from the /// where data is pulled and not pushed. /// public class PushStreamContent : HttpContent @@ -24,8 +24,8 @@ public class PushStreamContent : HttpContent /// /// Initializes a new instance of the class. The /// action is called when an output stream - /// has become available allowing the action to write to it directly. When the - /// stream is closed, it will signal to the content that is has completed and the + /// has become available allowing the action to write to it directly. When the + /// stream is closed, it will signal to the content that it has completed and the /// HTTP request or response will be completed. /// /// The action to call when an output stream is available. @@ -35,10 +35,11 @@ public PushStreamContent(Action onStreamA } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// The action to call when an output stream is available. The stream is automatically - /// closed when the return task is completed. + /// The action to call when an output stream is available. When the + /// output stream is closed or disposed, it will signal to the content that it has completed and the + /// HTTP request or response will be completed. public PushStreamContent(Func onStreamAvailable) : this(onStreamAvailable, (MediaTypeHeaderValue)null) { @@ -47,6 +48,8 @@ public PushStreamContent(Func onStr /// /// Initializes a new instance of the class with the given media type. /// + /// The action to call when an output stream is available. + /// The value of the Content-Type content header on an HTTP response. public PushStreamContent(Action onStreamAvailable, string mediaType) : this(Taskify(onStreamAvailable), new MediaTypeHeaderValue(mediaType)) { @@ -55,6 +58,10 @@ public PushStreamContent(Action onStreamA /// /// Initializes a new instance of the class with the given media type. /// + /// The action to call when an output stream is available. When the + /// output stream is closed or disposed, it will signal to the content that it has completed and the + /// HTTP request or response will be completed. + /// The value of the Content-Type content header on an HTTP response. public PushStreamContent(Func onStreamAvailable, string mediaType) : this(onStreamAvailable, new MediaTypeHeaderValue(mediaType)) { @@ -63,6 +70,8 @@ public PushStreamContent(Func onStr /// /// Initializes a new instance of the class with the given . /// + /// The action to call when an output stream is available. + /// The value of the Content-Type content header on an HTTP response. public PushStreamContent(Action onStreamAvailable, MediaTypeHeaderValue mediaType) : this(Taskify(onStreamAvailable), mediaType) { @@ -71,6 +80,10 @@ public PushStreamContent(Action onStreamA /// /// Initializes a new instance of the class with the given . /// + /// The action to call when an output stream is available. When the + /// output stream is closed or disposed, it will signal to the content that it has completed and the + /// HTTP request or response will be completed. + /// The value of the Content-Type content header on an HTTP response. public PushStreamContent(Func onStreamAvailable, MediaTypeHeaderValue mediaType) { if (onStreamAvailable == null) @@ -98,8 +111,8 @@ private static Func Taskify( } /// - /// When this method is called, it calls the action provided in the constructor with the output - /// stream to write to. Once the action has completed its work it closes the stream which will + /// When this method is called, it calls the action provided in the constructor with the output + /// stream to write to. Once the action has completed its work it closes the stream which will /// close this content instance and complete the HTTP request or response. /// /// The to which to write. @@ -140,10 +153,10 @@ public CompleteTaskOnCloseStream(Stream innerStream, TaskCompletionSource _serializeToStreamTask = serializeToStreamTask; } -#if NETFX_CORE +#if NETSTANDARD1_3 [SuppressMessage( - "Microsoft.Usage", - "CA2215:Dispose methods should call base class dispose", + "Microsoft.Usage", + "CA2215:Dispose methods should call base class dispose", Justification = "See comments, this is intentional.")] protected override void Dispose(bool disposing) { diff --git a/src/System.Net.Http.Formatting/Settings.StyleCop b/src/System.Net.Http.Formatting/Settings.StyleCop deleted file mode 100644 index 5b387864d..000000000 --- a/src/System.Net.Http.Formatting/Settings.StyleCop +++ /dev/null @@ -1,10 +0,0 @@ - - - UriQueryUtility.cs - - - False - - - - \ No newline at end of file diff --git a/src/System.Net.Http.Formatting/System.Net.Http.Formatting.csproj b/src/System.Net.Http.Formatting/System.Net.Http.Formatting.csproj index b520b1052..95ae4c580 100644 --- a/src/System.Net.Http.Formatting/System.Net.Http.Formatting.csproj +++ b/src/System.Net.Http.Formatting/System.Net.Http.Formatting.csproj @@ -10,171 +10,76 @@ $(OutputPath)$(AssemblyName).xml $(CodeAnalysis) ..\Strict.ruleset - $(DefineConstants);ASPNETMVC + $(DefineConstants);ASPNETHTTPFORMATTING Client 1591 - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True + + + ..\..\packages\Newtonsoft.Json.Bson.1.0.3\lib\net45\Newtonsoft.Json.Bson.dll + True + + + + ..\..\packages\System.Buffers.4.5.1\lib\netstandard2.0\System.Buffers.dll False False - + + ..\..\packages\System.Memory.4.5.5\lib\netstandard2.0\System.Memory.dll + False + False + + + ..\..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\netstandard2.0\System.Threading.Tasks.Extensions.dll + False + False + - - - - Properties\CommonAssemblyInfo.cs - - - Common\CollectionExtensions.cs - - - Common\Error.cs - - - Common\ListWrapperCollection.cs - - - Common\TaskHelpers.cs - - - Common\TaskHelpersExtensions.cs - - - Common\UriQueryUtility.cs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + ..\..\packages\NETStandard.Library.2.0.3\lib\netstandard2.0\netstandard.dll + False + False + + + + + + + + - Properties\CommonWebApiResources.Designer.cs True - True CommonWebApiResources.resx + True + Properties\CommonWebApiResources.Designer.cs - - - Properties\CommonWebApiResources.resx ResXFileCodeGenerator CommonWebApiResources.Designer.cs + Properties\CommonWebApiResources.resx - - + + True + Resources.resx + True + ResXFileCodeGenerator Resources.Designer.cs Designer - - - - CodeAnalysisDictionary.xml - - - + diff --git a/src/System.Net.Http.Formatting/UriExtensions.cs b/src/System.Net.Http.Formatting/UriExtensions.cs index ab83ec938..cf531431a 100644 --- a/src/System.Net.Http.Formatting/UriExtensions.cs +++ b/src/System.Net.Http.Formatting/UriExtensions.cs @@ -18,21 +18,12 @@ namespace System.Net.Http [EditorBrowsable(EditorBrowsableState.Never)] public static class UriExtensions { -#if NETFX_CORE - /// - /// Parses the query portion of the specified . - /// - /// The instance from which to read. - /// A containing the parsed result. - public static HttpValueCollection ParseQueryString(this Uri address) -#else /// /// Parses the query portion of the specified . /// /// The instance from which to read. /// A containing the parsed result. public static NameValueCollection ParseQueryString(this Uri address) -#endif { if (address == null) { diff --git a/src/System.Net.Http.Formatting/packages.config b/src/System.Net.Http.Formatting/packages.config index 992a6e6d0..fcc2b6cb5 100644 --- a/src/System.Net.Http.Formatting/packages.config +++ b/src/System.Net.Http.Formatting/packages.config @@ -1,4 +1,9 @@  - + + + + + + \ No newline at end of file diff --git a/src/System.Web.Http.Owin/HttpMessageHandlerAdapter.cs b/src/System.Web.Http.Owin/HttpMessageHandlerAdapter.cs index b8c6fc648..ac118a754 100644 --- a/src/System.Web.Http.Owin/HttpMessageHandlerAdapter.cs +++ b/src/System.Web.Http.Owin/HttpMessageHandlerAdapter.cs @@ -275,7 +275,7 @@ private static async Task CreateBufferedRequestContentAsync(IOwinRe } else { - buffer = new MemoryStream(contentLength.Value); + buffer = new MemoryStream(Math.Min(4 * 1024, contentLength.Value)); } cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/System.Web.Http.Owin/System.Web.Http.Owin.csproj b/src/System.Web.Http.Owin/System.Web.Http.Owin.csproj index 40565650e..a10aaa602 100644 --- a/src/System.Web.Http.Owin/System.Web.Http.Owin.csproj +++ b/src/System.Web.Http.Owin/System.Web.Http.Owin.csproj @@ -13,8 +13,9 @@ $(DefineConstants);ASPNETMVC - - ..\..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll + + ..\..\packages\Microsoft.Owin.4.2.3\lib\net45\Microsoft.Owin.dll + True ..\..\packages\Owin.1.0\lib\net40\Owin.dll diff --git a/src/System.Web.Http.Owin/packages.config b/src/System.Web.Http.Owin/packages.config index 57b34eaa5..af50e4ce0 100644 --- a/src/System.Web.Http.Owin/packages.config +++ b/src/System.Web.Http.Owin/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/src/System.Web.Http.SignalR/System.Web.Http.SignalR.csproj b/src/System.Web.Http.SignalR/System.Web.Http.SignalR.csproj index 1a31642ae..2ced546df 100644 --- a/src/System.Web.Http.SignalR/System.Web.Http.SignalR.csproj +++ b/src/System.Web.Http.SignalR/System.Web.Http.SignalR.csproj @@ -13,13 +13,13 @@ $(DefineConstants);ASPNETMVC - - ..\..\packages\Microsoft.AspNet.SignalR.Core.1.0.0\lib\net40\Microsoft.AspNet.SignalR.Core.dll + + ..\..\packages\Microsoft.AspNet.SignalR.Core.1.2.2\lib\net40\Microsoft.AspNet.SignalR.Core.dll + True - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - False - False + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True diff --git a/src/System.Web.Http.SignalR/packages.config b/src/System.Web.Http.SignalR/packages.config index 6342f7fc0..05b2576e6 100644 --- a/src/System.Web.Http.SignalR/packages.config +++ b/src/System.Web.Http.SignalR/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/src/System.Web.Http.Tracing/System.Web.Http.Tracing.csproj b/src/System.Web.Http.Tracing/System.Web.Http.Tracing.csproj index a0f9b09a5..b7d28c34f 100644 --- a/src/System.Web.Http.Tracing/System.Web.Http.Tracing.csproj +++ b/src/System.Web.Http.Tracing/System.Web.Http.Tracing.csproj @@ -13,10 +13,9 @@ $(DefineConstants);ASPNETMVC - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - False - False + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True diff --git a/src/System.Web.Http.Tracing/packages.config b/src/System.Web.Http.Tracing/packages.config index 992a6e6d0..c78bfcde2 100644 --- a/src/System.Web.Http.Tracing/packages.config +++ b/src/System.Web.Http.Tracing/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/System.Web.Http/ModelBinding/ErrorParameterBinding.cs b/src/System.Web.Http/ModelBinding/ErrorParameterBinding.cs index 05334819d..57b9c0b77 100644 --- a/src/System.Web.Http/ModelBinding/ErrorParameterBinding.cs +++ b/src/System.Web.Http/ModelBinding/ErrorParameterBinding.cs @@ -20,7 +20,7 @@ public ErrorParameterBinding(HttpParameterDescriptor descriptor, string message) { if (message == null) { - throw Error.ArgumentNull(message); + throw Error.ArgumentNull("message"); } _message = message; } @@ -36,7 +36,7 @@ public override string ErrorMessage public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) { // Caller should have already checked IsError before executing, so we shoulnd't be here. - return TaskHelpers.FromError(new InvalidOperationException()); + return TaskHelpers.FromError(new InvalidOperationException()); } } } diff --git a/src/System.Web.Http/Settings.StyleCop b/src/System.Web.Http/Settings.StyleCop deleted file mode 100644 index ddf8ec764..000000000 --- a/src/System.Web.Http/Settings.StyleCop +++ /dev/null @@ -1,11 +0,0 @@ - - - DynamicQueryable.cs - UriQueryUtility.cs - - - False - - - - \ No newline at end of file diff --git a/src/System.Web.Http/System.Web.Http.csproj b/src/System.Web.Http/System.Web.Http.csproj index 2df7c494b..11d333042 100644 --- a/src/System.Web.Http/System.Web.Http.csproj +++ b/src/System.Web.Http/System.Web.Http.csproj @@ -14,10 +14,9 @@ 1591 - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - False - False + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True @@ -102,9 +101,6 @@ Common\TypeExtensions.cs - - Common\UriQueryUtility.cs - diff --git a/src/System.Web.Http/packages.config b/src/System.Web.Http/packages.config index 992a6e6d0..c78bfcde2 100644 --- a/src/System.Web.Http/packages.config +++ b/src/System.Web.Http/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/System.Web.Mvc/JavaScript/jquery.unobtrusive-ajax.js b/src/System.Web.Mvc/JavaScript/jquery.unobtrusive-ajax.js index 378686e78..3fbaccd5d 100644 --- a/src/System.Web.Mvc/JavaScript/jquery.unobtrusive-ajax.js +++ b/src/System.Web.Mvc/JavaScript/jquery.unobtrusive-ajax.js @@ -42,19 +42,21 @@ mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase(); $(element.getAttribute("data-ajax-update")).each(function (i, update) { + var top; + switch (mode) { - case "BEFORE": - $(update).prepend(data); - break; - case "AFTER": - $(update).append(data); - break; - case "REPLACE-WITH": - $(update).replaceWith(data); - break; - default: - $(update).html(data); - break; + case "BEFORE": + $(update).prepend(data); + break; + case "AFTER": + $(update).append(data); + break; + case "REPLACE-WITH": + $(update).replaceWith(data); + break; + default: + $(update).html(data); + break; } }); } @@ -73,7 +75,7 @@ $.extend(options, { type: element.getAttribute("data-ajax-method") || undefined, url: element.getAttribute("data-ajax-url") || undefined, - cache: !!element.getAttribute("data-ajax-cache"), + cache: (element.getAttribute("data-ajax-cache") || "").toLowerCase() === "true", beforeSend: function (xhr) { var result; asyncOnBeforeSend(xhr, method); @@ -104,6 +106,30 @@ options.data.push({ name: "X-HTTP-Method-Override", value: method }); } + // change here: + // Check for a Form POST with enctype=multipart/form-data + // add the input file that were not previously included in the serializeArray() + // set processData and contentType to false + var $element = $(element); + if ($element.is("form") && $element.attr("enctype") == "multipart/form-data") { + var formdata = new FormData(); + $.each(options.data, function (i, v) { + formdata.append(v.name, v.value); + }); + $("input[type=file]", $element).each(function () { + var file = this; + $.each(file.files, function (n, v) { + formdata.append(file.name, v); + }); + }); + $.extend(options, { + processData: false, + contentType: false, + data: formdata + }); + } + // end change + $.ajax(options); } @@ -154,7 +180,7 @@ $(document).on("submit", "form[data-ajax=true]", function (evt) { var clickInfo = $(this).data(data_click) || [], clickTarget = $(this).data(data_target), - isCancel = clickTarget && clickTarget.hasClass("cancel"); + isCancel = clickTarget && (clickTarget.hasClass("cancel") || clickTarget.attr('formnovalidate') !== undefined); evt.preventDefault(); if (!isCancel && !validate(this)) { return; diff --git a/src/System.Web.WebPages.Administration/Framework/packages/WebProjectManager.cs b/src/System.Web.WebPages.Administration/Framework/packages/WebProjectManager.cs index 1b19fa69a..669ccad68 100644 --- a/src/System.Web.WebPages.Administration/Framework/packages/WebProjectManager.cs +++ b/src/System.Web.WebPages.Administration/Framework/packages/WebProjectManager.cs @@ -94,7 +94,7 @@ public IEnumerable GetPackagesWithUpdates(string searchTerms, bool fil { packagesToUpdate = packagesToUpdate.Where(p => !String.IsNullOrEmpty(p.Tags) && p.Tags.ToLower().Contains(WebPagesPreferredTag)); } - return SourceRepository.GetUpdates(packagesToUpdate, includePrerelease: false).AsQueryable(); + return SourceRepository.GetUpdates(packagesToUpdate, includePrerelease: false, includeAllVersions: false).AsQueryable(); } internal IEnumerable InstallPackage(IPackage package) @@ -154,7 +154,7 @@ public bool IsPackageInstalled(IPackage package) public IPackage GetUpdate(IPackage package) { - return SourceRepository.GetUpdates(new[] { package }, includePrerelease: false).SingleOrDefault(); + return SourceRepository.GetUpdates(new[] { package }, includePrerelease: false, includeAllVersions: false).SingleOrDefault(); } private void AddBindingRedirects(AppDomain appDomain) @@ -168,7 +168,7 @@ private void AddBindingRedirects(AppDomain appDomain) var assemblies = RemoteAssembly.GetAssembliesForBindingRedirect(appDomain, binDirectory); var bindingRedirects = BindingRedirectResolver.GetBindingRedirects(assemblies); - if (bindingRedirects.Any()) + if (Enumerable.Any(bindingRedirects)) { // NuGet ends up reading our web.config file regardless of if any bindingRedirects are needed. var bindingRedirectManager = new BindingRedirectManager(_projectManager.Project, "web.config"); @@ -200,7 +200,7 @@ public static IEnumerable CollapseVersions(IQueryable packag const int BufferSize = 30; return packages.Where(package => package.IsLatestVersion) .AsBufferedEnumerable(BufferSize) - .DistinctLast(PackageEqualityComparer.Id, PackageComparer.Version); + .AsCollapsed(); } internal IEnumerable GetPackagesRequiringLicenseAcceptance(IPackage package) diff --git a/src/System.Web.WebPages.Administration/Framework/packages/WebProjectSystem.cs b/src/System.Web.WebPages.Administration/Framework/packages/WebProjectSystem.cs index 2b59e92a5..2876683c4 100644 --- a/src/System.Web.WebPages.Administration/Framework/packages/WebProjectSystem.cs +++ b/src/System.Web.WebPages.Administration/Framework/packages/WebProjectSystem.cs @@ -40,6 +40,14 @@ public FrameworkName TargetFramework get { return VersionUtility.DefaultTargetFramework; } } + /// + /// Gets a value indicating whether assembly binding redirects are supported. + /// + public bool IsBindingRedirectSupported + { + get { return true; } + } + public void AddReference(string referencePath, Stream stream) { // Copy to bin by default @@ -82,7 +90,7 @@ public void RemoveReference(string name) DeleteFile(GetReferencePath(name)); // Delete the bin directory if this was the last reference - if (!GetFiles(BinDir).Any()) + if (!Enumerable.Any(GetFiles(BinDir, recursive: false))) { DeleteDirectory(BinDir); } @@ -172,11 +180,12 @@ internal static void AddReferencesToConfig(IFileSystem fileSystem, string refere // Get the name of the existing references // References are stored in the format - bool existingAssembly = (from item in assemblies.Elements() - where !String.IsNullOrEmpty(item.GetOptionalAttributeValue("assembly")) - let assemblyName = new AssemblyName(item.Attribute("assembly").Value).Name - where String.Equals(assemblyName, references, StringComparison.OrdinalIgnoreCase) - select item).Any(); + bool existingAssembly = Enumerable.Any( + from item in assemblies.Elements() + where !String.IsNullOrEmpty(item.GetOptionalAttributeValue("assembly")) + let assemblyName = new AssemblyName(item.Attribute("assembly").Value).Name + where String.Equals(assemblyName, references, StringComparison.OrdinalIgnoreCase) + select item); if (!existingAssembly) { diff --git a/src/System.Web.WebPages.Administration/System.Web.WebPages.Administration.csproj b/src/System.Web.WebPages.Administration/System.Web.WebPages.Administration.csproj index 7854b177c..dc1393420 100644 --- a/src/System.Web.WebPages.Administration/System.Web.WebPages.Administration.csproj +++ b/src/System.Web.WebPages.Administration/System.Web.WebPages.Administration.csproj @@ -14,9 +14,9 @@ 1591 - + + ..\..\packages\NuGet.Core.1.8.0\lib\net40-Client\NuGet.Core.dll True - ..\..\packages\Nuget.Core.1.6.2\lib\net40\NuGet.Core.dll @@ -66,6 +66,7 @@ + @@ -169,7 +170,12 @@ - - + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}. + + + \ No newline at end of file diff --git a/src/System.Web.WebPages.Administration/packages.config b/src/System.Web.WebPages.Administration/packages.config index fa456c98a..8d62cfb49 100644 --- a/src/System.Web.WebPages.Administration/packages.config +++ b/src/System.Web.WebPages.Administration/packages.config @@ -1,5 +1,5 @@  - - + + \ No newline at end of file diff --git a/src/System.Web.WebPages.Administration/packages/Default.cshtml b/src/System.Web.WebPages.Administration/packages/Default.cshtml index 1c901a369..9ce522254 100644 --- a/src/System.Web.WebPages.Administration/packages/Default.cshtml +++ b/src/System.Web.WebPages.Administration/packages/Default.cshtml @@ -132,7 +132,7 @@ return; } -@if (!grid.Rows.Any()) { +@if (!Enumerable.Any(grid.Rows)) {

@PackageManagerResources.NoPackagesFound

} else { diff --git a/src/System.Web.WebPages.Administration/packages/Install.cshtml b/src/System.Web.WebPages.Administration/packages/Install.cshtml index 028f70750..3d80dbbab 100644 --- a/src/System.Web.WebPages.Administration/packages/Install.cshtml +++ b/src/System.Web.WebPages.Administration/packages/Install.cshtml @@ -57,7 +57,7 @@ @{ var licensePackages = projectManager.GetPackagesRequiringLicenseAcceptance(package); - if (licensePackages.Any()) { + if (Enumerable.Any(licensePackages)) {
    @foreach(var licensePackage in licensePackages.Where(p => PageUtils.IsValidLicenseUrl(p.LicenseUrl))){ diff --git a/src/System.Web.WebPages.Administration/packages/Uninstall.cshtml b/src/System.Web.WebPages.Administration/packages/Uninstall.cshtml index 44a2a9924..b2b31ae06 100644 --- a/src/System.Web.WebPages.Administration/packages/Uninstall.cshtml +++ b/src/System.Web.WebPages.Administration/packages/Uninstall.cshtml @@ -61,7 +61,7 @@ @AntiForgery.GetHtml() - @if (package.Dependencies.Any()) { + @if (Enumerable.Any(package.Dependencies)) {
    diff --git a/src/System.Web.WebPages.Administration/packages/_PackageDetails.cshtml b/src/System.Web.WebPages.Administration/packages/_PackageDetails.cshtml index 870269e82..2c5854d68 100644 --- a/src/System.Web.WebPages.Administration/packages/_PackageDetails.cshtml +++ b/src/System.Web.WebPages.Administration/packages/_PackageDetails.cshtml @@ -14,7 +14,7 @@ } @{ var authors = package.Authors as IEnumerable; - if (authors.Any()) { + if (Enumerable.Any(authors)) {

    @PackageManagerResources.AuthorsLabel: @String.Join(PackageManagerResources.WordSeparator, authors)

    diff --git a/src/System.Web.WebPages.Administration/razorgenerator.directives b/src/System.Web.WebPages.Administration/razorgenerator.directives new file mode 100644 index 000000000..2421be975 --- /dev/null +++ b/src/System.Web.WebPages.Administration/razorgenerator.directives @@ -0,0 +1 @@ +GeneratePrettyNames: true diff --git a/src/WebApiHelpPage/Areas/HelpPage/Views/Web.config b/src/WebApiHelpPage/Areas/HelpPage/Views/Web.config index 820e75486..198766754 100644 --- a/src/WebApiHelpPage/Areas/HelpPage/Views/Web.config +++ b/src/WebApiHelpPage/Areas/HelpPage/Views/Web.config @@ -9,7 +9,7 @@ - + @@ -34,8 +34,17 @@ - + + + + + + + + + + diff --git a/src/WebApiHelpPage/VB/Areas/HelpPage/Views/Web.config b/src/WebApiHelpPage/VB/Areas/HelpPage/Views/Web.config index 9a921ab54..043fbd6e2 100644 --- a/src/WebApiHelpPage/VB/Areas/HelpPage/Views/Web.config +++ b/src/WebApiHelpPage/VB/Areas/HelpPage/Views/Web.config @@ -9,7 +9,7 @@ - + @@ -34,8 +34,17 @@ - + + + + + + + + + + diff --git a/src/WebApiHelpPage/VB/WebApiHelpPage.VB.nuspec b/src/WebApiHelpPage/VB/WebApiHelpPage.VB.nuspec index 6715ceca9..3d98bbab6 100644 --- a/src/WebApiHelpPage/VB/WebApiHelpPage.VB.nuspec +++ b/src/WebApiHelpPage/VB/WebApiHelpPage.VB.nuspec @@ -2,20 +2,18 @@ Microsoft.AspNet.WebApi.HelpPage.VB - 5.1.0-alpha-0 + 5.3.1 Microsoft ASP.NET Web API Help Page (VB) Microsoft Microsoft http://www.asp.net/web-api - true - http://www.microsoft.com/web/webpi/eula/mvc4extensions_prerelease_eula.htm The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site. Visitors to your help page can use this content to learn how to call your web APIs. Everything generated by the help page is fully customizable using ASP.NET MVC and Razor. ASP.NET Web API Help Page is a great addition to any ASP.NET Web API project. The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site. - - - + + + diff --git a/src/WebApiHelpPage/VB/WebApiHelpPageVB.vbproj b/src/WebApiHelpPage/VB/WebApiHelpPageVB.vbproj index 5c1d45882..37e7cd7b9 100644 --- a/src/WebApiHelpPage/VB/WebApiHelpPageVB.vbproj +++ b/src/WebApiHelpPage/VB/WebApiHelpPageVB.vbproj @@ -42,10 +42,9 @@ On - - ..\..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - False - False + + ..\..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True diff --git a/src/WebApiHelpPage/VB/packages.config b/src/WebApiHelpPage/VB/packages.config index 3cb4a4570..de4ec4118 100644 --- a/src/WebApiHelpPage/VB/packages.config +++ b/src/WebApiHelpPage/VB/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/src/WebApiHelpPage/WebApiHelpPage.csproj b/src/WebApiHelpPage/WebApiHelpPage.csproj index 15964d7c8..4f63ac32f 100644 --- a/src/WebApiHelpPage/WebApiHelpPage.csproj +++ b/src/WebApiHelpPage/WebApiHelpPage.csproj @@ -15,10 +15,9 @@ 1591 - - ..\..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - False - False + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True diff --git a/src/WebApiHelpPage/WebApiHelpPage.nuspec b/src/WebApiHelpPage/WebApiHelpPage.nuspec index aa69da71f..6e0f62121 100644 --- a/src/WebApiHelpPage/WebApiHelpPage.nuspec +++ b/src/WebApiHelpPage/WebApiHelpPage.nuspec @@ -2,27 +2,25 @@ Microsoft.AspNet.WebApi.HelpPage - 5.1.0-alpha-0 + 5.3.1 Microsoft ASP.NET Web API Help Page Microsoft Microsoft http://www.asp.net/web-api - true - http://www.microsoft.com/web/webpi/eula/mvc4extensions_prerelease_eula.htm The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site. Visitors to your help page can use this content to learn how to call your web APIs. Everything generated by the help page is fully customizable using ASP.NET MVC and Razor. ASP.NET Web API Help Page is a great addition to any ASP.NET Web API project. The ASP.NET Web API Help Page automatically generates help page content for the web APIs on your site. - - - + + + en-US - Microsoft AspNet WebApi AspNetWebApi HelpPage + Microsoft AspNet WebApi AspNetWebApi HelpPage diff --git a/src/WebApiHelpPage/packages.config b/src/WebApiHelpPage/packages.config index 96befa888..9e4c69487 100644 --- a/src/WebApiHelpPage/packages.config +++ b/src/WebApiHelpPage/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/test/Common/UriQueryUtilityTest.cs b/test/Common/UriQueryUtilityTest.cs index 4b325abbd..ac0307cae 100644 --- a/test/Common/UriQueryUtilityTest.cs +++ b/test/Common/UriQueryUtilityTest.cs @@ -10,7 +10,7 @@ namespace System.Net.Http { - public class UriQueryUtilityTest + public class WebUtilityTest { public static TheoryDataSet UriQueryData { @@ -23,19 +23,20 @@ public static TheoryDataSet UriQueryData [Fact] public void TypeIsCorrect() { - Assert.Type.HasProperties(typeof(UriQueryUtility), TypeAssert.TypeProperties.IsClass | TypeAssert.TypeProperties.IsStatic); + Assert.Type.HasProperties(typeof(WebUtility), + TypeAssert.TypeProperties.IsStatic | TypeAssert.TypeProperties.IsPublicVisibleClass); } [Fact] public void UrlEncode_ReturnsNull() { - Assert.Null(UriQueryUtility.UrlEncode(null)); + Assert.Null(WebUtility.UrlEncode(null)); } [Fact] public void UrlDecode_ReturnsNull() { - Assert.Null(UriQueryUtility.UrlDecode(null)); + Assert.Null(WebUtility.UrlDecode(null)); } [Fact] diff --git a/test/Directory.Build.props b/test/Directory.Build.props index 8dc298fd2..c55ba298d 100644 --- a/test/Directory.Build.props +++ b/test/Directory.Build.props @@ -4,6 +4,9 @@ false true - v4.5.2 + v4.6.2 diff --git a/test/Directory.Build.targets b/test/Directory.Build.targets index 72087f737..99772c023 100644 --- a/test/Directory.Build.targets +++ b/test/Directory.Build.targets @@ -1,6 +1,7 @@ - + diff --git a/test/Microsoft.AspNet.Facebook.Test/App.config b/test/Microsoft.AspNet.Facebook.Test/App.config index eef865c03..5fd3a3014 100644 --- a/test/Microsoft.AspNet.Facebook.Test/App.config +++ b/test/Microsoft.AspNet.Facebook.Test/App.config @@ -1,13 +1,5 @@  - - - - - - - - @@ -16,4 +8,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/Microsoft.AspNet.Facebook.Test/Microsoft.AspNet.Facebook.Test.csproj b/test/Microsoft.AspNet.Facebook.Test/Microsoft.AspNet.Facebook.Test.csproj index 9bb06e0b4..63480c922 100644 --- a/test/Microsoft.AspNet.Facebook.Test/Microsoft.AspNet.Facebook.Test.csproj +++ b/test/Microsoft.AspNet.Facebook.Test/Microsoft.AspNet.Facebook.Test.csproj @@ -1,7 +1,7 @@  - - + + {C3BEF382-C7C4-454D-B017-1EAC03E9A82C} @@ -14,41 +14,50 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Facebook.6.4.2\lib\net45\Facebook.dll + + ..\..\packages\Facebook.6.8.0\lib\net45\Facebook.dll + True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -129,23 +138,23 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - - + \ No newline at end of file diff --git a/test/Microsoft.AspNet.Facebook.Test/packages.config b/test/Microsoft.AspNet.Facebook.Test/packages.config index 92ea6b4cd..fdf33da32 100644 --- a/test/Microsoft.AspNet.Facebook.Test/packages.config +++ b/test/Microsoft.AspNet.Facebook.Test/packages.config @@ -1,15 +1,17 @@  - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/Microsoft.TestCommon/AppDomainUtils.cs b/test/Microsoft.TestCommon/AppDomainUtils.cs index 58d7befb8..391f45b35 100644 --- a/test/Microsoft.TestCommon/AppDomainUtils.cs +++ b/test/Microsoft.TestCommon/AppDomainUtils.cs @@ -14,7 +14,10 @@ public static class AppDomainUtils // other tests will not be affected. public static void RunInSeparateAppDomain(Action action) { - RunInSeparateAppDomain(new AppDomainSetup(), action); + RunInSeparateAppDomain(new AppDomainSetup + { + ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile + }, action); } public static void RunInSeparateAppDomain(AppDomainSetup setup, Action action) diff --git a/test/Microsoft.TestCommon/Directory.Build.props b/test/Microsoft.TestCommon/Directory.Build.props new file mode 100644 index 000000000..1c94e6e8e --- /dev/null +++ b/test/Microsoft.TestCommon/Directory.Build.props @@ -0,0 +1,9 @@ + + + + + + obj\ns1_3\ + $(DefaultItemExcludes);obj\** + + diff --git a/test/Microsoft.TestCommon/ExceptionAssertions.cs b/test/Microsoft.TestCommon/ExceptionAssertions.cs index 1d21f04f0..39b6df95e 100644 --- a/test/Microsoft.TestCommon/ExceptionAssertions.cs +++ b/test/Microsoft.TestCommon/ExceptionAssertions.cs @@ -6,6 +6,9 @@ using System.Reflection; using System.Threading.Tasks; using System.Web; +#if Testing_NetStandard1_3 +using System.Web.Http; +#endif namespace Microsoft.TestCommon { @@ -294,7 +297,7 @@ public static async Task ThrowsArgumentNullAsync(FuncThrown when an exception was not thrown, or when an exception of the incorrect type is thrown public static ArgumentException ThrowsArgumentNullOrEmpty(Action testCode, string paramName) { - return Throws(testCode, "Value cannot be null or empty.\r\nParameter name: " + paramName, allowDerivedExceptions: false); + return Throws(testCode, "Value cannot be null or empty." + GetParameterMessage(paramName), allowDerivedExceptions: false); } /// @@ -324,7 +327,7 @@ public static ArgumentOutOfRangeException ThrowsArgumentOutOfRange(Action testCo { if (exceptionMessage != null) { - exceptionMessage = exceptionMessage + "\r\nParameter name: " + paramName; + exceptionMessage = exceptionMessage + GetParameterMessage(paramName); if (actualValue != null) { exceptionMessage += String.Format(CultureReplacer.DefaultCulture, "\r\nActual value was {0}.", actualValue); @@ -357,7 +360,7 @@ public static async Task ThrowsArgumentOutOfRangeAs { if (exceptionMessage != null) { - exceptionMessage = exceptionMessage + "\r\nParameter name: " + paramName; + exceptionMessage = exceptionMessage + GetParameterMessage(paramName); if (actualValue != null) { exceptionMessage += String.Format(CultureReplacer.DefaultCulture, "\r\nActual value was {0}.", actualValue); @@ -466,6 +469,7 @@ public static ArgumentOutOfRangeException ThrowsArgumentLessThanOrEqualTo(Action String.Format(CultureReplacer.DefaultCulture, "Value must be less than or equal to {0}.", maxValue), false, actualValue); } +#if !NETCOREAPP /// /// Verifies that the code throws an HttpException (or optionally any exception which derives from it). /// @@ -481,6 +485,7 @@ public static HttpException ThrowsHttpException(Action testCode, string exceptio Equal(httpCode, ex.GetHttpCode()); return ex; } +#endif /// /// Verifies that the code throws an InvalidEnumArgumentException (or optionally any exception which derives from it). @@ -492,12 +497,17 @@ public static HttpException ThrowsHttpException(Action testCode, string exceptio /// Pass true to allow exceptions which derive from TException; pass false, otherwise /// The exception that was thrown, when successful /// Thrown when an exception was not thrown, or when an exception of the incorrect type is thrown - public static InvalidEnumArgumentException ThrowsInvalidEnumArgument(Action testCode, string paramName, int invalidValue, Type enumType, bool allowDerivedExceptions = false) + public static ArgumentException ThrowsInvalidEnumArgument(Action testCode, string paramName, int invalidValue, Type enumType, bool allowDerivedExceptions = false) { string message = String.Format(CultureReplacer.DefaultCulture, - "The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.{3}Parameter name: {0}", - paramName, invalidValue, enumType.Name, Environment.NewLine); + "The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.{3}", + paramName, invalidValue, enumType.Name, GetParameterMessage(paramName)); + +#if Testing_NetStandard1_3 // InvalidEnumArgumentException not available in netstandard1.3. + return Throws(testCode, message, allowDerivedExceptions); +#else return Throws(testCode, message, allowDerivedExceptions); +#endif } /// @@ -571,6 +581,15 @@ public static async Task ThrowsAsync( return ex; } + private static string GetParameterMessage(string parameterName) + { +#if NETCOREAPP3_1_OR_GREATER + return " (Parameter '" + parameterName + "')"; +#else + return Environment.NewLine + "Parameter name: " + parameterName; +#endif + } + // We've re-implemented all the xUnit.net Throws code so that we can get this // updated implementation of RecordException which silently unwraps any instances // of AggregateException. In addition to unwrapping exceptions, this method ensures @@ -633,17 +652,26 @@ private static void VerifyExceptionMessage(Exception exception, string expectedM // Custom ThrowsException so we can filter the stack trace. [Serializable] - private class ThrowsException : Xunit.Sdk.ThrowsException + private class ThrowsException : Xunit.Sdk.XunitException { - public ThrowsException(Type type) : base(type) { } + private readonly string _stackTrace; - public ThrowsException(Type type, Exception ex) : base(type, ex) { } + public ThrowsException(Type type) + : base(Xunit.Sdk.ThrowsException.ForNoException(type).Message) + { + } + + public ThrowsException(Type type, Exception ex) + : base(Xunit.Sdk.ThrowsException.ForIncorrectExceptionType(type, ex).Message, ex) + { + _stackTrace = ex.StackTrace; + } public override string StackTrace { get { - return ExceptionUtility.FilterStackTrace(base.StackTrace); + return ExceptionUtility.FilterStackTrace(_stackTrace ?? base.StackTrace); } } } diff --git a/test/Microsoft.TestCommon/FactDiscoverer.cs b/test/Microsoft.TestCommon/FactDiscoverer.cs index db913e188..4be650293 100644 --- a/test/Microsoft.TestCommon/FactDiscoverer.cs +++ b/test/Microsoft.TestCommon/FactDiscoverer.cs @@ -76,6 +76,7 @@ public override IEnumerable Discover( var testCase = new SkippedXunitTestCase( _diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), + TestMethodDisplayOptions.None, skipReason, baseCase.TestMethod, baseCase.TestMethodArguments); diff --git a/test/Microsoft.TestCommon/Microsoft.TestCommon.csproj b/test/Microsoft.TestCommon/Microsoft.TestCommon.csproj index 73887c60e..8ac17597f 100644 --- a/test/Microsoft.TestCommon/Microsoft.TestCommon.csproj +++ b/test/Microsoft.TestCommon/Microsoft.TestCommon.csproj @@ -1,128 +1,39 @@ - - + - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0} - Library - Properties - Microsoft.TestCommon - Microsoft.TestCommon - false + net462;netcoreapp2.1;net8.0 + $(Configurations);CodeAnalysis + $(DefineConstants);Testing_NetStandard1_3 + false ..\..\bin\$(Configuration)\Test\ - false - false - true - false + $(OutputPath)ns1_3\ + - - - - - - - - - - - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll - True - - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll - True - - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll - True - - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll - True - + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - Code - - - - - - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - - - - - - - - - - \ No newline at end of file + diff --git a/test/Microsoft.TestCommon/PlatformInfo.cs b/test/Microsoft.TestCommon/PlatformInfo.cs index 678ecff08..e3026e39e 100644 --- a/test/Microsoft.TestCommon/PlatformInfo.cs +++ b/test/Microsoft.TestCommon/PlatformInfo.cs @@ -26,7 +26,7 @@ private static Platform GetPlatform() { if (Type.GetType(_netCore20TypeName, throwOnError: false) != null) { - // Treat .NET Core 2.0 as a .NET 4.5 superset though internal types are different. + // Treat .NET Core 2.1 as a .NET 4.5 superset though internal types are different. return Platform.Net45; } diff --git a/test/Microsoft.TestCommon/PortReserver.cs b/test/Microsoft.TestCommon/PortReserver.cs index f085399af..f71a51e6c 100644 --- a/test/Microsoft.TestCommon/PortReserver.cs +++ b/test/Microsoft.TestCommon/PortReserver.cs @@ -12,6 +12,11 @@ namespace Microsoft.TestCommon { + [Xunit.CollectionDefinition("PortReserver Collection", DisableParallelization = true)] + public class PortReserverCollection + { + } + /// /// This class allocates ports while ensuring that: /// 1. Ports that are permanently taken (or taken for the duration of the test) are not being attempted to be used. @@ -36,7 +41,7 @@ public int PortNumber private set; } - public PortReserver(int basePort = 50231) + public PortReserver(int basePort = 60231) { if (basePort <= 0) { diff --git a/test/Microsoft.TestCommon/SkippedXunitTestCase.cs b/test/Microsoft.TestCommon/SkippedXunitTestCase.cs index e055b1e67..b5d536d3a 100644 --- a/test/Microsoft.TestCommon/SkippedXunitTestCase.cs +++ b/test/Microsoft.TestCommon/SkippedXunitTestCase.cs @@ -29,10 +29,11 @@ public class SkippedXunitTestCase : XunitTestCase public SkippedXunitTestCase( IMessageSink diagnosticMessageSink, TestMethodDisplay defaultMethodDisplay, + TestMethodDisplayOptions defaultMethodDisplayOptions, String skipReason, ITestMethod testMethod, object[] testMethodArguments = null) - : base(diagnosticMessageSink, defaultMethodDisplay, testMethod, testMethodArguments) + : base(diagnosticMessageSink, defaultMethodDisplay, defaultMethodDisplayOptions, testMethod, testMethodArguments) { _skipReason = skipReason; } diff --git a/test/Microsoft.TestCommon/TheoryDiscoverer.cs b/test/Microsoft.TestCommon/TheoryDiscoverer.cs index 8ca4c834e..cf62536fe 100644 --- a/test/Microsoft.TestCommon/TheoryDiscoverer.cs +++ b/test/Microsoft.TestCommon/TheoryDiscoverer.cs @@ -77,6 +77,7 @@ public override IEnumerable Discover( var testCase = new SkippedXunitTestCase( _diagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(), + TestMethodDisplayOptions.None, skipReason, baseCase.TestMethod, baseCase.TestMethodArguments); diff --git a/test/Microsoft.TestCommon/packages.config b/test/Microsoft.TestCommon/packages.config deleted file mode 100644 index d6bfcf037..000000000 --- a/test/Microsoft.TestCommon/packages.config +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/test/Microsoft.Web.Helpers.Test/Microsoft.Web.Helpers.Test.csproj b/test/Microsoft.Web.Helpers.Test/Microsoft.Web.Helpers.Test.csproj index ca98914c7..b1b8a1b3e 100644 --- a/test/Microsoft.Web.Helpers.Test/Microsoft.Web.Helpers.Test.csproj +++ b/test/Microsoft.Web.Helpers.Test/Microsoft.Web.Helpers.Test.csproj @@ -1,7 +1,7 @@  - - + + {2C653A66-8159-4A41-954F-A67915DFDA87} @@ -14,31 +14,40 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll + True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -93,16 +102,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/Microsoft.Web.Helpers.Test/packages.config b/test/Microsoft.Web.Helpers.Test/packages.config index b06fb5e7a..842db1984 100644 --- a/test/Microsoft.Web.Helpers.Test/packages.config +++ b/test/Microsoft.Web.Helpers.Test/packages.config @@ -1,13 +1,15 @@  - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/test/Microsoft.Web.Mvc.Test/Microsoft.Web.Mvc.Test.csproj b/test/Microsoft.Web.Mvc.Test/Microsoft.Web.Mvc.Test.csproj index a02c92522..81408d1f1 100644 --- a/test/Microsoft.Web.Mvc.Test/Microsoft.Web.Mvc.Test.csproj +++ b/test/Microsoft.Web.Mvc.Test/Microsoft.Web.Mvc.Test.csproj @@ -1,7 +1,7 @@  - - + + {6C28DA70-60F1-4442-967F-591BF3962EC5} @@ -16,40 +16,49 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -153,23 +162,22 @@ - - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/Microsoft.Web.Mvc.Test/Test/AsyncManagerExtensionsTest.cs b/test/Microsoft.Web.Mvc.Test/Test/AsyncManagerExtensionsTest.cs index da31d4f16..a37fc7c85 100644 --- a/test/Microsoft.Web.Mvc.Test/Test/AsyncManagerExtensionsTest.cs +++ b/test/Microsoft.Web.Mvc.Test/Test/AsyncManagerExtensionsTest.cs @@ -89,7 +89,7 @@ public void RegisterTask_ResetsOutstandingOperationCountIfBeginMethodThrows() AsyncManager asyncManager = new AsyncManager(syncContext); Func beginDelegate = cb => { throw new InvalidOperationException("BeginDelegate throws."); }; - Action endDelegate = ar => { Assert.True(false, "This should never be called."); }; + Action endDelegate = ar => { Assert.Fail("This should never be called."); }; // Act & assert Assert.Throws( diff --git a/test/Microsoft.Web.Mvc.Test/Test/VersionTest.cs b/test/Microsoft.Web.Mvc.Test/Test/VersionTest.cs index 155f13f2f..834dbe4ab 100644 --- a/test/Microsoft.Web.Mvc.Test/Test/VersionTest.cs +++ b/test/Microsoft.Web.Mvc.Test/Test/VersionTest.cs @@ -13,7 +13,7 @@ public class VersionTest public void VerifyMVCVersionChangesAreIntentional() { Version mvcVersion = VersionTestHelper.GetVersionFromAssembly("System.Web.Mvc", typeof(Controller)); - Assert.Equal(new Version(5, 2, 7, 0), mvcVersion); + Assert.Equal(new Version(5, 3, 1, 0), mvcVersion); } } } diff --git a/test/Microsoft.Web.Mvc.Test/app.config b/test/Microsoft.Web.Mvc.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/Microsoft.Web.Mvc.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/Microsoft.Web.Mvc.Test/packages.config b/test/Microsoft.Web.Mvc.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/Microsoft.Web.Mvc.Test/packages.config +++ b/test/Microsoft.Web.Mvc.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/Microsoft.Web.WebPages.OAuth.Test/Microsoft.Web.WebPages.OAuth.Test.csproj b/test/Microsoft.Web.WebPages.OAuth.Test/Microsoft.Web.WebPages.OAuth.Test.csproj index 3d56fbe66..102a07f00 100644 --- a/test/Microsoft.Web.WebPages.OAuth.Test/Microsoft.Web.WebPages.OAuth.Test.csproj +++ b/test/Microsoft.Web.WebPages.OAuth.Test/Microsoft.Web.WebPages.OAuth.Test.csproj @@ -1,7 +1,7 @@  - - + + {694C6EDF-EA52-438F-B745-82B025ECC0E7} @@ -14,56 +14,72 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - False - ..\..\packages\DotNetOpenAuth.AspNet.4.0.3.12153\lib\net40-full\DotNetOpenAuth.AspNet.dll + + ..\..\packages\DotNetOpenAuth.AspNet.4.3.4.13329\lib\net45-full\DotNetOpenAuth.AspNet.dll + True - - False - ..\..\packages\DotNetOpenAuth.Core.4.0.3.12153\lib\net40-full\DotNetOpenAuth.Core.dll + + ..\..\packages\DotNetOpenAuth.Core.4.3.4.13329\lib\net45-full\DotNetOpenAuth.Core.dll + True - - False - ..\..\packages\DotNetOpenAuth.OAuth.Core.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OAuth.dll + + ..\..\packages\DotNetOpenAuth.OAuth.Core.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OAuth.dll + True - - False - ..\..\packages\DotNetOpenAuth.OAuth.Consumer.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OAuth.Consumer.dll + + ..\..\packages\DotNetOpenAuth.OAuth.Consumer.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OAuth.Consumer.dll + True - - False - ..\..\packages\DotNetOpenAuth.OpenId.Core.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OpenId.dll + + ..\..\packages\DotNetOpenAuth.OpenId.Core.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OpenId.dll + True - - False - ..\..\packages\DotNetOpenAuth.OpenId.RelyingParty.4.0.3.12153\lib\net40-full\DotNetOpenAuth.OpenId.RelyingParty.dll + + ..\..\packages\DotNetOpenAuth.OpenId.RelyingParty.4.3.4.13329\lib\net45-full\DotNetOpenAuth.OpenId.RelyingParty.dll + True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True + + ..\..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Extensions.dll + True + + + ..\..\packages\Microsoft.Net.Http.2.2.29\lib\net45\System.Net.Http.Primitives.dll + True + + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -90,23 +106,25 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + + - - + + \ No newline at end of file diff --git a/test/Microsoft.Web.WebPages.OAuth.Test/OAuthWebSecurityTest.cs b/test/Microsoft.Web.WebPages.OAuth.Test/OAuthWebSecurityTest.cs index 06faab04c..2ccd60de8 100644 --- a/test/Microsoft.Web.WebPages.OAuth.Test/OAuthWebSecurityTest.cs +++ b/test/Microsoft.Web.WebPages.OAuth.Test/OAuthWebSecurityTest.cs @@ -324,7 +324,7 @@ public void TestRegisterFacebookClient() // Assert Assert.True(data.IsReadOnly); - Assert.Equal(1, data.Count); + Assert.Single(data); Assert.Equal("facebook", data.First().AuthenticationClient.ProviderName); Assert.Equal("FB", data.First().DisplayName); Assert.Null(data.First().ExtraData); @@ -341,7 +341,7 @@ public void TestRegisterMicrosoftClient() // Assert Assert.True(data.IsReadOnly); - Assert.Equal(1, data.Count); + Assert.Single(data); Assert.Equal("microsoft", data.First().AuthenticationClient.ProviderName); Assert.Equal("MS", data.First().DisplayName); Assert.Null(data.First().ExtraData); @@ -358,7 +358,7 @@ public void TestRegisterTwitterClient() // Assert Assert.True(data.IsReadOnly); - Assert.Equal(1, data.Count); + Assert.Single(data); Assert.Equal("twitter", data.First().AuthenticationClient.ProviderName); Assert.Equal("Tweet", data.First().DisplayName); Assert.Null(data.First().ExtraData); @@ -375,7 +375,7 @@ public void TestRegisterLinkedInClient() // Assert Assert.True(data.IsReadOnly); - Assert.Equal(1, data.Count); + Assert.Single(data); Assert.Equal("linkedIn", data.First().AuthenticationClient.ProviderName); Assert.Equal("LINKED", data.First().DisplayName); Assert.Null(data.First().ExtraData); @@ -392,7 +392,7 @@ public void TestRegisterGoogleClient() // Assert Assert.True(data.IsReadOnly); - Assert.Equal(1, data.Count); + Assert.Single(data); Assert.Equal("google", data.First().AuthenticationClient.ProviderName); Assert.Equal("GOOG", data.First().DisplayName); Assert.Null(data.First().ExtraData); @@ -409,7 +409,7 @@ public void TestRegisterYahooClient() // Assert Assert.True(data.IsReadOnly); - Assert.Equal(1, data.Count); + Assert.Single(data); Assert.Equal("yahoo", data.First().AuthenticationClient.ProviderName); Assert.Equal("YHOO", data.First().DisplayName); Assert.Null(data.First().ExtraData); diff --git a/test/Microsoft.Web.WebPages.OAuth.Test/packages.config b/test/Microsoft.Web.WebPages.OAuth.Test/packages.config index 16962493c..b4517b6ac 100644 --- a/test/Microsoft.Web.WebPages.OAuth.Test/packages.config +++ b/test/Microsoft.Web.WebPages.OAuth.Test/packages.config @@ -1,19 +1,24 @@  - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.NetCore.Test/System.Net.Http.Formatting.NetCore.Test.csproj b/test/System.Net.Http.Formatting.NetCore.Test/System.Net.Http.Formatting.NetCore.Test.csproj deleted file mode 100644 index 0a37202a2..000000000 --- a/test/System.Net.Http.Formatting.NetCore.Test/System.Net.Http.Formatting.NetCore.Test.csproj +++ /dev/null @@ -1,330 +0,0 @@ - - - - - - - {8DA61DAC-FF7E-4CA1-93A0-6148DB66FD08} - Library - Properties - System.Net.Http - System.Net.Http.Formatting.NetCore.Test - ..\..\bin\$(Configuration)\Test\NetCore\ - $(DefineConstants);NETFX_CORE - - - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll - True - - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll - True - - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll - True - - - - - - - ..\..\packages\Microsoft.Net.Http.2.2.13\lib\net45\System.Net.Http.Extensions.dll - - - ..\..\packages\Microsoft.Net.Http.2.2.13\lib\net45\System.Net.Http.Primitives.dll - - - - - - - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll - True - - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll - True - - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll - True - - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll - True - - - - - False - - - - - DataSets\Types\DerivedFormUrlEncodedMediaTypeFormatter.cs - - - Formatting\BsonMediaTypeFormatterTests.cs - - - Internal\FormDataCollectionTests.cs - - - Formatting\FormUrlEncodedFromContentTests.cs - - - Formatting\FormUrlEncodedFromUriQueryTests.cs - - - Internal\FormUrlEncodedJsonTests.cs - - - Formatting\FormUrlEncodedMediaTypeFormatterTests.cs - - - Formatting\JsonNetSerializationTest.cs - - - Formatting\JsonNetValidationTest.cs - - - Internal\FormUrlEncodedParserTests.cs - - - HttpContentFormDataExtensionsTest.cs - - - HttpValueCollectionTest.cs - - - Internal\ReadOnlyStreamWithEncodingPreambleTest.cs - - - MimeBodyPartTest.cs - - - HttpHeaderExtensionsTest.cs - - - HttpUnsortedResponseTest.cs - - - HttpUnsortedRequestTest.cs - - - SFormatting\tringComparisonHelperTest.cs - - - Mocks\MockAsyncCallback.cs - - - Mocks\MockCompletedAsyncResult.cs - - - HttpClientFactoryTest.cs - - - Handlers\ProgressContentTest.cs - - - Handlers\ProgressStreamTest.cs - - - Handlers\HttpProgressEventArgsTest.cs - - - MultipartRelatedStreamProviderTests.cs - - - MultipartStreamProviderTestBase.cs - - - MultipartFileDataTest.cs - - - DataSets\Types\DataContractEnum.cs - - - DataSets\Types\DataContractType.cs - - - DataSets\Types\DerivedDataContractType.cs - - - DataSets\Types\DerivedJsonMediaTypeFormatter.cs - - - DataSets\Types\DerivedWcfPocoType.cs - - - DataSets\Types\DerivedXmlMediaTypeFormatter.cs - - - DataSets\Types\DerivedXmlSerializableType.cs - - - DataSets\HttpTestData.cs - - - DataSets\Types\INotJsonSerializable.cs - - - DataSets\Types\WcfPocoType.cs - - - DataSets\Types\XmlSerializableType.cs - - - Formatting\SerializerConsistencyTests.cs - - - Formatting\XmlSerializerMediaTypeFormatterTests.cs - - - Formatting\MediaTypeFormatterTestBase.cs - - - HttpClientExtensionsTest.cs - - - Internal\AsyncResultTest.cs - - - Internal\DelegatingStreamTest.cs - - - Mocks\MockDelegatingHandler.cs - - - Mocks\MockDelegatingStream.cs - - - Mocks\MockProgressEventHandler.cs - - - Mocks\TestableHttpMessageHandler.cs - - - UriExtensionsTests.cs - - - UriQueryDataSet.cs - - - FormattingUtilitiesTests.cs - - - Formatting\JsonMediaTypeFormatterTests.cs - - - Formatting\MediaTypeConstantsTests.cs - - - Formatting\MediaTypeFormatterCollectionTests.cs - - - Formatting\MediaTypeFormatterTests.cs - - - Formatting\MediaTypeHeaderValueExtensionsTests.cs - - - Formatting\ParsedMediaTypeHeaderValueTests.cs - - - Formatting\XmlMediaTypeFormatterTests.cs - - - HttpContentMessageExtensionsTests.cs - - - HttpContentMultipartExtensionsTests.cs - - - HttpMessageContentTests.cs - - - Formatting\Parsers\HttpRequestHeaderParserTests.cs - - - Formatting\Parsers\HttpRequestLineParserTests.cs - - - Formatting\Parsers\HttpResponseHeaderParserTests.cs - - - Formatting\Parsers\HttpStatusLineParserTests.cs - - - Formatting\Parsers\InternetMessageFormatHeaderParserTests.cs - - - Formatting\Parsers\MimeMultipartParserTests.cs - - - MultipartMemoryStreamProviderTests.cs - - - ObjectContentOfTTests.cs - - - ObjectContentTests.cs - - - ParserData.cs - - - Mocks\MockHttpContent.cs - - - Mocks\MockMediaTypeFormatter.cs - - - HttpContentExtensionsTest.cs - - - PushStreamContentTest.cs - - - ProgressMessageHandlerTest.cs - - - ConcurrentDictionaryTests.cs - - - - - {C7060639-719B-4BD2-8A37-2F146B5A0668} - System.Net.Http.Formatting - - - {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0} - Microsoft.TestCommon - - - - - - Designer - - - - - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.NetCore.Test/app.config b/test/System.Net.Http.Formatting.NetCore.Test/app.config deleted file mode 100644 index 965f5a300..000000000 --- a/test/System.Net.Http.Formatting.NetCore.Test/app.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.NetCore.Test/packages.config b/test/System.Net.Http.Formatting.NetCore.Test/packages.config deleted file mode 100644 index 6518cc255..000000000 --- a/test/System.Net.Http.Formatting.NetCore.Test/packages.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.NetStandard.Test/System.Net.Http.Formatting.NetStandard.Test.csproj b/test/System.Net.Http.Formatting.NetStandard.Test/System.Net.Http.Formatting.NetStandard.Test.csproj deleted file mode 100644 index 31732bd10..000000000 --- a/test/System.Net.Http.Formatting.NetStandard.Test/System.Net.Http.Formatting.NetStandard.Test.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - netcoreapp2.0;net461 - System.Net.Http - System.Net.Http.Formatting.NetStandard.Test - ..\..\bin\$(Configuration)\Test\ - $(DefineConstants);NEWTONSOFTJSON10 - $(Configurations);CodeAnalysis - false - - - - - - - - - %(RecursiveDir)\%(Filename).cs - - - - - - - - - - - - - diff --git a/test/System.Net.Http.Formatting.NetStandard.Test/app.config b/test/System.Net.Http.Formatting.NetStandard.Test/app.config deleted file mode 100644 index 8460dd432..000000000 --- a/test/System.Net.Http.Formatting.NetStandard.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.Test/ByteRangeStreamContentTest.cs b/test/System.Net.Http.Formatting.Test/ByteRangeStreamContentTest.cs index 410fc2b24..7dbed8f7d 100644 --- a/test/System.Net.Http.Formatting.Test/ByteRangeStreamContentTest.cs +++ b/test/System.Net.Http.Formatting.Test/ByteRangeStreamContentTest.cs @@ -127,7 +127,8 @@ public void Ctor_ThrowsOnNullMediaTypeString() range: range, mediaType: (String)null, bufferSize: 128), - "mediaType"); + "mediaType", + allowDerivedExceptions: true); } [Fact] diff --git a/test/System.Net.Http.Formatting.Test/DataSets/HttpTestData.cs b/test/System.Net.Http.Formatting.Test/DataSets/HttpTestData.cs index fb482788b..5e7672b2e 100644 --- a/test/System.Net.Http.Formatting.Test/DataSets/HttpTestData.cs +++ b/test/System.Net.Http.Formatting.Test/DataSets/HttpTestData.cs @@ -302,11 +302,11 @@ public static TheoryDataSet ReadAndWriteCorrectCharacterEn { "This is a test 激光這兩個字是甚麼意思 string written using utf-8", "utf-8", true }, { "This is a test 激光這兩個字是甚麼意思 string written using utf-16", "utf-16", true }, { "This is a test 激光這兩個字是甚麼意思 string written using utf-32", "utf-32", false }, -#if !NETCOREAPP2_0 // shift_jis and iso-2022-kr are not supported when running on .NET Core 2.0. +#if !NETCOREAPP // shift_jis and iso-2022-kr are not supported when running on .NET Core 2.1. { "This is a test 激光這兩個字是甚麼意思 string written using shift_jis", "shift_jis", false }, #endif { "This is a test æøå string written using iso-8859-1", "iso-8859-1", false }, -#if !NETCOREAPP2_0 +#if !NETCOREAPP { "This is a test 레이저 단어 뜻 string written using iso-2022-kr", "iso-2022-kr", false }, #endif }; @@ -356,7 +356,6 @@ public static TestData StandardHttpContents //// TODO: make this list compose from other data? // Collection of legal instances of all standard MediaTypeMapping types -#if !NETFX_CORE // not present in portable library version public static TestData StandardMediaTypeMappings { get @@ -375,7 +374,6 @@ public static TestData QueryStringMappings }); } } -#endif public static TestData LegalUriPathExtensions { diff --git a/test/System.Net.Http.Formatting.Test/Formatting/BsonMediaTypeFormatterTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/BsonMediaTypeFormatterTests.cs index d849df473..93cea6ba7 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/BsonMediaTypeFormatterTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/BsonMediaTypeFormatterTests.cs @@ -149,9 +149,7 @@ void CopyConstructor() // Arrange TestBsonMediaTypeFormatter formatter = new TestBsonMediaTypeFormatter() { -#if !NETFX_CORE // MaxDepth is not supported in portable library MaxDepth = 42, -#endif }; // Replace serializable settings and switch one property's value @@ -163,16 +161,13 @@ void CopyConstructor() TestBsonMediaTypeFormatter derivedFormatter = new TestBsonMediaTypeFormatter(formatter); // Assert -#if !NETFX_CORE // MaxDepth is not supported in portable library Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth); -#endif Assert.NotSame(oldSettings, formatter.SerializerSettings); Assert.NotEqual(oldSettings.CheckAdditionalContent, formatter.SerializerSettings.CheckAdditionalContent); Assert.Same(formatter.SerializerSettings, derivedFormatter.SerializerSettings); Assert.Same(formatter.SerializerSettings.ContractResolver, derivedFormatter.SerializerSettings.ContractResolver); } -#if !NETFX_CORE // MaxDepth is not supported in portable library [Fact] public void MaxDepth_RoundTrips() { @@ -187,7 +182,6 @@ public void MaxDepth_RoundTrips() illegalUpperValue: null, roundTripTestValue: 256); } -#endif [Theory] [TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection")] @@ -262,14 +256,8 @@ public async Task FormatterThrowsOnWriteWithInvalidContent() BsonMediaTypeFormatter formatter = new BsonMediaTypeFormatter(); HttpContent content = new StringContent(String.Empty); MemoryStream stream = new MemoryStream(); -#if NEWTONSOFTJSON10 // Json.NET 10's Bson package calculates the path in some exceptions differently. - string expectedPath = "Value"; -#else - string expectedPath = string.Empty; -#endif - string expectedMessage = string.Format( - "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values. Path '{0}'.", - expectedPath); + string expectedMessage = + "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values. Path 'Value'."; // Act & Assert // Note error message is not quite correct: BSON supports byte, ushort, and smaller uint / ulong values. @@ -340,9 +328,14 @@ public async Task FormatterThrowsOnReadWithInvalidContent() stream.Seek(0L, SeekOrigin.Begin); // Act & Assert - await Assert.ThrowsAsync( + await Assert.ThrowsAsync( () => formatter.ReadFromStreamAsync(variationType, stream, content, null), - "Value was either too large or too small for a Decimal."); +#if NETCOREAPP3_1_OR_GREATER + "Could not convert to decimal: 7.922816251426434E+28. Path 'Value'." +#else + "Could not convert to decimal: 7.92281625142643E+28. Path 'Value'." +#endif + ); } [Theory] @@ -399,7 +392,6 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_PerhapsJObjec } } -#if !NETFX_CORE // DBNull not supported in portable library // Test alternate null value [Theory] [TestDataSet(typeof(JsonMediaTypeFormatterTests), "DBNullAsObjectTestDataCollection", TestDataVariations.AllSingleInstances)] @@ -415,7 +407,7 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull( Assert.Null(readObj); } -#if !NETCOREAPP2_0 // DBNull not serializable on .NET Core 2.0 except at top level (using BsonMediaTypeformatter special case). +#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1 except at top level (using BsonMediaTypeformatter special case). [Theory] [TestDataSet(typeof(JsonMediaTypeFormatterTests), "DBNullAsObjectTestDataCollection", TestDataVariations.AsDictionary)] public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNullAsNull_Dictionary(Type variationType, object testData) @@ -519,7 +511,6 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNull() // Only BSON case where DBNull.Value round-trips Assert.Equal(testData, readObj); } -#endif private class TestBsonMediaTypeFormatter : BsonMediaTypeFormatter { diff --git a/test/System.Net.Http.Formatting.Test/Formatting/DataContractJsonMediaTypeFormatterTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/DataContractJsonMediaTypeFormatterTests.cs index ad3311326..b94b19598 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/DataContractJsonMediaTypeFormatterTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/DataContractJsonMediaTypeFormatterTests.cs @@ -24,6 +24,13 @@ public DataContractJsonMediaTypeFormatter() public class DataContractJsonMediaTypeFormatterTests : MediaTypeFormatterTestBase { + public static readonly TheoryDataSet AFewValidTypes = new() + { + typeof(bool), + typeof(int), + typeof(string), + }; + public override IEnumerable ExpectedSupportedMediaTypes { get { return HttpTestData.StandardJsonMediaTypes; } @@ -87,18 +94,19 @@ public void CanReadType_ReturnsExpectedValues(Type variationType, object testDat Assert.False(isSerializable != canSupport && isSerializable, String.Format("2nd CanReadType returned wrong value for '{0}'.", variationType)); } - [Fact] - public void CanReadType_ReturnsFalse_ForInvalidDataContracts() + [Theory] + [PropertyData(nameof(AFewValidTypes))] + public void CanWriteType_ReturnsFalse_ForValidTypes(Type type) { - JsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter(); - Assert.False(formatter.CanReadType(typeof(InvalidDataContract))); - } + XmlMediaTypeFormatter formatter = new(); - [Fact] - public void CanWriteType_ReturnsFalse_ForInvalidDataContracts() - { - JsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter(); - Assert.False(formatter.CanWriteType(typeof(InvalidDataContract))); + var canWrite = formatter.CanWriteType(type); + +#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation. + Assert.False(canWrite); +#else + Assert.True(canWrite); +#endif } public class InvalidDataContract @@ -109,6 +117,7 @@ public InvalidDataContract(string s) } } +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Theory] [InlineData(typeof(IQueryable))] [InlineData(typeof(IEnumerable))] @@ -122,6 +131,7 @@ public async Task UseJsonFormatterWithNull(Type type) string serializedString = new StreamReader(memoryStream).ReadToEnd(); Assert.True(serializedString.Contains("null"), "Using Json formatter to serialize null should emit 'null'."); } +#endif [Theory] [TestDataSet(typeof(JsonMediaTypeFormatterTests), "ValueAndRefTypeTestDataCollectionExceptULong", RoundTripDataVariations)] @@ -157,7 +167,55 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_KnownTypes(Ty } } -#if !NETCOREAPP2_0 // DBNull not serializable on .NET Core 2.0. +#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. + [Theory] + [TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection", RoundTripDataVariations)] + public async Task ReadFromStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData) + { + // Arrange. First, get some data using XmlSerializer. + bool canSerialize = IsTypeSerializableWithJsonSerializer(variationType, testData, actuallyCheck: true) && + Assert.Http.CanRoundTrip(variationType); + if (canSerialize) + { + var formatter = new JsonMediaTypeFormatter(); + using var stream = new MemoryStream(); + using var content = new StringContent(string.Empty); + + await formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null); + await stream.FlushAsync(); + stream.Position = 0L; + + content.Headers.ContentLength = stream.Length; + formatter.UseDataContractJsonSerializer = true; + + // Act & Assert + await Assert.ThrowsAsync(() => + formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger: null), + "Unable to validate types on this platform when UseDataContractJsonSerializer is 'true'. " + + "Please reset UseDataContractJsonSerializer or move to a supported platform, one where the " + + ".NET Standard 2.0 assembly is usable."); + } + } + + [Theory] + [TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection", RoundTripDataVariations)] + public async Task WriteToStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData) + { + // Arrange + var formatter = new JsonMediaTypeFormatter() { UseDataContractJsonSerializer = true}; + using var stream = new MemoryStream(); + using var content = new StringContent(string.Empty); + + // Act & Assert + await Assert.ThrowsAsync(() => + formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null), + "Unable to validate types on this platform when UseDataContractJsonSerializer is 'true'. " + + "Please reset UseDataContractJsonSerializer or move to a supported platform, one where the " + + ".NET Standard 2.0 assembly is usable."); + } + +#else +#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1. // Test alternate null value [Fact] public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync_DBNull() @@ -201,6 +259,7 @@ public async Task UseDataContractJsonSerializer_Default() string serializedString = new StreamReader(memoryStream).ReadToEnd(); Assert.False(serializedString.Contains("\r\n"), "Using DCJS should emit data without indentation by default."); } +#endif [Fact] public void UseDataContractJsonSerializer_True_Indent_Throws() @@ -214,14 +273,69 @@ public void UseDataContractJsonSerializer_True_Indent_Throws() memoryStream, content, transportContext: null)); } +#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. + [Fact] + public override Task Overridden_ReadFromStreamAsyncWithCancellationToken_GetsCalled() + { + return Task.CompletedTask; + } + + [Fact] + public override Task Overridden_ReadFromStreamAsyncWithoutCancellationToken_GetsCalled() + { + return Task.CompletedTask; + } + + [Fact] + public override Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled() + { + return Task.CompletedTask; + } + + [Fact] + public override Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled() + { + return Task.CompletedTask; + } + + [Fact] + public override Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } + + // Attributes are in base class. public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) { - if (!isDefaultEncoding) - { - // XmlDictionaryReader/Writer only supports utf-8 and 16 - return TaskHelpers.Completed(); - } + return Task.CompletedTask; + } + + [Fact] + public override Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } + + // Attributes are in base class. + public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) + { + return Task.CompletedTask; + } + [Fact] + public override Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } + + [Fact] + public override Task WriteToStreamAsync_WritesDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } +#else + public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) + { // Arrange DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter(); string formattedContent = "\"" + content + "\""; @@ -234,14 +348,6 @@ public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string con public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) { - // DataContractJsonSerializer does not honor the value of byteOrderMark in the UnicodeEncoding ctor. - // It doesn't include the BOM when byteOrderMark is set to true. - if (!isDefaultEncoding || encoding != "utf-8") - { - // XmlDictionaryReader/Writer only supports utf-8 and 16 - return TaskHelpers.Completed(); - } - // Arrange DataContractJsonMediaTypeFormatter formatter = new DataContractJsonMediaTypeFormatter(); string formattedContent = "\"" + content + "\""; @@ -251,6 +357,7 @@ public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string cont return WriteContentUsingCorrectCharacterEncodingHelperAsync( formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding); } +#endif public class TestJsonMediaTypeFormatter : DataContractJsonMediaTypeFormatter { @@ -279,8 +386,15 @@ public override DataContractJsonSerializer CreateDataContractSerializer(Type typ } } - private bool IsTypeSerializableWithJsonSerializer(Type type, object obj) + private bool IsTypeSerializableWithJsonSerializer(Type type, object obj, bool actuallyCheck = false) { +#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation. + if (!actuallyCheck) + { + return false; + } +#endif + try { new DataContractJsonSerializer(type); diff --git a/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromContentTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromContentTests.cs index dec45eab4..fcc01232d 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromContentTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromContentTests.cs @@ -340,11 +340,11 @@ private static void BuildParams(string prefix, JToken jsonValue, List re { dateStr = dateStr.Substring(1, dateStr.Length - 2); } - results.Add(prefix + "=" + UriQueryUtility.UrlEncode(dateStr)); + results.Add(prefix + "=" + WebUtility.UrlEncode(dateStr)); } else { - results.Add(prefix + "=" + UriQueryUtility.UrlEncode(jsonPrimitive.Value.ToString())); + results.Add(prefix + "=" + WebUtility.UrlEncode(jsonPrimitive.Value.ToString())); } } } diff --git a/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromUriQueryTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromUriQueryTests.cs index 4dee5366e..b56717039 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromUriQueryTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/FormUrlEncodedFromUriQueryTests.cs @@ -279,11 +279,11 @@ private static void BuildParams(string prefix, JToken jsonValue, List re { dateStr = dateStr.Substring(1, dateStr.Length - 2); } - results.Add(prefix + "=" + UriQueryUtility.UrlEncode(dateStr)); + results.Add(prefix + "=" + WebUtility.UrlEncode(dateStr)); } else { - results.Add(prefix + "=" + UriQueryUtility.UrlEncode(jsonPrimitive.Value.ToString())); + results.Add(prefix + "=" + WebUtility.UrlEncode(jsonPrimitive.Value.ToString())); } } } diff --git a/test/System.Net.Http.Formatting.Test/Formatting/JsonMediaTypeFormatterTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/JsonMediaTypeFormatterTests.cs index 34d17d884..31de4facd 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/JsonMediaTypeFormatterTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/JsonMediaTypeFormatterTests.cs @@ -11,6 +11,7 @@ using System.Text; using System.Threading.Tasks; using Microsoft.TestCommon; +using Moq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -83,18 +84,14 @@ void CopyConstructor() TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter() { Indent = true, -#if !NETFX_CORE // MaxDepth and DCJS not supported in client portable library MaxDepth = 42, UseDataContractJsonSerializer = true -#endif }; TestJsonMediaTypeFormatter derivedFormatter = new TestJsonMediaTypeFormatter(formatter); -#if !NETFX_CORE // MaxDepth and DCJS not supported in client portable library Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth); Assert.Equal(formatter.UseDataContractJsonSerializer, derivedFormatter.UseDataContractJsonSerializer); -#endif Assert.Equal(formatter.Indent, derivedFormatter.Indent); Assert.Same(formatter.SerializerSettings, derivedFormatter.SerializerSettings); Assert.Same(formatter.SerializerSettings.ContractResolver, derivedFormatter.SerializerSettings.ContractResolver); @@ -117,7 +114,6 @@ public void Indent_RoundTrips() expectedDefaultValue: false); } -#if !NETFX_CORE // MaxDepth is not supported in portable libraries [Fact] public void MaxDepth_RoundTrips() { @@ -131,7 +127,6 @@ public void MaxDepth_RoundTrips() illegalUpperValue: null, roundTripTestValue: 256); } -#endif [Theory] [TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection")] @@ -230,7 +225,7 @@ public async Task FormatterThrowsOnReadWhenOverridenCreateReturnsNull() Assert.NotNull(formatter.InnerJsonSerializer); } -#if !NETFX_CORE +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Fact] public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateFails() { @@ -374,7 +369,7 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsync(Type variatio } } -#if !NETCOREAPP2_0 // DBNull not serializable on .NET Core 2.0. +#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1. // Test alternate null value; always serialized as "null" [Theory] [TestDataSet(typeof(JsonMediaTypeFormatterTests), "DBNullAsObjectTestDataCollection", TestDataVariations.AllSingleInstances)] @@ -499,9 +494,7 @@ public async Task UseDataContractJsonSerializer_False() { JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter { -#if !NETFX_CORE // No JsonSerializer in portable libraries UseDataContractJsonSerializer = false -#endif }; MemoryStream memoryStream = new MemoryStream(); HttpContent content = new StringContent(String.Empty); @@ -518,9 +511,7 @@ public async Task UseDataContractJsonSerializer_False_Indent() { JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter { -#if !NETFX_CORE // No JsonSerializer in portable libraries UseDataContractJsonSerializer = false, -#endif Indent = true }; MemoryStream memoryStream = new MemoryStream(); @@ -538,9 +529,7 @@ public async Task UseJsonFormatterWithNull(Type type) { JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter { -#if !NETFX_CORE // No JsonSerializer in portable libraries UseDataContractJsonSerializer = false -#endif }; MemoryStream memoryStream = new MemoryStream(); HttpContent content = new StringContent(String.Empty); @@ -590,6 +579,29 @@ public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string cont formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding); } +#if NET6_0_OR_GREATER + // Cannot Mock a Stream and let JsonWriter write to it. Writer will use ReadOnlySpan in this case and such + // parameters are not currently mockable. See moq/moq4#829, moq/moq4#979, and dotnet/runtime#45152. + // Override here avoids the Mock and should confirm this Stream is not closed. Also adds an + // additional check of the written text. + [Fact] + public override async Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream() + { + // Arrange + JsonMediaTypeFormatter formatter = CreateFormatter(); + Stream stream = new MemoryStream(); + HttpContent content = new StreamContent(Stream.Null); + + // Act + await formatter.WriteToStreamAsync(typeof(SampleType), null, stream, content, null); + + // Assert (stream will throw if it has been closed) + stream.Position = 0; + using var reader = new StreamReader(stream); + Assert.Equal("null", reader.ReadToEnd()); + } +#endif + public class TestJsonMediaTypeFormatter : JsonMediaTypeFormatter { public TestJsonMediaTypeFormatter() @@ -633,7 +645,6 @@ public override JsonSerializer CreateJsonSerializer() return InnerJsonSerializer; } -#if !NETFX_CORE public override DataContractJsonSerializer CreateDataContractSerializer(Type type) { InnerDataContractSerializer = base.CreateDataContractSerializer(type); @@ -650,7 +661,6 @@ public override DataContractJsonSerializer CreateDataContractSerializer(Type typ return InnerDataContractSerializer; } -#endif } private bool IsTypeSerializableWithJsonSerializer(Type type, object obj) diff --git a/test/System.Net.Http.Formatting.Test/Formatting/JsonNetSerializationTest.cs b/test/System.Net.Http.Formatting.Test/Formatting/JsonNetSerializationTest.cs index b544752f0..da5c9d7da 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/JsonNetSerializationTest.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/JsonNetSerializationTest.cs @@ -92,7 +92,7 @@ public static TheoryDataSet SerializedJson // Classes { new DataContractType() { s = "foo", i = 49, NotAMember = "Error" }, "{\"s\":\"foo\",\"i\":49}" }, { new POCOType() { s = "foo", t = "Error"}, "{\"s\":\"foo\"}" }, -#if !NETFX_CORE // Only publics are serialized in portable library +#if !Testing_NetStandard1_3 // Only publics are serialized in netstandard1.3 { new SerializableType("protected") { publicField = "public", protectedInternalField = "protected internal", internalField = "internal", PublicProperty = "private", nonSerializedField = "Error" }, "{\"publicField\":\"public\",\"internalField\":\"internal\",\"protectedInternalField\":\"protected internal\",\"protectedField\":\"protected\",\"privateField\":\"private\"}" }, #else { new SerializableType("protected") { publicField = "public", protectedInternalField = "protected internal", internalField = "internal", PublicProperty = "private", nonSerializedField = "Error" }, "{\"publicField\":\"public\",\"PublicProperty\":\"private\"}" }, @@ -258,7 +258,7 @@ public Task DeserializingDeepArraysThrows() // low surrogate not preceded by high surrogate [InlineData("ABC \\udc00\\ud800 DEF", "ABC \ufffd\ufffd DEF")] // make sure unencoded invalid surrogate characters don't make it through -#if NETCOREAPP2_0 // Json.NET uses its regular invalid Unicode character on .NET Core 2.0; '?' elsewhere. +#if NETCOREAPP // Json.NET uses its regular invalid Unicode character on .NET Core 2.1; '?' elsewhere. [InlineData("\udc00\ud800\ud800", "\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd")] #else [InlineData("\udc00\ud800\ud800", "??????")] @@ -491,7 +491,7 @@ public string PublicProperty public bool Equals(SerializableType other) { -#if !NETFX_CORE // Only publics are serialized in portable library. privateField is serialized through PublicProperty +#if !Testing_NetStandard1_3 // Only publics are serialized in netstandard1.3. privateField is serialized through PublicProperty return this.publicField == other.publicField && this.internalField == other.internalField && this.protectedInternalField == other.protectedInternalField && diff --git a/test/System.Net.Http.Formatting.Test/Formatting/JsonNetValidationTest.cs b/test/System.Net.Http.Formatting.Test/Formatting/JsonNetValidationTest.cs index 5eb23569f..60bad376d 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/JsonNetValidationTest.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/JsonNetValidationTest.cs @@ -28,15 +28,7 @@ public static TheoryDataSet Theories {"\"foo\"", typeof(DateTime), 1}, {"[\"a\",\"b\",\"45\",34]", typeof(int[]), 2}, - { - "[\"a\",\"b\",\"45\",34]", - typeof(DateTime[]), -#if NEWTONSOFTJSON10 // Json.NET 10 detects an additional error over earlier versions. - 5 -#else - 4 -#endif - }, + {"[\"a\",\"b\",\"45\",34]", typeof(DateTime[]), 5}, // Required members @@ -51,7 +43,6 @@ public static TheoryDataSet Theories } } -#if !NETFX_CORE // IRequiredMemeberSelector is not in portable libraries because there is no model state on the client. [Theory] [PropertyData("Theories")] public async Task ModelErrorsPopulatedWithValidationErrors(string json, Type type, int expectedErrors) @@ -64,7 +55,6 @@ public async Task ModelErrorsPopulatedWithValidationErrors(string json, Type typ mockLogger.Verify(mock => mock.LogError(It.IsAny(), It.IsAny()), Times.Exactly(expectedErrors)); } -#endif [Fact] public async Task HittingMaxDepthRaisesOnlyOneValidationError() @@ -89,7 +79,6 @@ public async Task HittingMaxDepthRaisesOnlyOneValidationError() } } -#if !NETFX_CORE // IRequiredMemeberSelector is not in portable libraries because there is no model state on the client. // this IRMS treats all member names that start with "Required" as required public class SimpleRequiredMemberSelector : IRequiredMemberSelector { @@ -98,7 +87,6 @@ public bool IsRequiredMember(MemberInfo member) return member.Name.StartsWith("Required"); } } -#endif public class DataContractWithRequiredMembers { diff --git a/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterCollectionTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterCollectionTests.cs index cd1c9e03b..9c8643757 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterCollectionTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterCollectionTests.cs @@ -361,9 +361,7 @@ public void FindWriter_ReturnsFormatterOnMatch(Type variationType, object testDa [InlineData(typeof(XAttribute))] [InlineData(typeof(Type))] [InlineData(typeof(byte[]))] -#if !NETFX_CORE [InlineData(typeof(XmlElement))] -#endif [InlineData(typeof(FormDataCollection))] public void IsTypeExcludedFromValidation_ReturnsTrueForExcludedTypes(Type type) { diff --git a/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTestBase.cs b/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTestBase.cs index d5618f8db..b3c4e4831 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTestBase.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTestBase.cs @@ -152,7 +152,7 @@ public async Task ReadFromStreamAsync_WhenContentLengthIsZero_ReturnsDefaultType } [Fact] - public async Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream() + public virtual async Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream() { // Arrange TFormatter formatter = CreateFormatter(); @@ -173,7 +173,7 @@ public async Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream() } [Fact] - public async Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream() + public virtual async Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream() { // Arrange TFormatter formatter = CreateFormatter(); @@ -219,7 +219,7 @@ public virtual async Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesN } [Fact] - public async Task WriteToStreamAsync_WritesDataButDoesNotCloseStream() + public virtual async Task WriteToStreamAsync_WritesDataButDoesNotCloseStream() { // Arrange TFormatter formatter = CreateFormatter(); diff --git a/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTests.cs index 0d75a9634..526e0734f 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/MediaTypeFormatterTests.cs @@ -51,12 +51,10 @@ public void Constructor() Collection supportedMediaTypes = formatter.SupportedMediaTypes; Assert.NotNull(supportedMediaTypes); Assert.Empty(supportedMediaTypes); -#if !NETFX_CORE // No MediaTypeMapping support in portable libraries Collection mappings = formatter.MediaTypeMappings; Assert.NotNull(mappings); Assert.Empty(mappings); -#endif } [Fact] @@ -65,11 +63,9 @@ void CopyConstructor() TestMediaTypeFormatter formatter = new TestMediaTypeFormatter(); TestMediaTypeFormatter derivedFormatter = new TestMediaTypeFormatter(formatter); -#if !NETFX_CORE // No MediaTypeMapping or RequiredMemberSelector in client libraries Assert.Same(formatter.MediaTypeMappings, derivedFormatter.MediaTypeMappings); Assert.Same(formatter.MediaTypeMappingsInternal, derivedFormatter.MediaTypeMappingsInternal); Assert.Equal(formatter.RequiredMemberSelector, derivedFormatter.RequiredMemberSelector); -#endif Assert.Same(formatter.SupportedMediaTypes, derivedFormatter.SupportedMediaTypes); Assert.Same(formatter.SupportedMediaTypesInternal, derivedFormatter.SupportedMediaTypesInternal); @@ -151,7 +147,6 @@ public void SupportedMediaTypes_InsertThrowsWithMediaRange(MediaTypeHeaderValue Assert.ThrowsArgument(() => supportedMediaTypes.Insert(0, mediaType), "item", Error.Format(Properties.Resources.CannotUseMediaRangeForSupportedMediaType, typeof(MediaTypeHeaderValue).Name, mediaType.MediaType)); } -#if !NETFX_CORE // No MediaTypeMapping support in portable libraries [Fact] public void MediaTypeMappings_IsMutable() { @@ -165,7 +160,6 @@ public void MediaTypeMappings_IsMutable() Assert.True(standardMappings.SequenceEqual(formatter.MediaTypeMappings)); } -#endif [Fact] public void SelectCharacterEncoding_ThrowsIfNoSupportedEncodings() diff --git a/test/System.Net.Http.Formatting.Test/Formatting/SerializerConsistencyTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/SerializerConsistencyTests.cs index 63dec00a3..f396552cf 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/SerializerConsistencyTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/SerializerConsistencyTests.cs @@ -4,12 +4,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Net.Http.Formatting; using System.Runtime.Serialization; using System.Threading.Tasks; using Microsoft.TestCommon; -namespace System.Net.Formatting.Tests +namespace System.Net.Http.Formatting { // Tests for ensuring the serializers behave consistently in various cases. // This is important for conneg. @@ -18,7 +17,12 @@ public class SerializerConsistencyTests [Fact] public Task PartialContract() { - var c = new PartialDataContract { PropertyWithAttribute = "one", PropertyWithoutAttribute = "false" }; + var c = new PartialDataContract { + PropertyWithAttribute = "one", +#if !Testing_NetStandard1_3 // Xml formatter ignores DCS attributes but JSON one does not in netstandard1.3. + PropertyWithoutAttribute = "false" +#endif + }; return SerializerConsistencyHepers.TestAsync(c); } @@ -62,6 +66,7 @@ public Task NullEmptyWhitespaceString() return SerializerConsistencyHepers.TestAsync(source); } +#if !Testing_NetStandard1_3 // XmlSerializer is unable to write XML for a dictionary. [Fact] public Task Dictionary() { @@ -71,6 +76,7 @@ public Task Dictionary() return SerializerConsistencyHepers.TestAsync(dict); } +#endif [Fact] public Task Array() @@ -80,6 +86,7 @@ public Task Array() return SerializerConsistencyHepers.TestAsync(array); } +#if !Testing_NetStandard1_3 // XmlSerializer is unable to read XML for interfaces. [Fact] public async Task ArrayInterfaces() { @@ -99,6 +106,7 @@ public Task Linq() // So explicitly call out IEnumerable return SerializerConsistencyHepers.TestAsync(l, typeof(IEnumerable)); } +#endif [Fact] public Task StaticProps() @@ -124,12 +132,12 @@ public static string StaticProp { get { - Assert.True(false, "serializers should never call static properties"); + Assert.Fail("serializers should never call static properties"); return string.Empty; } set { - Assert.True(false, "serializers should never call static properties"); + Assert.Fail("serializers should never call static properties"); throw new InvalidOperationException(); // assert already threw } } @@ -141,8 +149,10 @@ public class PartialDataContract [DataMember] public string PropertyWithAttribute { get; set; } +#if !Testing_NetStandard1_3 // Xml formatter ignores DCS attributes but JSON one does not in netstandard1.3. // no attribute here public string PropertyWithoutAttribute { get; set; } +#endif } public class PrivateProperty // with private field diff --git a/test/System.Net.Http.Formatting.Test/Formatting/StringComparisonHelperTest.cs b/test/System.Net.Http.Formatting.Test/Formatting/StringComparisonHelperTest.cs index 77a8d2361..104a4c48a 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/StringComparisonHelperTest.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/StringComparisonHelperTest.cs @@ -12,15 +12,7 @@ public StringComparisonHelperTest() { } -#if NETFX_CORE // InvariantCulture and InvarianteCultureIgnore case are not supported in portable library projects - protected override void AssertForUndefinedValue(Action testCode, string parameterName, int invalidValue, Type enumType, bool allowDerivedExceptions = false) - { - Assert.ThrowsArgument( - testCode, - parameterName, - allowDerivedExceptions); - } - +#if Testing_NetStandard1_3 // InvariantCulture and InvariantCultureIgnoreCase case are not supported in netstandard1.3 project protected override bool ValueExistsForFramework(StringComparison value) { return !(value == StringComparison.InvariantCulture || value == StringComparison.InvariantCultureIgnoreCase); diff --git a/test/System.Net.Http.Formatting.Test/Formatting/XmlMediaTypeFormatterTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/XmlMediaTypeFormatterTests.cs index b1865376b..8dd69fe12 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/XmlMediaTypeFormatterTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/XmlMediaTypeFormatterTests.cs @@ -36,11 +36,18 @@ public class XmlMediaTypeFormatterTests : MediaTypeFormatterTestBase AFewValidTypes = new() + { + typeof(bool), + typeof(int), + typeof(string), + }; + public static IEnumerable BunchOfTypedObjectsTestDataCollection { get { return new TestData[] { BunchOfTypedObjectsTestData, }; } @@ -67,18 +74,14 @@ void CopyConstructor() TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter() { Indent = true, -#if !NETFX_CORE // We don't support MaxDepth in the portable library MaxDepth = 42, -#endif UseXmlSerializer = true }; TestXmlMediaTypeFormatter derivedFormatter = new TestXmlMediaTypeFormatter(formatter); Assert.Equal(formatter.Indent, derivedFormatter.Indent); -#if !NETFX_CORE // We don't support MaxDepth in the portable library Assert.Equal(formatter.MaxDepth, derivedFormatter.MaxDepth); -#endif Assert.Equal(formatter.UseXmlSerializer, derivedFormatter.UseXmlSerializer); } @@ -90,7 +93,6 @@ public void DefaultMediaType_ReturnsApplicationXml() Assert.Equal("application/xml", mediaType.MediaType); } -#if !NETFX_CORE // We don't support MaxDepth in the portable library [Fact] public void MaxDepthReturnsCorrectValue() { @@ -105,6 +107,7 @@ public void MaxDepthReturnsCorrectValue() roundTripTestValue: 10); } +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Fact] public async Task ReadDeeplyNestedObjectThrows() { @@ -135,6 +138,7 @@ public void UseXmlSerializer_RoundTrips() expectedDefaultValue: false); } +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Theory] [InlineData(typeof(IEnumerable))] [InlineData(typeof(IQueryable))] @@ -179,6 +183,7 @@ public async Task UseXmlSerializer_False_Indent() string serializedString = new StreamReader(memoryStream).ReadToEnd(); Assert.True(serializedString.Contains("\r\n"), "Using DCS with indent set to true should emit data with indentation."); } +#endif [Fact] public void SetSerializer_ThrowsWithNullType() @@ -231,6 +236,7 @@ public void RemoveSerializer_ThrowsWithNullType() Assert.ThrowsArgumentNull(() => { formatter.RemoveSerializer(null); }, "type"); } +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Fact] public async Task FormatterThrowsOnWriteWhenOverridenCreateFails() { @@ -311,9 +317,10 @@ public async Task FormatterThrowsOnReadWhenOverridenCreateReturnsNull() Assert.NotNull(formatter.InnerDataContractSerializer); Assert.Null(formatter.InnerXmlSerializer); } +#endif [Fact] - public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateFails() + public async Task XmlSerializerFormatterThrowsOnWriteWhenOverridenCreateFails() { // Arrange TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter(); @@ -333,7 +340,7 @@ public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateFails() } [Fact] - public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateReturnsNull() + public async Task XmlSerializerFormatterThrowsOnWriteWhenOverridenCreateReturnsNull() { // Arrange TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter(); @@ -353,7 +360,7 @@ public async Task DataContractFormatterThrowsOnWriteWhenOverridenCreateReturnsNu } [Fact] - public async Task DataContractFormatterThrowsOnReadWhenOverridenCreateFails() + public async Task XmlSerializerFormatterThrowsOnReadWhenOverridenCreateFails() { // Arrange TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter(); @@ -375,7 +382,7 @@ public async Task DataContractFormatterThrowsOnReadWhenOverridenCreateFails() } [Fact] - public async Task DataContractFormatterThrowsOnReadWhenOverridenCreateReturnsNull() + public async Task XmlSerializerFormatterThrowsOnReadWhenOverridenCreateReturnsNull() { // Arrange TestXmlMediaTypeFormatter formatter = new TestXmlMediaTypeFormatter(); @@ -484,7 +491,55 @@ public async Task ReadFromStream_AsyncRoundTripsWriteToStreamUsingDataContractSe } } -#if !NETCOREAPP2_0 // DBNull not serializable on .NET Core 2.0. +#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. + [Theory] + [TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection", RoundTripDataVariations)] + public async Task ReadFromStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData) + { + // Arrange. First, get some data using XmlSerializer. + bool canSerialize = IsSerializableWithXmlSerializer(variationType, testData) && Assert.Http.CanRoundTrip(variationType); + if (canSerialize) + { + var formatter = new XmlMediaTypeFormatter() { UseXmlSerializer = true }; + using var stream = new MemoryStream(); + using var content = new StringContent(string.Empty); + + await formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null); + await stream.FlushAsync(); + stream.Position = 0L; + + content.Headers.ContentLength = stream.Length; + formatter.RemoveSerializer(variationType); + formatter.UseXmlSerializer = false; + + // Act & Assert + await Assert.ThrowsAsync(() => + formatter.ReadFromStreamAsync(variationType, stream, content, formatterLogger: null), + "Unable to validate types on this platform when UseXmlSerializer is 'false'. Please set " + + "UseXmlSerializer or move to a supported platform, one where the .NET Standard 2.0 assembly " + + "is usable."); + } + } + + [Theory] + [TestDataSet(typeof(CommonUnitTestDataSets), "RepresentativeValueAndRefTypeTestDataCollection", RoundTripDataVariations)] + public async Task WriteToStreamAsync_UsingDataContractSerializer_Throws(Type variationType, object testData) + { + // Arrange + var formatter = new XmlMediaTypeFormatter(); + using var stream = new MemoryStream(); + using var content = new StringContent(string.Empty); + + // Act & Assert + await Assert.ThrowsAsync(() => + formatter.WriteToStreamAsync(variationType, testData, stream, content, transportContext: null), + "Unable to validate types on this platform when UseXmlSerializer is 'false'. Please set " + + "UseXmlSerializer or move to a supported platform, one where the .NET Standard 2.0 assembly " + + "is usable."); + } + +#else +#if !NETCOREAPP2_1 // DBNull not serializable on .NET Core 2.1. [Fact] public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingDataContractSerializer_DBNull() { @@ -520,28 +575,16 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingDataContr public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) { - if (!isDefaultEncoding) - { - // XmlDictionaryReader/Writer only supports utf-8 and 16 - return TaskHelpers.Completed(); - } - // Arrange XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); string formattedContent = "" + content + ""; -#if NETFX_CORE - // We need to supply the xml declaration when compiled in portable library for non utf-8 content - if (String.Equals("utf-16", encoding, StringComparison.OrdinalIgnoreCase)) - { - formattedContent = "" + formattedContent; - } -#endif string mediaType = string.Format("application/xml; charset={0}", encoding); // Act & assert return ReadFromStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding); } +#endif [Fact] public async Task ReadFromStreamAsync_UsesGetDeserializerAndCreateXmlReader() @@ -586,14 +629,9 @@ public Task ReadFromStreamAsync_ThrowsException_WhenGetDeserializerReturnsInvali "The object of type 'JsonSerializer' returned by GetDeserializer must be an instance of either XmlObjectSerializer or XmlSerializer."); } +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) { - if (!isDefaultEncoding) - { - // XmlDictionaryReader/Writer only supports utf-8 and 16 - return TaskHelpers.Completed(); - } - // Arrange XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); string formattedContent = "" + content + @@ -603,6 +641,7 @@ public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string cont // Act & assert return WriteToStreamAsync_UsesCorrectCharacterEncodingHelper(formatter, content, formattedContent, mediaType, encoding, isDefaultEncoding); } +#endif [Fact] public async Task WriteToStreamAsync_UsesGetSerializerAndCreateXmlWriter() @@ -675,6 +714,7 @@ public void Property_WriterSettings_DefaultValues() Assert.False(formatter.WriterSettings.CheckCharacters); } +#if !Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Fact] public async Task InvalidXmlCharacters_CanBeSerialized_Default() { @@ -697,8 +737,38 @@ public Task InvalidXmlCharacters_CannotBeSerialized_IfCheckCharactersIsTrue() () => formatter.WriteToStreamAsync(typeof(string), "\x16", stream, content, null), "'\x16', hexadecimal value 0x16, is an invalid character."); } +#endif + + [Theory] + [PropertyData(nameof(AFewValidTypes))] + public void CanReadType_ReturnsFalse_ForValidTypes(Type type) + { + XmlMediaTypeFormatter formatter = new(); + + var canRead = formatter.CanReadType(type); + +#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation. + Assert.False(canRead); +#else + Assert.True(canRead); +#endif + } + + [Theory] + [PropertyData(nameof(AFewValidTypes))] + public void CanWriteType_ReturnsFalse_ForValidTypes(Type type) + { + XmlMediaTypeFormatter formatter = new(); + + var canWrite = formatter.CanWriteType(type); + +#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation. + Assert.False(canWrite); +#else + Assert.True(canWrite); +#endif + } -#if !NETFX_CORE // Different behavior in portable libraries due to no DataContract validation [Fact] public void CanReadType_ReturnsFalse_ForInvalidDataContracts() { @@ -714,23 +784,66 @@ public void CanWriteType_ReturnsFalse_ForInvalidDataContracts() Assert.False(formatter.CanWriteType(typeof(InvalidDataContract))); } -#else + +#if Testing_NetStandard1_3 // Cannot read or write w/ DCS in netstandard1.3. [Fact] - public void CanReadType_InPortableLibrary_ReturnsFalse_ForInvalidDataContracts() + public override Task Overridden_ReadFromStreamAsyncWithCancellationToken_GetsCalled() { - XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); + return Task.CompletedTask; + } - // The formatter is unable to positively identify non readable types, so true is always returned - Assert.True(formatter.CanReadType(typeof(InvalidDataContract))); + [Fact] + public override Task Overridden_ReadFromStreamAsyncWithoutCancellationToken_GetsCalled() + { + return Task.CompletedTask; } [Fact] - public void CanWriteType_InPortableLibrary_ReturnsTrue_ForInvalidDataContracts() + public override Task Overridden_WriteToStreamAsyncWithCancellationToken_GetsCalled() { - XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); + return Task.CompletedTask; + } + + [Fact] + public override Task Overridden_WriteToStreamAsyncWithoutCancellationToken_GetsCalled() + { + return Task.CompletedTask; + } + + [Fact] + public override Task ReadFromStreamAsync_ReadsDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } + + // Attributes are in base class. + public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) + { + return Task.CompletedTask; + } + + [Fact] + public override Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } + + // Attributes are in base class. + public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) + { + return Task.CompletedTask; + } - // The formatter is unable to positively identify non readable types, so true is always returned - Assert.True(formatter.CanWriteType(typeof(InvalidDataContract))); + [Fact] + public override Task WriteToStreamAsync_WhenObjectIsNull_WritesDataButDoesNotCloseStream() + { + return Task.CompletedTask; + } + + [Fact] + public override Task WriteToStreamAsync_WritesDataButDoesNotCloseStream() + { + return Task.CompletedTask; } #endif @@ -828,6 +941,9 @@ private bool IsSerializableWithXmlSerializer(Type type, object obj) private bool IsSerializableWithDataContractSerializer(Type type, object obj) { +#if Testing_NetStandard1_3 // Different behavior in netstandard1.3 due to no DataContract validation. + return false; +#else if (Assert.Http.IsKnownUnserializable(type, obj)) { return false; @@ -847,6 +963,7 @@ private bool IsSerializableWithDataContractSerializer(Type type, object obj) } return true; +#endif } } } diff --git a/test/System.Net.Http.Formatting.Test/Formatting/XmlSerializerMediaTypeFormatterTests.cs b/test/System.Net.Http.Formatting.Test/Formatting/XmlSerializerMediaTypeFormatterTests.cs index 0b48c73ff..865b2be43 100644 --- a/test/System.Net.Http.Formatting.Test/Formatting/XmlSerializerMediaTypeFormatterTests.cs +++ b/test/System.Net.Http.Formatting.Test/Formatting/XmlSerializerMediaTypeFormatterTests.cs @@ -61,9 +61,7 @@ public async Task ReadDeeplyNestedObjectWorks() { XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter() { -#if !NETFX_CORE // We don't support MaxDepth in the portable library MaxDepth = 5001 -#endif }; StringContent content = new StringContent(GetDeeplyNestedObject(5000)); @@ -250,22 +248,9 @@ public async Task ReadFromStreamAsync_RoundTripsWriteToStreamAsyncUsingXmlSerial public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) { - if (!isDefaultEncoding) - { - // XmlDictionaryReader/Writer only supports utf-8 and 16 - return TaskHelpers.Completed(); - } - // Arrange XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter(); string formattedContent = "" + content + ""; -#if NETFX_CORE - if (String.Equals("utf-16", encoding, StringComparison.OrdinalIgnoreCase)) - { - // We need to supply the xml declaration when compiled in portable library for non utf-8 content - formattedContent = "" + formattedContent; - } -#endif string mediaType = string.Format("application/xml; charset={0}", encoding); // Act & assert @@ -274,12 +259,6 @@ public override Task ReadFromStreamAsync_UsesCorrectCharacterEncoding(string con public override Task WriteToStreamAsync_UsesCorrectCharacterEncoding(string content, string encoding, bool isDefaultEncoding) { - if (!isDefaultEncoding) - { - // XmlDictionaryReader/Writer only supports utf-8 and 16 - return TaskHelpers.Completed(); - } - // Arrange XmlSerializerMediaTypeFormatter formatter = new XmlSerializerMediaTypeFormatter(); string formattedContent = "" + content + ""; diff --git a/test/System.Net.Http.Formatting.Test/Handlers/ProgressMessageHandlerTest.cs b/test/System.Net.Http.Formatting.Test/Handlers/ProgressMessageHandlerTest.cs index b7d71b4e5..2984dbd4a 100644 --- a/test/System.Net.Http.Formatting.Test/Handlers/ProgressMessageHandlerTest.cs +++ b/test/System.Net.Http.Formatting.Test/Handlers/ProgressMessageHandlerTest.cs @@ -84,7 +84,8 @@ public async Task SendAsync_InsertsReceiveProgressWhenResponseEntityPresent(bool } else { - Assert.Null(response.Content); + Assert.NotNull(response.Content); + Assert.Equal(0L, response.Content.Headers.ContentLength); } } } @@ -125,16 +126,13 @@ public ShortCircuitMessageHandler(bool includeResponseEntity) protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { -#if NETFX_CORE // Extension method only available on non portable library - HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; -#else HttpResponseMessage response = request.CreateResponse(); -#endif if (_includeResponseEntity) { response.Content = new StringContent("Response Entity"); response.Content.Headers.Add(TestHeader, TestValue); } + return Task.FromResult(response); } } diff --git a/test/System.Net.Http.Formatting.Test/Handlers/ProgressStreamTest.cs b/test/System.Net.Http.Formatting.Test/Handlers/ProgressStreamTest.cs index a6de511b8..0355dcdab 100644 --- a/test/System.Net.Http.Formatting.Test/Handlers/ProgressStreamTest.cs +++ b/test/System.Net.Http.Formatting.Test/Handlers/ProgressStreamTest.cs @@ -66,7 +66,7 @@ public async Task ReadByte_ReportsBytesRead() Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3 [Fact] public async Task BeginEndRead_ReportsBytesRead() { @@ -186,7 +186,7 @@ public void WriteByte_ReportsBytesWritten() Assert.Equal(100, mockProgressEventHandler.EventArgs.ProgressPercentage); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3 [Fact] public void BeginEndWrite_ReportsBytesWritten() { @@ -274,7 +274,7 @@ internal static ProgressStream CreateProgressStream( Stream iStream = innerStream ?? new Mock().Object; ProgressMessageHandler pHandler = progressMessageHandler ?? new ProgressMessageHandler(); HttpRequestMessage req = request ?? new HttpRequestMessage(); - HttpResponseMessage rsp = response ?? new HttpResponseMessage(); + HttpResponseMessage rsp = response ?? new HttpResponseMessage() { Content = new StreamContent(Stream.Null) }; return new ProgressStream(iStream, pHandler, req, rsp); } diff --git a/test/System.Net.Http.Formatting.Test/Headers/CookieStateTest.cs b/test/System.Net.Http.Formatting.Test/Headers/CookieStateTest.cs index a00af171c..68383c238 100644 --- a/test/System.Net.Http.Formatting.Test/Headers/CookieStateTest.cs +++ b/test/System.Net.Http.Formatting.Test/Headers/CookieStateTest.cs @@ -29,19 +29,21 @@ public static TheoryDataSet EncodedCookieStateStrings { get { - return new TheoryDataSet + TheoryDataSet data = new TheoryDataSet { - { "?", "%3f" }, - { "=", "%3d" }, - { "", "%3cacb%3e" }, - { "{acb}", "%7bacb%7d" }, - { "[acb]", "%5bacb%5d" }, + { "?", "%3F" }, + { "=", "%3D" }, + { "", "%3Cacb%3E" }, + { "{acb}", "%7Bacb%7D" }, + { "[acb]", "%5Bacb%5D" }, { "\"acb\"", "%22acb%22" }, - { "a,b", "a%2cb" }, - { "a;b", "a%3bb" }, - { "a\\b", "a%5cb" }, - { "[]{}\\|!@#$%^&*()_-+=", "%5b%5d%7b%7d%5c%7c!%40%23%24%25%5e%26*()_-%2b%3d" }, + { "a,b", "a%2Cb" }, + { "a;b", "a%3Bb" }, + { "a\\b", "a%5Cb" }, + { "[]{}\\|!@#$%^&*()_-+=", "%5B%5D%7B%7D%5C%7C!%40%23%24%25%5E%26*()_-%2B%3D" }, }; + + return data; } } diff --git a/test/System.Net.Http.Formatting.Test/HttpClientExtensionsTest.cs b/test/System.Net.Http.Formatting.Test/HttpClientExtensionsTest.cs index a12ab0383..2e6dc1d73 100644 --- a/test/System.Net.Http.Formatting.Test/HttpClientExtensionsTest.cs +++ b/test/System.Net.Http.Formatting.Test/HttpClientExtensionsTest.cs @@ -14,6 +14,12 @@ namespace System.Net.Http { public class HttpClientExtensionsTest { + private const string InvalidUriMessage = +#if NET6_0_OR_GREATER + "An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set."; +#else + "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."; +#endif private readonly MediaTypeFormatter _formatter = new MockMediaTypeFormatter { CallBase = true }; private readonly HttpClient _client; private readonly MediaTypeHeaderValue _mediaTypeHeader = MediaTypeHeaderValue.Parse("foo/bar; charset=utf-16"); @@ -40,7 +46,7 @@ public void PostAsJsonAsync_String_WhenClientIsNull_ThrowsException() public void PostAsJsonAsync_String_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PostAsJsonAsync((string)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -60,11 +66,12 @@ public void PostAsXmlAsync_String_WhenClientIsNull_ThrowsException() Assert.ThrowsArgumentNull(() => client.PostAsXmlAsync("http://www.example.com", new object()), "client"); } +#if !Testing_NetStandard1_3 // Avoid "The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'." [Fact] public void PostAsXmlAsync_String_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PostAsXmlAsync((string)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -75,6 +82,7 @@ public async Task PostAsXmlAsync_String_UsesXmlMediaTypeFormatter() var content = Assert.IsType>(response.RequestMessage.Content); Assert.IsType(content.Formatter); } +#endif [Fact] public void PostAsync_String_WhenClientIsNull_ThrowsException() @@ -88,7 +96,7 @@ public void PostAsync_String_WhenClientIsNull_ThrowsException() public void PostAsync_String_WhenRequestUriIsNull_ThrowsException() { Assert.Throws(() => _client.PostAsync((string)null, new object(), new JsonMediaTypeFormatter(), "text/json"), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -169,7 +177,7 @@ public void PutAsJsonAsync_String_WhenClientIsNull_ThrowsException() public void PutAsJsonAsync_String_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PutAsJsonAsync((string)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -189,11 +197,12 @@ public void PutAsXmlAsync_String_WhenClientIsNull_ThrowsException() Assert.ThrowsArgumentNull(() => client.PutAsXmlAsync("http://www.example.com", new object()), "client"); } +#if !Testing_NetStandard1_3 // Avoid "The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'." [Fact] public void PutAsXmlAsync_String_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PutAsXmlAsync((string)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -204,6 +213,7 @@ public async Task PutAsXmlAsync_String_UsesXmlMediaTypeFormatter() var content = Assert.IsType>(response.RequestMessage.Content); Assert.IsType(content.Formatter); } +#endif [Fact] public void PutAsync_String_WhenClientIsNull_ThrowsException() @@ -217,7 +227,7 @@ public void PutAsync_String_WhenClientIsNull_ThrowsException() public void PutAsync_String_WhenRequestUriIsNull_ThrowsException() { Assert.Throws(() => _client.PutAsync((string)null, new object(), new JsonMediaTypeFormatter(), "text/json"), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -298,7 +308,7 @@ public void PostAsJsonAsync_Uri_WhenClientIsNull_ThrowsException() public void PostAsJsonAsync_Uri_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PostAsJsonAsync((Uri)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -318,11 +328,12 @@ public void PostAsXmlAsync_Uri_WhenClientIsNull_ThrowsException() Assert.ThrowsArgumentNull(() => client.PostAsXmlAsync(new Uri("http://www.example.com"), new object()), "client"); } +#if !Testing_NetStandard1_3 // Avoid "The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'." [Fact] public void PostAsXmlAsync_Uri_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PostAsXmlAsync((Uri)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -333,6 +344,7 @@ public async Task PostAsXmlAsync_Uri_UsesXmlMediaTypeFormatter() var content = Assert.IsType>(response.RequestMessage.Content); Assert.IsType(content.Formatter); } +#endif [Fact] public void PostAsync_Uri_WhenClientIsNull_ThrowsException() @@ -346,7 +358,7 @@ public void PostAsync_Uri_WhenClientIsNull_ThrowsException() public void PostAsync_Uri_WhenRequestUriIsNull_ThrowsException() { Assert.Throws(() => _client.PostAsync((Uri)null, new object(), new JsonMediaTypeFormatter(), "text/json"), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -427,7 +439,7 @@ public void PutAsJsonAsync_Uri_WhenClientIsNull_ThrowsException() public void PutAsJsonAsync_Uri_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PutAsJsonAsync((Uri)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -447,11 +459,12 @@ public void PutAsXmlAsync_Uri_WhenClientIsNull_ThrowsException() Assert.ThrowsArgumentNull(() => client.PutAsXmlAsync(new Uri("http://www.example.com"), new object()), "client"); } +#if !Testing_NetStandard1_3 // Avoid "The configured formatter 'System.Net.Http.Formatting.XmlMediaTypeFormatter' cannot write an object of type 'Object'." [Fact] public void PutAsXmlAsync_Uri_WhenUriIsNull_ThrowsException() { Assert.Throws(() => _client.PutAsXmlAsync((Uri)null, new object()), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] @@ -462,6 +475,7 @@ public async Task PutAsXmlAsync_Uri_UsesXmlMediaTypeFormatter() var content = Assert.IsType>(response.RequestMessage.Content); Assert.IsType(content.Formatter); } +#endif [Fact] public void PutAsync_Uri_WhenClientIsNull_ThrowsException() @@ -475,7 +489,7 @@ public void PutAsync_Uri_WhenClientIsNull_ThrowsException() public void PutAsync_Uri_WhenRequestUriIsNull_ThrowsException() { Assert.Throws(() => _client.PutAsync((Uri)null, new object(), new JsonMediaTypeFormatter(), "text/json"), - "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."); + InvalidUriMessage); } [Fact] diff --git a/test/System.Net.Http.Formatting.Test/HttpContentFormDataExtensionsTest.cs b/test/System.Net.Http.Formatting.Test/HttpContentFormDataExtensionsTest.cs index d82bc3687..cf787bf37 100644 --- a/test/System.Net.Http.Formatting.Test/HttpContentFormDataExtensionsTest.cs +++ b/test/System.Net.Http.Formatting.Test/HttpContentFormDataExtensionsTest.cs @@ -8,9 +8,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.TestCommon; -#if NETFX_CORE -using NameValueCollection = System.Net.Http.Formatting.HttpValueCollection; -#endif namespace System.Net.Http { diff --git a/test/System.Net.Http.Formatting.Test/HttpContentMessageExtensionsTests.cs b/test/System.Net.Http.Formatting.Test/HttpContentMessageExtensionsTests.cs index 27273e4f2..7003cdbd5 100644 --- a/test/System.Net.Http.Formatting.Test/HttpContentMessageExtensionsTests.cs +++ b/test/System.Net.Http.Formatting.Test/HttpContentMessageExtensionsTests.cs @@ -482,16 +482,50 @@ public Task ReadAsHttpResponseMessageAsync_LargeHeaderSize() } [Fact] - public Task ReadAsHttpRequestMessageAsync_LargeHeaderSize() + public async Task ReadAsHttpRequestMessageAsync_LargeHeaderSize() { + string cookieValue = string.Format("{0}={1}", new String('a', 16 * 1024), new String('b', 16 * 1024)); string[] request = new[] { @"GET / HTTP/1.1", @"Host: msdn.microsoft.com", - String.Format("Cookie: {0}={1}", new String('a', 16 * 1024), new String('b', 16 * 1024)) + string.Format("Cookie: {0}", cookieValue), + }; + + HttpContent content = CreateContent(true, request, "sample body"); + var httpRequestMessage = await content.ReadAsHttpRequestMessageAsync(Uri.UriSchemeHttp, 64 * 1024, 64 * 1024); + + Assert.Equal(HttpMethod.Get, httpRequestMessage.Method); + Assert.Equal("/", httpRequestMessage.RequestUri.PathAndQuery); + Assert.Equal("msdn.microsoft.com", httpRequestMessage.Headers.Host); + IEnumerable actualCookieValue; + Assert.True(httpRequestMessage.Headers.TryGetValues("Cookie", out actualCookieValue)); + Assert.Equal(cookieValue, Assert.Single(actualCookieValue)); + } + + [Fact] + public async Task ReadAsHttpRequestMessageAsync_LargeHttpRequestLine() + { + string requestPath = string.Format("/myurl?{0}={1}", new string('a', 4 * 1024), new string('b', 4 * 1024)); + string cookieValue = string.Format("{0}={1}", new String('a', 4 * 1024), new String('b', 4 * 1024)); + string[] request = new[] + { + string.Format("GET {0} HTTP/1.1", requestPath), + @"Host: msdn.microsoft.com", + string.Format("Cookie: {0}", cookieValue), }; HttpContent content = CreateContent(true, request, "sample body"); - return content.ReadAsHttpRequestMessageAsync(Uri.UriSchemeHttp, 64 * 1024, 64 * 1024); + var httpRequestMessage = await content.ReadAsHttpRequestMessageAsync( + Uri.UriSchemeHttp, + bufferSize: 64 * 1024, + maxHeaderSize: 64 * 1024); + + Assert.Equal(HttpMethod.Get, httpRequestMessage.Method); + Assert.Equal(requestPath, httpRequestMessage.RequestUri.PathAndQuery); + Assert.Equal("msdn.microsoft.com", httpRequestMessage.Headers.Host); + IEnumerable actualCookieValue; + Assert.True(httpRequestMessage.Headers.TryGetValues("Cookie", out actualCookieValue)); + Assert.Equal(cookieValue, Assert.Single(actualCookieValue)); } [Theory] diff --git a/test/System.Net.Http.Formatting.Test/HttpContentMultipartExtensionsTests.cs b/test/System.Net.Http.Formatting.Test/HttpContentMultipartExtensionsTests.cs index 1fc9c1ea8..b9769fa63 100644 --- a/test/System.Net.Http.Formatting.Test/HttpContentMultipartExtensionsTests.cs +++ b/test/System.Net.Http.Formatting.Test/HttpContentMultipartExtensionsTests.cs @@ -444,7 +444,7 @@ public override Task ReadAsync(byte[] buffer, int offset, int count, Cancel throw new IOException(ExceptionAsyncStreamMessage); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new IOException(ExceptionAsyncStreamMessage); @@ -464,7 +464,7 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati throw new IOException(ExceptionAsyncStreamMessage); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new IOException(ExceptionAsyncStreamMessage); diff --git a/test/System.Net.Http.Formatting.Test/HttpMessageContentTests.cs b/test/System.Net.Http.Formatting.Test/HttpMessageContentTests.cs index a8b41b562..4206730b1 100644 --- a/test/System.Net.Http.Formatting.Test/HttpMessageContentTests.cs +++ b/test/System.Net.Http.Formatting.Test/HttpMessageContentTests.cs @@ -1,6 +1,7 @@ // 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.IO; using System.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.TestCommon; @@ -39,28 +40,40 @@ private static HttpResponseMessage CreateResponse(bool containsEntity) httpResponse.ReasonPhrase = ParserData.HttpReasonPhrase; httpResponse.Version = new Version("1.2"); AddMessageHeaders(httpResponse.Headers); - if (containsEntity) - { - httpResponse.Content = new StringContent(ParserData.HttpMessageEntity); - } + httpResponse.Content = + containsEntity ? new StringContent(ParserData.HttpMessageEntity) : new StreamContent(Stream.Null); return httpResponse; } - private static async Task ReadContentAsync(HttpContent content) + private static async Task ReadContentAsync(HttpContent content, bool unBuffered = false) { - await content.LoadIntoBufferAsync(); + if (unBuffered) + { + var stream = new MemoryStream(); + await content.CopyToAsync(stream); + stream.Position = 0L; + + // StreamReader will dispose of the Stream. + using var reader = new StreamReader(stream); + + return await reader.ReadToEndAsync(); + } + else + { + await content.LoadIntoBufferAsync(); - return await content.ReadAsStringAsync(); + return await content.ReadAsStringAsync(); + } } - private static async Task ValidateRequest(HttpContent content, bool containsEntity) + private static async Task ValidateRequest(HttpContent content, bool containsEntity, bool unBuffered = false) { Assert.Equal(ParserData.HttpRequestMediaType, content.Headers.ContentType); long? length = content.Headers.ContentLength; Assert.NotNull(length); - string message = await ReadContentAsync(content); + string message = await ReadContentAsync(content, unBuffered); if (containsEntity) { Assert.Equal(ParserData.HttpRequestWithEntity.Length, length); @@ -73,13 +86,14 @@ private static async Task ValidateRequest(HttpContent content, bool containsEnti } } - private static async Task ValidateResponse(HttpContent content, bool containsEntity) + private static async Task ValidateResponse(HttpContent content, bool containsEntity, bool unBuffered = false) { Assert.Equal(ParserData.HttpResponseMediaType, content.Headers.ContentType); + long? length = content.Headers.ContentLength; Assert.NotNull(length); - string message = await ReadContentAsync(content); + string message = await ReadContentAsync(content, unBuffered); if (containsEntity) { Assert.Equal(ParserData.HttpResponseWithEntity.Length, length); @@ -153,14 +167,16 @@ public async Task SerializeRequestWithExistingHostHeader() Assert.Equal(ParserData.HttpRequestWithHost, message); } - [Fact] - public async Task SerializeRequestMultipleTimes() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SerializeRequestMultipleTimes(bool unBuffered) { - HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false); - HttpMessageContent instance = new HttpMessageContent(request); + HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false); + HttpMessageContent instance = new(request); for (int cnt = 0; cnt < iterations; cnt++) { - await ValidateRequest(instance, false); + await ValidateRequest(instance, containsEntity: false, unBuffered); } } @@ -175,14 +191,16 @@ public async Task SerializeResponse() } } - [Fact] - public async Task SerializeResponseMultipleTimes() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SerializeResponseMultipleTimes(bool unBuffered) { - HttpResponseMessage response = CreateResponse(false); - HttpMessageContent instance = new HttpMessageContent(response); + HttpResponseMessage response = CreateResponse(containsEntity: false); + HttpMessageContent instance = new(response); for (int cnt = 0; cnt < iterations; cnt++) { - await ValidateResponse(instance, false); + await ValidateResponse(instance, containsEntity: false, unBuffered); } } @@ -197,14 +215,16 @@ public async Task SerializeRequestWithEntity() } } - [Fact] - public async Task SerializeRequestWithEntityMultipleTimes() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SerializeRequestWithEntityMultipleTimes(bool unBuffered) { - HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, true); - HttpMessageContent instance = new HttpMessageContent(request); + HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, containsEntity: true); + HttpMessageContent instance = new(request); for (int cnt = 0; cnt < iterations; cnt++) { - await ValidateRequest(instance, true); + await ValidateRequest(instance, containsEntity: true, unBuffered); } } @@ -219,14 +239,16 @@ public async Task SerializeResponseWithEntity() } } - [Fact] - public async Task SerializeResponseWithEntityMultipleTimes() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task SerializeResponseWithEntityMultipleTimes(bool unBuffered) { - HttpResponseMessage response = CreateResponse(true); - HttpMessageContent instance = new HttpMessageContent(response); + HttpResponseMessage response = CreateResponse(containsEntity: true); + HttpMessageContent instance = new(response); for (int cnt = 0; cnt < iterations; cnt++) { - await ValidateResponse(instance, true); + await ValidateResponse(instance, containsEntity: true, unBuffered); } } @@ -303,5 +325,227 @@ public void DisposeInnerHttpResponseMessage() instance.Dispose(); Assert.ThrowsObjectDisposed(() => { response.StatusCode = HttpStatusCode.OK; }, typeof(HttpResponseMessage).FullName); } + + [Fact] + public void Request_ContentLengthNull_IfReadOnlyStream() + { + var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false); + request.Content = new StreamContent(new ReadOnlyStream()); + var instance = new HttpMessageContent(request); + + var length = instance.Headers.ContentLength; + + Assert.Null(length); + } + + [Fact] + public void Response_ContentLengthNull_IfReadOnlyStream() + { + var response = CreateResponse(containsEntity: false); + response.Content = new StreamContent(new ReadOnlyStream()); + var instance = new HttpMessageContent(response); + + var length = instance.Headers.ContentLength; + + Assert.Null(length); + } + + // Also confirms content can be serialized multiple times if either buffered or involves a seekable Stream. + [Theory] + [InlineData(false, true)] + [InlineData(true, false)] + public async Task Request_NoContentLength_IfNotRequested(bool readOnlyStream, bool unBuffered) + { + var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false); + if (readOnlyStream) + { + request.Content = new StreamContent(new ReadOnlyStream()); + } + var instance = new HttpMessageContent(request); + + for (int cnt = 0; cnt < iterations; cnt++) + { + var contentString = await ReadContentAsync(instance, unBuffered); + + Assert.Equal(ParserData.HttpRequest.Replace("Content-Length: 0\r\n", ""), contentString); + } + } + + // Also confirms content can be serialized multiple times if either buffered or involves a seekable Stream. + [Theory] + [InlineData(false, true)] + [InlineData(true, false)] + public async Task Response_NoContentLength_IfNotRequested(bool readOnlyStream, bool unBuffered) + { + var response = CreateResponse(containsEntity: false); + if (readOnlyStream) + { + response.Content = new StreamContent(new ReadOnlyStream()); + } + var instance = new HttpMessageContent(response); + + for (int cnt = 0; cnt < iterations; cnt++) + { + var contentString = await ReadContentAsync(instance, unBuffered); + + Assert.Equal(ParserData.HttpResponse.Replace("Content-Length: 0\r\n", ""), contentString); + } + } + + // Covers the false, false case of Request_NoContentLength_IfNotRequested(...). + [Fact] + public async Task Request_HasContentLength_IfBuffered_EvenIfNotRequested() + { + var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false); + var instance = new HttpMessageContent(request); + for (int cnt = 0; cnt < iterations; cnt++) + { + var contentString = await ReadContentAsync(instance, unBuffered: false); + + Assert.Equal(ParserData.HttpRequest, contentString); + } + } + + // Covers the false, false case of Response_NoContentLength_IfNotRequested(...). + [Fact] + public async Task Response_HasContentLength_IfBuffered_EvenIfNotRequested() + { + var response = CreateResponse(containsEntity: false); + var instance = new HttpMessageContent(response); + for (int cnt = 0; cnt < iterations; cnt++) + { + var contentString = await ReadContentAsync(instance, unBuffered: false); + + Assert.Equal(ParserData.HttpResponse, contentString); + } + } + + // Covers the true, true case of Request_NoContentLength_IfNotRequested(...). + [Fact] + public async Task Request_CannotSerializeMultipleTimes_IfNotBufferedAndNotSeekable() + { + var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false); + request.Content = new StreamContent(new ReadOnlyStream()); + var instance = new HttpMessageContent(request); + + // Act #1 + var contentString = await ReadContentAsync(instance, unBuffered: true); + + // Assert #1 + Assert.Equal(ParserData.HttpRequest.Replace("Content-Length: 0\r\n", ""), contentString); + + // Act #2 + await Assert.ThrowsAsync( + () => ReadContentAsync(instance, unBuffered: true), + "The 'HttpContent' of the 'HttpRequestMessage' has already been read."); + } + + // Covers the true, true case of Response_NoContentLength_IfNotRequested(...). + [Fact] + public async Task Response_CannotSerializeMultipleTimes_IfNotBufferedAndNotSeekable() + { + var response = CreateResponse(containsEntity: false); + response.Content = new StreamContent(new ReadOnlyStream()); + var instance = new HttpMessageContent(response); + + // Act #1 + var contentString = await ReadContentAsync(instance, unBuffered: true); + + // Assert #1 + Assert.Equal(ParserData.HttpResponse.Replace("Content-Length: 0\r\n", ""), contentString); + + // Act #2 + await Assert.ThrowsAsync( + () => ReadContentAsync(instance, unBuffered: true), + "The 'HttpContent' of the 'HttpResponseMessage' has already been read."); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Request_CannotSerialize_IfWriteOnlyStream(bool unBuffered) + { + var request = CreateRequest(ParserData.HttpRequestUri, containsEntity: false); + request.Content = new StreamContent(new WriteOnlyStream()); + var instance = new HttpMessageContent(request); + + await Assert.ThrowsAsync( + () => ReadContentAsync(instance, unBuffered), + "Stream does not support reading."); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Response_CannotSerialize_IfWriteOnlyStream(bool unBuffered) + { + var response = CreateResponse(containsEntity: false); + response.Content = new StreamContent(new WriteOnlyStream()); + var instance = new HttpMessageContent(response); + + await Assert.ThrowsAsync( + () => ReadContentAsync(instance, unBuffered), + "Stream does not support reading."); + } + + // Unlike Stream.Null, this stream does not support seeking. Bit more like (say) a network stream or + // the EmptyReadStream introduced in .NET 5. Note: EmptyReadStream should never be visible to our code + // because HttpContentMessageExtensions and HttpRequestMessageExtensions overwrite + // HttpResponseMessage.Content (or HttpRequestMessage.Content in one case) when creating an instance. + private class ReadOnlyStream : Stream + { + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotImplementedException(); + public override long Position + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } + + public override void Flush() + { + // Do nothing. + } + + public override int Read(byte[] buffer, int offset, int count) => 0; + + public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); + + public override void SetLength(long value) => throw new NotImplementedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotImplementedException(); + } + + // Unlike Stream.Null, this stream does not support seeking. Bit more like (say) a network stream. + private class WriteOnlyStream : Stream + { + public override bool CanRead => false; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotImplementedException(); + public override long Position + { + get => throw new NotImplementedException(); + set => throw new NotImplementedException(); + } + + public override void Flush() + { + // Do nothing. + } + + public override int Read(byte[] buffer, int offset, int count) => throw new NotImplementedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); + + public override void SetLength(long value) => throw new NotImplementedException(); + + public override void Write(byte[] buffer, int offset, int count) + { + // Ignore all parameters and do nothing. + } + } } } diff --git a/test/System.Net.Http.Formatting.Test/HttpRequestHeadersExtensionsTest.cs b/test/System.Net.Http.Formatting.Test/HttpRequestHeadersExtensionsTest.cs index a02eaa6da..b385cb423 100644 --- a/test/System.Net.Http.Formatting.Test/HttpRequestHeadersExtensionsTest.cs +++ b/test/System.Net.Http.Formatting.Test/HttpRequestHeadersExtensionsTest.cs @@ -45,7 +45,7 @@ public static TheoryDataSet CookieMatches new string[] { "adxcs=-", - "ADXCS=si=0%3a1" + "ADXCS=si=0%3A1" } }, { diff --git a/test/System.Net.Http.Formatting.Test/Internal/ByteRangeStreamTest.cs b/test/System.Net.Http.Formatting.Test/Internal/ByteRangeStreamTest.cs index eb193b51a..6e8251778 100644 --- a/test/System.Net.Http.Formatting.Test/Internal/ByteRangeStreamTest.cs +++ b/test/System.Net.Http.Formatting.Test/Internal/ByteRangeStreamTest.cs @@ -303,6 +303,7 @@ public async Task Position_PositionsNextRead() } } +#if !Testing_NetStandard1_3 // BeginX and EndX are not supported on Streams in netstandard1.3 [Theory] [PropertyData("ReadBoundsDataWithLimit")] public void BeginRead_ReadsEffectiveLengthBytes(int from, int to, int innerLength, int effectiveLength) @@ -330,6 +331,7 @@ public void BeginRead_ReadsEffectiveLengthBytes(int from, int to, int innerLengt Assert.Equal(effectiveLength, rangeStream.Position); } } +#endif [Fact] public async Task BeginRead_CanReadAfterLength() diff --git a/test/System.Net.Http.Formatting.Test/Internal/ConcurrentDictionaryTests.cs b/test/System.Net.Http.Formatting.Test/Internal/ConcurrentDictionaryTests.cs index 2294f8ff5..cc08f4d92 100644 --- a/test/System.Net.Http.Formatting.Test/Internal/ConcurrentDictionaryTests.cs +++ b/test/System.Net.Http.Formatting.Test/Internal/ConcurrentDictionaryTests.cs @@ -4,26 +4,10 @@ using System.Collections.Generic; using Microsoft.TestCommon; -#if NETFX_CORE -namespace System.Net.Http.Internal -#else namespace System.Collections.Concurrent -#endif { public class ConcurrentDictionaryTests { -#if NETFX_CORE // This doesn't exist on the ConcurrentDictionary in the full framework - [Fact] - public void IsReadOnly_ReturnsFalse() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act & Assert - Assert.False(dictionary.IsReadOnly); - } -#endif - [Fact] public void ContainsKey_ReturnsFalseWhenKeyIsNotPresent() { @@ -41,7 +25,7 @@ public void ContainsKey_ReturnsTrueWhenKeyIsPresent() ConcurrentDictionary dictionary = new ConcurrentDictionary(); // Act - dictionary.TryAdd(1, 2); + dictionary.TryAdd(1, 2); // Assert Assert.True(dictionary.ContainsKey(1)); @@ -129,211 +113,5 @@ public void AddOrUpdate_UpdatesValueWhenKeyIsPresent() // Assert Assert.Equal(3, result); } - -#if NETFX_CORE - [Fact] - public void Add_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Add(0, 0)); - } - - [Fact] - public void Add_KeyValuePairThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Add(new KeyValuePair(0, 0))); - } - - [Fact] - public void Clear_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Clear()); - } - - [Fact] - public void Contains_KeyValuePairThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Contains(new KeyValuePair(0, 0))); - } - - [Fact] - public void CopyTo_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.CopyTo(new KeyValuePair[1], 1)); - } - - [Fact] - public void GetEnumerator_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.GetEnumerator()); - } - - [Fact] - public void Remove_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Remove(0)); - } - - [Fact] - public void Remove_WithKeyValuePairThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Remove(new KeyValuePair(0, 0))); - } - - [Fact] - public void GetEnumerator_AsEnumerableThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => ((System.Collections.IEnumerable)dictionary).GetEnumerator()); - } - - [Fact] - public void TryGetValue_ReturnsTrueAndValueWhenPresent() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - dictionary.TryAdd(1, -1); - - // Act - int returnedValue; - bool tryResult = dictionary.TryGetValue(1, out returnedValue); - - // Assert - Assert.Equal(-1, returnedValue); - Assert.True(tryResult); - } - - [Fact] - public void TryGetValue_ReturnsFalseAndDefaultWhenMissing() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - dictionary.TryAdd(1, -1); - - // Act - int returnedValue; - bool tryResult = dictionary.TryGetValue(2, out returnedValue); - - // Assert - Assert.Equal(0, returnedValue); - Assert.False(tryResult); - } - - [Fact] - public void TryRemove_ReturnsTrueAndRemovesWhenPresent() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - dictionary.TryAdd(1, -1); - - // Act - int returnedValue; - bool tryResult = dictionary.TryGetValue(1, out returnedValue); - - // Assert - Assert.Equal(-1, returnedValue); - Assert.True(tryResult); - } - - [Fact] - public void TryRemove_ReturnsFalseAndDefaultWhenMissing() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - dictionary.TryAdd(1, -1); - - // Act - int returnedValue; - bool tryResult = dictionary.TryGetValue(2, out returnedValue); - - // Assert - Assert.Equal(0, returnedValue); - Assert.False(tryResult); - } - - [Fact] - public void Count_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Count); - } - - [Fact] - public void GetItem_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary[0]); - } - - [Fact] - public void SetItem_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary[0] = 1); - } - - [Fact] - public void GetKeys_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Keys); - } - - [Fact] - public void GetValues_ThrowsNotImplementedException() - { - // Arrange - ConcurrentDictionary dictionary = new ConcurrentDictionary(); - - // Act/Assert - Assert.Throws(() => dictionary.Values); - } -#endif } } diff --git a/test/System.Net.Http.Formatting.Test/Internal/DelegatingStreamTest.cs b/test/System.Net.Http.Formatting.Test/Internal/DelegatingStreamTest.cs index 70d419804..1ed7db60a 100644 --- a/test/System.Net.Http.Formatting.Test/Internal/DelegatingStreamTest.cs +++ b/test/System.Net.Http.Formatting.Test/Internal/DelegatingStreamTest.cs @@ -141,7 +141,7 @@ public void DelegatingStream_Dispose() mockStream.Dispose(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Once(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Once(), exactParameterMatch: true, args: true); mockInnerStream.Verify(s => s.Close(), Times.Once()); } @@ -156,7 +156,7 @@ public void DelegatingStream_Close() mockStream.Close(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Once(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Once(), exactParameterMatch: true, args: true); mockInnerStream.Verify(s => s.Close(), Times.Once()); } @@ -193,7 +193,7 @@ public void DelegatingStream_Read() mockInnerStream.Verify(s => s.Read(buffer, offset, count), Times.Once()); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3 [Fact] public void DelegatingStream_BeginRead() { @@ -305,7 +305,7 @@ public void DelegatingStream_Write() mockInnerStream.Verify(s => s.Write(buffer, offset, count), Times.Once()); } -#if !NETFX_CORE // BeginX and EndX not supported on Streams in portable libraries +#if !Testing_NetStandard1_3 // BeginX and EndX not supported on Streams in netstandard1.3 [Fact] public void DelegatingStream_BeginWrite() { diff --git a/test/System.Net.Http.Formatting.Test/Internal/HttpValueCollectionTest.cs b/test/System.Net.Http.Formatting.Test/Internal/HttpValueCollectionTest.cs index 8e06557b4..7567e02d2 100644 --- a/test/System.Net.Http.Formatting.Test/Internal/HttpValueCollectionTest.cs +++ b/test/System.Net.Http.Formatting.Test/Internal/HttpValueCollectionTest.cs @@ -4,9 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; -#if !NETFX_CORE using System.Net.Http.Formatting.Internal; -#endif using System.Web.WebPages.TestUtils; using Microsoft.TestCommon; @@ -14,23 +12,21 @@ namespace System.Net.Http.Internal { public class HttpValueCollectionTest { -#if !NETCOREAPP2_0 // Unused on .NET Core 2.0. +#if !NETCOREAPP // Unused on .NET Core. private static readonly int _maxCollectionKeys = 1000; #endif private static HttpValueCollection CreateInstance() { -#if NETFX_CORE - return new HttpValueCollection(); -#else return HttpValueCollection.Create(); -#endif } +#if !NETCOREAPP // Unsupported on .NET Core. private static void RunInIsolation(Action action) { AppDomainUtils.RunInSeparateAppDomain(action); } +#endif public static TheoryDataSet>> KeyValuePairs { @@ -77,11 +73,7 @@ public static TheoryDataSet ToStringTestData hvc4.Add("na me", ""); dataSet.Add(hvc4, "na+me"); -#if NETFX_CORE string encoded5 = "n%22%2C%3B%5Cn"; -#else - string encoded5 = "n%22%2c%3b%5cn"; -#endif var hvc5 = CreateInstance(); hvc5.Add("n\",;\\n", ""); @@ -101,22 +93,14 @@ public static TheoryDataSet ToStringTestData hvc7.Add("n4", "v4"); dataSet.Add(hvc7, "n1=v1&n2=v2&n3=v3&n4=v4"); -#if NETFX_CORE string encoded8 = "n%2C1=v%2C1&n%3B2=v%3B2"; -#else - string encoded8 = "n%2c1=v%2c1&n%3b2=v%3b2"; -#endif var hvc8 = CreateInstance(); hvc8.Add("n,1", "v,1"); hvc8.Add("n;2", "v;2"); dataSet.Add(hvc8, encoded8); -#if NETFX_CORE string encoded9 = "n1=%26&n2=%3B&n3=%26&n4=%2B&n5=%26&n6=%3D&n7=%26"; -#else - string encoded9 = "n1=%26&n2=%3b&n3=%26&n4=%2b&n5=%26&n6=%3d&n7=%26"; -#endif var hvc9 = CreateInstance(); hvc9.Add("n1", "&"); @@ -148,7 +132,7 @@ public void Create_CreatesEmptyCollection() Assert.Empty(nvc); } -#if !NETCOREAPP2_0 // DBNull not serializable on .NET Core 2.0. +#if !NETCOREAPP // Able to run on a separate AppDomain only on .NET Framework. // This set of tests requires running on a separate appdomain so we don't // touch the static property MediaTypeFormatter.MaxHttpCollectionKeys. [Fact] @@ -266,14 +250,8 @@ public void Create_InitializesCorrectly(IEnumerable string expectedKey = kvp.Key ?? String.Empty; string expectedValue = kvp.Value ?? String.Empty; -#if NETFX_CORE - KeyValuePair actualKvp = nvc.List[index]; - string actualKey = actualKvp.Key; - string actualValue = actualKvp.Value; -#else string actualKey = nvc.AllKeys[index]; string actualValue = nvc[index]; -#endif index++; Assert.Equal(expectedKey, actualKey); diff --git a/test/System.Net.Http.Formatting.Test/Internal/NonClosingDelegatingStreamTest.cs b/test/System.Net.Http.Formatting.Test/Internal/NonClosingDelegatingStreamTest.cs index fa73637b9..838dc8634 100644 --- a/test/System.Net.Http.Formatting.Test/Internal/NonClosingDelegatingStreamTest.cs +++ b/test/System.Net.Http.Formatting.Test/Internal/NonClosingDelegatingStreamTest.cs @@ -22,7 +22,7 @@ public void NonClosingDelegatingStream_Dispose() mockStream.Dispose(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Never(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Never(), exactParameterMatch: true, args: true); mockInnerStream.Verify(s => s.Close(), Times.Never()); } @@ -37,7 +37,7 @@ public void NonClosingDelegatingStream_Close() mockStream.Close(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Never(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Never(), exactParameterMatch: true, args: true); mockInnerStream.Verify(s => s.Close(), Times.Never()); } } diff --git a/test/System.Net.Http.Formatting.Test/Internal/ReadOnlyStreamWithEncodingPreambleTest.cs b/test/System.Net.Http.Formatting.Test/Internal/ReadOnlyStreamWithEncodingPreambleTest.cs deleted file mode 100644 index fc7fa40ac..000000000 --- a/test/System.Net.Http.Formatting.Test/Internal/ReadOnlyStreamWithEncodingPreambleTest.cs +++ /dev/null @@ -1,75 +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.IO; -using System.Reflection; -using System.Text; -using Microsoft.TestCommon; - -namespace System.Net.Http.Internal -{ - public class ReadOnlyStreamWithEncodingPreambleTest - { - [Theory] - [EncodingData] - public void StreamWithoutPreamble(Encoding encoding, bool includePreambleInInputStream) - { - using (MemoryStream inputStream = new MemoryStream()) - { - // Arrange - string message = "Hello, world" + Environment.NewLine // English - + "こんにちは、世界" + Environment.NewLine // Japanese - + "مرحبا، العالم"; // Arabic - - byte[] preamble = encoding.GetPreamble(); - byte[] encodedMessage = encoding.GetBytes(message); - - if (includePreambleInInputStream) - { - inputStream.Write(preamble, 0, preamble.Length); - } - - inputStream.Write(encodedMessage, 0, encodedMessage.Length); - - byte[] expectedBytes = new byte[preamble.Length + encodedMessage.Length]; - preamble.CopyTo(expectedBytes, 0); - encodedMessage.CopyTo(expectedBytes, preamble.Length); - - inputStream.Seek(0, SeekOrigin.Begin); - - using (ReadOnlyStreamWithEncodingPreamble wrapperStream = new ReadOnlyStreamWithEncodingPreamble(inputStream, encoding)) - { - // Act - int totalRead = 0; - byte[] readBuffer = new byte[expectedBytes.Length]; - - while (totalRead < readBuffer.Length) - { - int read = wrapperStream.Read(readBuffer, totalRead, readBuffer.Length - totalRead); - totalRead += read; - - if (read == 0) - break; - } - - // Assert - Assert.Equal(expectedBytes.Length, totalRead); - Assert.Equal(expectedBytes, readBuffer); - Assert.Equal(0, wrapperStream.Read(readBuffer, 0, 1)); // Make sure there are no stray bytes left in the stream - } - } - } - - class EncodingDataAttribute : DataAttribute - { - public override IEnumerable GetData(MethodInfo methodUnderTest, Type[] parameterTypes) - { - return new MatrixTheoryDataSet( - new[] { Encoding.UTF7, Encoding.UTF8, Encoding.BigEndianUnicode, Encoding.Unicode, Encoding.UTF32, Encoding.ASCII }, - new[] { false, true } - ); - } - } - } -} diff --git a/test/System.Net.Http.Formatting.Test/Internal/TranscodingStreamTests.cs b/test/System.Net.Http.Formatting.Test/Internal/TranscodingStreamTests.cs new file mode 100644 index 000000000..c92b43915 --- /dev/null +++ b/test/System.Net.Http.Formatting.Test/Internal/TranscodingStreamTests.cs @@ -0,0 +1,1145 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// From https://github.com/dotnet/runtime/blob/88868b7a781f4e5b9037b8721f30440207a7aa42/src/libraries/System.Text.Encoding/tests/Encoding/TranscodingStreamTests.cs + +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.IO.Pipelines; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.TestCommon; +using Moq; + +#nullable enable annotations + +namespace System.Text.Tests +{ + public class TranscodingStreamTests + { + public static IEnumerable ReadWriteTestBufferLengths + { + get + { + yield return new object[] { 1 }; + yield return new object[] { 4 * 1024 }; + yield return new object[] { 128 * 1024 }; + yield return new object[] { 2 * 1024 * 1024 }; + } + } + +#if Testing_NetStandard1_3 || Testing_NetStandard2_0 // .NET Framework implementation loses track of cancellation token. + [Fact] + public void AsyncMethods_ReturnCanceledTaskIfCancellationTokenTripped() + { + // Arrange + + CancellationTokenSource cts = new(); + CancellationToken expectedCancellationToken = cts.Token; + cts.Cancel(); + + var innerStreamMock = new Mock(MockBehavior.Strict); // only CanRead/CanWrite should ever be invoked + innerStreamMock.Setup(o => o.CanRead).Returns(true); + innerStreamMock.Setup(o => o.CanWrite).Returns(true); + + Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + + // Act & assert + + RunTest(() => transcodingStream.ReadAsync(new byte[0], 0, 0, expectedCancellationToken)); + RunTest(() => transcodingStream.WriteAsync(new byte[0], 0, 0, expectedCancellationToken)); +#if NETCOREAPP || NETSTANDARD2_1 + RunTest(() => transcodingStream.ReadAsync(Memory.Empty, expectedCancellationToken).AsTask()); + RunTest(() => transcodingStream.WriteAsync(ReadOnlyMemory.Empty, expectedCancellationToken).AsTask()); +#endif + + void RunTest(Func callback) + { + Task task = callback(); + Assert.True(task.IsCanceled); + Assert.Equal(expectedCancellationToken, Assert.Throws(() => task.GetAwaiter().GetResult()).CancellationToken); + } + } +#endif + + [Fact] + public void CreateTranscodingStream_InvalidArgs() + { + Assert.ThrowsArgumentNull(() => new TranscodingStream(null, Encoding.UTF8, Encoding.UTF8), "innerStream"); + Assert.ThrowsArgumentNull(() => new TranscodingStream(Stream.Null, null, Encoding.UTF8), "innerEncoding"); + Assert.ThrowsArgumentNull(() => new TranscodingStream(Stream.Null, Encoding.UTF8, null), "thisEncoding"); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void CanRead_DelegatesToInnerStream(bool expectedCanRead) + { + // Arrange + + var innerStreamMock = new Mock(); + innerStreamMock.Setup(o => o.CanRead).Returns(expectedCanRead); + Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + + // Act + + bool actualCanReadBeforeDispose = transcodingStream.CanRead; + transcodingStream.Dispose(); + bool actualCanReadAfterDispose = transcodingStream.CanRead; + + // Assert + + Assert.Equal(expectedCanRead, actualCanReadBeforeDispose); + Assert.False(actualCanReadAfterDispose); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void CanWrite_DelegatesToInnerStream(bool expectedCanWrite) + { + // Arrange + + var innerStreamMock = new Mock(); + innerStreamMock.Setup(o => o.CanWrite).Returns(expectedCanWrite); + Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + + // Act + + bool actualCanWriteBeforeDispose = transcodingStream.CanWrite; + transcodingStream.Dispose(); + bool actualCanWriteAfterDispose = transcodingStream.CanWrite; + + // Assert + + Assert.Equal(expectedCanWrite, actualCanWriteBeforeDispose); + Assert.False(actualCanWriteAfterDispose); + } + + [Fact] + public void Dispose_MakesMostSubsequentOperationsThrow() + { + // Arrange + + MemoryStream innerStream = new(); + Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + + // Act + + transcodingStream.Dispose(); + + // Assert + // For Task/ValueTask-returning methods, we want the exception to be thrown synchronously. + + Assert.False(transcodingStream.CanRead); + Assert.False(transcodingStream.CanSeek); + Assert.False(transcodingStream.CanWrite); + +#if true // Not overriding these and base Stream's BeginXYZ methods check CanXYZ first, throwing NotSupportedException. + Assert.Throws(() => transcodingStream.BeginRead(new byte[0], 0, 0, null, null)); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[0], 0, 0, null, null)); +#else + Assert.Throws(() => transcodingStream.BeginRead(new byte[0], 0, 0, null, null)); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[0], 0, 0, null, null)); +#endif +#if NETCOREAPP || NETSTANDARD2_1 + Assert.Throws(() => transcodingStream.Read(Span.Empty)); + Assert.Throws(() => (object)transcodingStream.ReadAsync(Memory.Empty)); + Assert.Throws(() => transcodingStream.Write(ReadOnlySpan.Empty)); + Assert.Throws(() => (object)transcodingStream.WriteAsync(ReadOnlyMemory.Empty)); +#endif + Assert.Throws(() => transcodingStream.Flush()); + Assert.Throws(() => (object)transcodingStream.FlushAsync()); + Assert.Throws(() => transcodingStream.Read(new byte[0], 0, 0)); + Assert.Throws(() => (object)transcodingStream.ReadAsync(new byte[0], 0, 0)); + Assert.Throws(() => transcodingStream.ReadByte()); + Assert.Throws(() => transcodingStream.Write(new byte[0], 0, 0)); + Assert.Throws(() => (object)transcodingStream.WriteAsync(new byte[0], 0, 0)); + Assert.Throws(() => transcodingStream.WriteByte((byte)'x')); + } + + [Fact] + public void Dispose_WithLeaveOpenFalse_DisposesInnerStream() + { + // Sync + + MemoryStream innerStream = new(); + Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: false); + transcodingStream.Dispose(); + transcodingStream.Dispose(); // calling it a second time should no-op + Assert.Throws(() => innerStream.Read(Array.Empty(), 0, 0)); + + // Async + +#if NETCOREAPP3_1_OR_GREATER || NETSTANDARD2_1 + innerStream = new MemoryStream(); + transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: false); + transcodingStream.DisposeAsync().GetAwaiter().GetResult(); + transcodingStream.DisposeAsync().GetAwaiter().GetResult(); // calling it a second time should no-op + Assert.Throws(() => innerStream.Read(Span.Empty)); +#endif + } + + [Fact] + public void Dispose_WithLeaveOpenTrue_DoesNotDisposeInnerStream() + { + // Sync + + MemoryStream innerStream = new(); + Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + transcodingStream.Dispose(); + transcodingStream.Dispose(); // calling it a second time should no-op + innerStream.Read(Array.Empty(), 0, 0); // shouldn't throw + + // Async + +#if NETCOREAPP3_1_OR_GREATER || NETSTANDARD2_1 + innerStream = new MemoryStream(); + transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + transcodingStream.DisposeAsync().GetAwaiter().GetResult(); + transcodingStream.DisposeAsync().GetAwaiter().GetResult(); // calling it a second time should no-op + innerStream.Read(Span.Empty); // shouldn't throw +#endif + } + + // Moq heavily utilizes RefEmit, which does not work on most aot workloads + [Fact] + public void Flush_FlushesInnerStreamButNotDecodedState() + { + // Arrange + + CancellationToken expectedCancellationToken = new CancellationTokenSource().Token; + Task expectedFlushAsyncTask = Task.FromResult("just some task"); + + var innerStreamMock = new Mock() { CallBase = true }; + innerStreamMock.Setup(o => o.FlushAsync(expectedCancellationToken)).Returns(expectedFlushAsyncTask); + Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + + transcodingStream.Write(new byte[] { 0x7A, 0xE0 }, 0, 2); + innerStreamMock.Verify(o => o.Flush(), Times.Never); + innerStreamMock.Verify(o => o.FlushAsync(It.IsAny()), Times.Never); + + // Act & assert - sync flush + + transcodingStream.Flush(); + innerStreamMock.Verify(o => o.Flush(), Times.Once); + innerStreamMock.Verify(o => o.FlushAsync(It.IsAny()), Times.Never); + + // Act & assert - async flush + // This also validates that we flowed the CancellationToken as expected + + Task actualFlushAsyncReturnedTask = transcodingStream.FlushAsync(expectedCancellationToken); + Assert.Same(expectedFlushAsyncTask, actualFlushAsyncReturnedTask); + innerStreamMock.Verify(o => o.Flush(), Times.Once); + innerStreamMock.Verify(o => o.FlushAsync(expectedCancellationToken), Times.Once); + + Assert.Equal("z", Encoding.UTF8.GetString(innerStreamMock.Object.ToArray())); // [ E0 ] shouldn't have been flushed + } + + [Fact] + public void IdenticalInnerAndOuterEncodings_DoesNotActAsPassthrough() + { + // Test read + // [ C0 ] is never a valid UTF-8 byte, should be replaced with U+FFFD + + MemoryStream innerStream = new(new byte[] { 0xC0 }); + Stream transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8); + + Assert.Equal(0xEF, transcodingStream.ReadByte()); + Assert.Equal(0xBF, transcodingStream.ReadByte()); + Assert.Equal(0xBD, transcodingStream.ReadByte()); + Assert.Equal(-1 /* eof */, transcodingStream.ReadByte()); + + // Test write + + innerStream = new MemoryStream(); + transcodingStream = new TranscodingStream(innerStream, Encoding.UTF8, Encoding.UTF8); + transcodingStream.WriteByte(0xC0); + Assert.Equal(new byte[] { 0xEF, 0xBF, 0xBD }, innerStream.ToArray()); + } + + [Theory] + [PropertyData(nameof(ReadWriteTestBufferLengths))] + public void Read_ByteArray(int bufferLength) + { + // Tests TranscodingStream.Read(byte[], int, int) + + byte[] buffer = new byte[bufferLength + 3]; + + RunReadTest((transcodingStream, sink) => + { + int numBytesRead = transcodingStream.Read(buffer, 1, bufferLength); + Assert.True(numBytesRead >= 0); + Assert.True(numBytesRead <= bufferLength); + + sink.Write(buffer, 1, numBytesRead); + return numBytesRead; + }); + } + + [Fact] + public void Read_ByteArray_WithInvalidArgs_Throws() + { + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + + Assert.ThrowsArgumentNull(() => transcodingStream.Read(null, 0, 0), "buffer"); + Assert.Throws(() => transcodingStream.Read(new byte[5], -1, -1)); + Assert.Throws(() => transcodingStream.Read(new byte[5], 3, -1)); + Assert.Throws(() => transcodingStream.Read(new byte[5], 5, 1)); + Assert.Throws(() => transcodingStream.Read(new byte[5], 6, -1)); + Assert.Throws(() => transcodingStream.Read(new byte[5], 6, 0)); + } + + [Fact] + public void Read_ByteByByte() + { + // Tests TranscodingStream.ReadByte + + RunReadTest((transcodingStream, sink) => + { + int value = transcodingStream.ReadByte(); + if (value < 0) + { + return 0; + } + + sink.WriteByte(checked((byte)value)); + return 1; + }); + } + +#if NETCOREAPP || NETSTANDARD2_1 + [Theory] + [PropertyData(nameof(ReadWriteTestBufferLengths))] + public void Read_Span(int bufferLength) + { + // Tests TranscodingStream.Read(Span) + + byte[] buffer = new byte[bufferLength]; + + RunReadTest((transcodingStream, sink) => + { + int numBytesRead = transcodingStream.Read(buffer.AsSpan()); + Assert.True(numBytesRead >= 0); + Assert.True(numBytesRead <= bufferLength); + + sink.Write(buffer.AsSpan(0, numBytesRead)); + return numBytesRead; + }); + } +#endif + + private void RunReadTest(Func callback) + { + MemoryStream sink = new(); + + MemoryStream innerStream = new(); + Stream transcodingStream = new TranscodingStream(innerStream, + innerEncoding: Encoding.UTF8, + thisEncoding: CustomAsciiEncoding); + + // Test with a small string, then test with a large string + + RunOneTestIteration(128); + RunOneTestIteration(10 * 1024 * 1024); + + Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF + + // Now put some invalid data into the inner stream, followed by EOF, and ensure we get U+FFFD back out. + + innerStream.SetLength(0); // reset + innerStream.WriteByte(0xC0); // [ C0 ] is never valid in UTF-8 + innerStream.Position = 0; + + sink.SetLength(0); // reset + int numBytesReadJustNow; + do + { + numBytesReadJustNow = callback(transcodingStream, sink); + Assert.True(numBytesReadJustNow >= 0); + } while (numBytesReadJustNow > 0); + + Assert.Equal("[FFFD]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF + + // Now put some incomplete data into the inner stream, followed by EOF, and ensure we get U+FFFD back out. + + innerStream.SetLength(0); // reset + innerStream.WriteByte(0xC2); // [ C2 ] must be followed by [ 80..BF ] in UTF-8 + innerStream.Position = 0; + + sink.SetLength(0); // reset + do + { + numBytesReadJustNow = callback(transcodingStream, sink); + Assert.True(numBytesReadJustNow >= 0); + } while (numBytesReadJustNow > 0); + + Assert.Equal("[FFFD]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF + + void RunOneTestIteration(int stringLength) + { + sink.SetLength(0); // reset + + string expectedStringContents = GetVeryLongAsciiString(stringLength); + innerStream.SetLength(0); // reset + var bytes = Encoding.UTF8.GetBytes(expectedStringContents); + innerStream.Write(bytes, 0, bytes.Length); + innerStream.Position = 0; + + int numBytesReadJustNow; + do + { + numBytesReadJustNow = callback(transcodingStream, sink); + Assert.True(numBytesReadJustNow >= 0); + } while (numBytesReadJustNow > 0); + + Assert.Equal(expectedStringContents, ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + } + } + + [Fact] + public Task ReadApm() + { + // Tests TranscodingStream.BeginRead / EndRead + + byte[] buffer = new byte[1024 * 1024]; + + return RunReadTestAsync((transcodingStream, cancellationToken, sink) => + { + TaskCompletionSource tcs = new(); + object expectedState = new(); + + try + { + IAsyncResult asyncResult = transcodingStream.BeginRead(buffer, 1, buffer.Length - 2, (asyncResult) => + { + try + { + int numBytesReadJustNow = transcodingStream.EndRead(asyncResult); + Assert.True(numBytesReadJustNow >= 0); + Assert.True(numBytesReadJustNow < buffer.Length - 3); + sink.Write(buffer, 1, numBytesReadJustNow); + tcs.SetResult(numBytesReadJustNow); + } + catch (Exception ex) + { + tcs.SetException(ex); + } + }, expectedState); + Assert.Same(expectedState, asyncResult.AsyncState); + } + catch (Exception ex) + { + tcs.SetException(ex); + } + + return new ValueTask(tcs.Task); + }, + suppressExpectedCancellationTokenAsserts: true); // APM pattern doesn't allow flowing CancellationToken + } + + [Theory] + [PropertyData(nameof(ReadWriteTestBufferLengths))] + public Task ReadAsync_ByteArray(int bufferLength) + { + // Tests TranscodingStream.ReadAsync(byte[], int, int, CancellationToken) + + byte[] buffer = new byte[bufferLength + 3]; + + return RunReadTestAsync(async (transcodingStream, cancellationToken, sink) => + { + int numBytesRead = await transcodingStream.ReadAsync(buffer, 1, bufferLength, cancellationToken); + Assert.True(numBytesRead >= 0); + Assert.True(numBytesRead <= bufferLength); + + sink.Write(buffer, 1, numBytesRead); + return numBytesRead; + }); + } + +#if NETCOREAPP || NETSTANDARD2_1 + [Theory] + [PropertyData(nameof(ReadWriteTestBufferLengths))] + public async Task ReadAsync_Memory(int bufferLength) + { + // Tests TranscodingStream.ReadAsync(Memory, CancellationToken) + + byte[] buffer = new byte[bufferLength]; + + await RunReadTestAsync(async (transcodingStream, cancellationToken, sink) => + { + int numBytesRead = await transcodingStream.ReadAsync(buffer.AsMemory(), cancellationToken); + Assert.True(numBytesRead >= 0); + Assert.True(numBytesRead <= bufferLength); + + sink.Write(buffer.AsSpan(0, numBytesRead)); + return numBytesRead; + }); + } +#endif + + [Fact] + public async Task ReadAsync_LoopsWhenPartialDataReceived() + { + // Validates that the TranscodingStream will loop instead of returning 0 + // if the inner stream read partial data and GetBytes cannot make forward progress. + + using AsyncComms comms = new(); + Stream transcodingStream = new TranscodingStream(comms.ReadStream, Encoding.UTF8, Encoding.UTF8); + + // First, ensure that writing [ C0 ] (always invalid UTF-8) to the stream + // causes the reader to return immediately with fallback behavior. + + byte[] readBuffer = new byte[1024]; + comms.WriteBytes(new byte[] { 0xC0 }); + + int numBytesRead = await transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length); + Assert.Equal(new byte[] { 0xEF, 0xBF, 0xBD }, readBuffer.AsSpan(0, numBytesRead).ToArray()); // fallback substitution + + // Next, ensure that writing [ C2 ] (partial UTF-8, needs more data) to the stream + // causes the reader to asynchronously loop, returning "not yet complete". + + readBuffer = new byte[1024]; + comms.WriteBytes(new byte[] { 0xC2 }); + + var task = transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length); + Assert.False(task.IsCompleted); + comms.WriteBytes(new byte[] { 0x80 }); // [ C2 80 ] is valid UTF-8 + + numBytesRead = await task; // should complete successfully + Assert.Equal(new byte[] { 0xC2, 0x80 }, readBuffer.AsSpan(0, numBytesRead).ToArray()); + + // Finally, ensure that writing [ C2 ] (partial UTF-8, needs more data) to the stream + // followed by EOF causes the reader to perform substitution before returning EOF. + + readBuffer = new byte[1024]; + comms.WriteBytes(new byte[] { 0xC2 }); + + task = transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length); + Assert.False(task.IsCompleted); + comms.WriteEof(); + + numBytesRead = await task; // should complete successfully + Assert.Equal(new byte[] { 0xEF, 0xBF, 0xBD }, readBuffer.AsSpan(0, numBytesRead).ToArray()); // fallback substitution + + // Next call really should return "EOF reached" + + readBuffer = new byte[1024]; + Assert.Equal(0, await transcodingStream.ReadAsync(readBuffer, 0, readBuffer.Length)); + } + + [Fact] + public void ReadAsync_WithInvalidArgs_Throws() + { + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + + Assert.ThrowsArgumentNull(() => { transcodingStream.ReadAsync(null, 0, 0); }, "buffer"); + Assert.Throws(() => (object)transcodingStream.ReadAsync(new byte[5], -1, -1)); + Assert.Throws(() => (object)transcodingStream.ReadAsync(new byte[5], 3, -1)); + Assert.Throws(() => (object)transcodingStream.ReadAsync(new byte[5], 5, 1)); + Assert.Throws(() => (object)transcodingStream.ReadAsync(new byte[5], 6, -1)); + Assert.Throws(() => (object)transcodingStream.ReadAsync(new byte[5], 6, 0)); + } + + [Fact] + public void ReadApm_WithInvalidArgs_ThrowsAsync() + { + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + +#if true + // Not overriding BeginRead and base Stream's method returns a Task as its IAsyncResult, delaying parameter checks. + Assert.ThrowsArgumentNull(() => transcodingStream.EndRead(transcodingStream.BeginRead(null, 0, 0, null, null)), "buffer"); + Assert.Throws(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], -1, -1, null, null))); + Assert.Throws(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 3, -1, null, null))); + Assert.Throws(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 5, 1, null, null))); + Assert.Throws(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 6, -1, null, null))); + Assert.Throws(() => transcodingStream.EndRead(transcodingStream.BeginRead(new byte[5], 6, 0, null, null))); +#else + Assert.ThrowsArgumentNull(() => transcodingStream.BeginRead(null, 0, 0, null, null), "buffer"); + Assert.Throws(() => transcodingStream.BeginRead(new byte[5], -1, -1, null, null)); + Assert.Throws(() => transcodingStream.BeginRead(new byte[5], 3, -1, null, null)); + Assert.Throws(() => transcodingStream.BeginRead(new byte[5], 5, 1, null, null)); + Assert.Throws(() => transcodingStream.BeginRead(new byte[5], 6, -1, null, null)); + Assert.Throws(() => transcodingStream.BeginRead(new byte[5], 6, 0, null, null)); +#endif + } + + private async Task RunReadTestAsync(Func> callback, bool suppressExpectedCancellationTokenAsserts = false) + { + CancellationToken expectedCancellationToken = new CancellationTokenSource().Token; + MemoryStream sink = new(); + MemoryStream innerStream = new(); + + var delegatingInnerStreamMock = new Mock(MockBehavior.Strict); + delegatingInnerStreamMock.Setup(o => o.CanRead).Returns(true); + + // Needed for ReadByte calls. + delegatingInnerStreamMock.Setup(o => o.Read(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(innerStream.Read); + +#if true // In current src/ projects, always pass byte array to inner Stream. + if (suppressExpectedCancellationTokenAsserts) + { + delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(innerStream.ReadAsync); + } + else + { + delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny(), It.IsAny(), It.IsAny(), expectedCancellationToken)) + .Returns(innerStream.ReadAsync); + } +#else + if (suppressExpectedCancellationTokenAsserts) + { + delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny>(), It.IsAny())) + .Returns, CancellationToken>(innerStream.ReadAsync); + } + else + { + delegatingInnerStreamMock.Setup(o => o.ReadAsync(It.IsAny>(), expectedCancellationToken)) + .Returns, CancellationToken>(innerStream.ReadAsync); + } +#endif + + Stream transcodingStream = new TranscodingStream( + innerStream: delegatingInnerStreamMock.Object, + innerEncoding: Encoding.UTF8, + thisEncoding: CustomAsciiEncoding); + + // Test with a small string, then test with a large string + + await RunOneTestIteration(128); + await RunOneTestIteration(10 * 1024 * 1024); + + Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF + + // Now put some invalid data into the inner stream, followed by EOF, and ensure we get U+FFFD back out. + + innerStream.SetLength(0); // reset + innerStream.WriteByte(0xC0); // [ C0 ] is never valid in UTF-8 + innerStream.Position = 0; + + sink.SetLength(0); // reset + int numBytesReadJustNow; + do + { + numBytesReadJustNow = await callback(transcodingStream, expectedCancellationToken, sink); + Assert.True(numBytesReadJustNow >= 0); + } while (numBytesReadJustNow > 0); + + Assert.Equal("[FFFD]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF + + // Now put some incomplete data into the inner stream, followed by EOF, and ensure we get U+FFFD back out. + + innerStream.SetLength(0); // reset + innerStream.WriteByte(0xC2); // [ C2 ] must be followed by [ 80..BF ] in UTF-8 + innerStream.Position = 0; + + sink.SetLength(0); // reset + do + { + numBytesReadJustNow = await callback(transcodingStream, expectedCancellationToken, sink); + Assert.True(numBytesReadJustNow >= 0); + } while (numBytesReadJustNow > 0); + + Assert.Equal("[FFFD]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + Assert.Equal(-1, transcodingStream.ReadByte()); // should've reached EOF + + async Task RunOneTestIteration(int stringLength) + { + sink.SetLength(0); // reset + + string expectedStringContents = GetVeryLongAsciiString(stringLength); + innerStream.SetLength(0); // reset + var bytes = Encoding.UTF8.GetBytes(expectedStringContents); + innerStream.Write(bytes, 0, bytes.Length); + innerStream.Position = 0; + + int numBytesReadJustNow; + do + { + numBytesReadJustNow = await callback(transcodingStream, expectedCancellationToken, sink); + Assert.True(numBytesReadJustNow >= 0); + } while (numBytesReadJustNow > 0); + + Assert.Equal(expectedStringContents, ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + } + } + + [Fact] + public void ReadTimeout_WriteTimeout_NotSupported() + { + // Arrange - allow inner stream to support ReadTimeout + WriteTimeout + + var innerStreamMock = new Mock(); + innerStreamMock.SetupProperty(o => o.ReadTimeout); + innerStreamMock.SetupProperty(o => o.WriteTimeout); + Stream transcodingStream = new TranscodingStream(Stream.Null, Encoding.UTF8, Encoding.UTF8, leaveOpen: true); + + // Act & assert - TranscodingStream shouldn't support ReadTimeout + WriteTimeout + + Assert.False(transcodingStream.CanTimeout); + Assert.Throws(() => transcodingStream.ReadTimeout); + Assert.Throws(() => transcodingStream.ReadTimeout = 42); + Assert.Throws(() => transcodingStream.WriteTimeout); + Assert.Throws(() => transcodingStream.WriteTimeout = 42); + } + + [Fact] + public void Seek_AlwaysThrows() + { + // MemoryStream is seekable, but we're not + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + + Assert.False(transcodingStream.CanSeek); + Assert.Throws(() => transcodingStream.Length); + Assert.Throws(() => transcodingStream.Position); + Assert.Throws(() => transcodingStream.Position = 0); + Assert.Throws(() => transcodingStream.Seek(0, SeekOrigin.Current)); + Assert.Throws(() => transcodingStream.SetLength(0)); + } + + [Fact] + public void Write() + { + MemoryStream innerStream = new(); + Stream transcodingStream = new TranscodingStream( + innerStream, + innerEncoding: ErrorCheckingUnicodeEncoding /* throws on error */, + thisEncoding: Encoding.UTF8 /* performs substitution */, + leaveOpen: true); + + // First, test Write(byte[], int, int) + + transcodingStream.Write(Encoding.UTF8.GetBytes("abcdefg"), 2, 3); + Assert.Equal("cde", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray())); + + // Then test WriteByte(byte) + + transcodingStream.WriteByte((byte)'z'); + Assert.Equal("cdez", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray())); + + // We'll write U+00E0 (utf-8: [C3 A0]) byte-by-byte. + // We shouldn't flush any intermediate bytes. + + transcodingStream.WriteByte((byte)0xC3); + Assert.Equal("cdez", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray())); + + transcodingStream.WriteByte((byte)0xA0); + Assert.Equal("cdez\u00E0", ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray())); + + innerStream.SetLength(0); // reset inner stream + + // Then test Write(ROS), once with a short string and once with a long string + + string asciiString = GetVeryLongAsciiString(128); + byte[] asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString); + transcodingStream.Write(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length); + Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray())); + + innerStream.SetLength(0); // reset inner stream + + asciiString = GetVeryLongAsciiString(16 * 1024 * 1024); + asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString); + transcodingStream.Write(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length); + Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(innerStream.ToArray())); + + innerStream.SetLength(0); // reset inner stream + + // Close the outer stream and ensure no leftover data was written to the inner stream + + transcodingStream.Close(); + Assert.Equal(0, innerStream.Position); + } + + [Fact] + public void Write_WithPartialData() + { + MemoryStream innerStream = new(); + Stream transcodingStream = new TranscodingStream( + innerStream, + innerEncoding: CustomAsciiEncoding /* performs custom substitution */, + thisEncoding: Encoding.UTF8 /* performs U+FFFD substitution */, + leaveOpen: true); + + // First, write some incomplete data + + transcodingStream.Write(new byte[] { 0x78, 0x79, 0x7A, 0xC3 }, 0, 4); // [C3] shouldn't be flushed yet + Assert.Equal("xyz", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray())); + + // Flushing should have no effect + + transcodingStream.Flush(); + Assert.Equal("xyz", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray())); + + // Provide the second byte of the multi-byte sequence + + transcodingStream.WriteByte(0xA0); // [C3 A0] = U+00E0 + Assert.Equal("xyz[00E0]", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray())); + + // Provide an incomplete sequence, then close the stream. + // Closing the stream should flush the underlying buffers and write the replacement char. + + transcodingStream.Write(new byte[] { 0xE0, 0xBF }, 0, 1); // first 2 bytes of incomplete 3-byte sequence + Assert.Equal("xyz[00E0]", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray())); // wasn't flushed yet + + transcodingStream.Close(); + Assert.Equal("xyz[00E0][FFFD]", ErrorCheckingAsciiEncoding.GetString(innerStream.ToArray())); + } + + [Fact] + public void Write_WithInvalidArgs_Throws() + { + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + + Assert.ThrowsArgumentNull(() => transcodingStream.Write(null, 0, 0), "buffer"); + Assert.Throws(() => transcodingStream.Write(new byte[5], -1, -1)); + Assert.Throws(() => transcodingStream.Write(new byte[5], 3, -1)); + Assert.Throws(() => transcodingStream.Write(new byte[5], 5, 1)); + Assert.Throws(() => transcodingStream.Write(new byte[5], 6, -1)); + Assert.Throws(() => transcodingStream.Write(new byte[5], 6, 0)); + } + + // Moq heavily utilizes RefEmit, which does not work on most aot workloads + [Fact] + public async Task WriteAsync_WithFullData() + { + MemoryStream sink = new(); + CancellationToken expectedFlushAsyncCancellationToken = new CancellationTokenSource().Token; + CancellationToken expectedWriteAsyncCancellationToken = new CancellationTokenSource().Token; + + var innerStreamMock = new Mock(MockBehavior.Strict); + innerStreamMock.Setup(o => o.CanWrite).Returns(true); +#if true // In current src/ projects, always pass byte array to inner Stream. + innerStreamMock.Setup(o => o.WriteAsync(It.IsAny(), It.IsAny(), It.IsAny(), expectedWriteAsyncCancellationToken)) + .Returns(sink.WriteAsync); +#else + innerStreamMock.Setup(o => o.WriteAsync(It.IsAny>(), expectedWriteAsyncCancellationToken)) + .Returns, CancellationToken>(sink.WriteAsync); +#endif + innerStreamMock.Setup(o => o.FlushAsync(expectedFlushAsyncCancellationToken)).Returns(TaskHelpers.Completed()); + + Stream transcodingStream = new TranscodingStream( + innerStreamMock.Object, + innerEncoding: ErrorCheckingUnicodeEncoding, + thisEncoding: Encoding.UTF8 /* performs U+FFFD substitution */, + leaveOpen: true); + + // First, test WriteAsync(byte[], int, int, CancellationToken) + + await transcodingStream.WriteAsync(Encoding.UTF8.GetBytes("abcdefg"), 2, 3, expectedWriteAsyncCancellationToken); + Assert.Equal("cde", ErrorCheckingUnicodeEncoding.GetString(sink.ToArray())); + + // We'll write U+00E0 (utf-8: [C3 A0]) byte-by-byte. + // We shouldn't flush any intermediate bytes. + + await transcodingStream.WriteAsync(new byte[] { 0xC3, 0xA0 }, 0, 1, expectedWriteAsyncCancellationToken); + await transcodingStream.FlushAsync(expectedFlushAsyncCancellationToken); + Assert.Equal("cde", ErrorCheckingUnicodeEncoding.GetString(sink.ToArray())); + + await transcodingStream.WriteAsync(new byte[] { 0xC3, 0xA0 }, 1, 1, expectedWriteAsyncCancellationToken); + Assert.Equal("cde\u00E0", ErrorCheckingUnicodeEncoding.GetString(sink.ToArray())); + + sink.SetLength(0); // reset sink + + // Then test WriteAsync(ROM, CancellationToken), once with a short string and once with a long string + + string asciiString = GetVeryLongAsciiString(128); + byte[] asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString); + await transcodingStream.WriteAsync(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length, expectedWriteAsyncCancellationToken); + Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(sink.ToArray())); + + sink.SetLength(0); // reset sink + + asciiString = GetVeryLongAsciiString(16 * 1024 * 1024); + asciiBytesAsUtf8 = Encoding.UTF8.GetBytes(asciiString); + await transcodingStream.WriteAsync(asciiBytesAsUtf8, 0, asciiBytesAsUtf8.Length, expectedWriteAsyncCancellationToken); + Assert.Equal(asciiString, ErrorCheckingUnicodeEncoding.GetString(sink.ToArray())); + + sink.SetLength(0); // reset sink + + // Close the outer stream and ensure no leftover data was written to the inner stream + + transcodingStream.Dispose(); + Assert.Equal(0, sink.Position); + } + + // Moq heavily utilizes RefEmit, which does not work on most aot workloads + [Fact] + public async Task WriteAsync_WithPartialData() + { + MemoryStream sink = new(); + CancellationToken expectedCancellationToken = new CancellationTokenSource().Token; + + var innerStreamMock = new Mock(MockBehavior.Strict); + innerStreamMock.Setup(o => o.CanWrite).Returns(true); +#if true // In current src/ projects, always pass byte array to inner Stream. + innerStreamMock.Setup(o => o.WriteAsync(It.IsAny(), It.IsAny(), It.IsAny(), expectedCancellationToken)) + .Returns(sink.WriteAsync); +#else + innerStreamMock.Setup(o => o.WriteAsync(It.IsAny>(), expectedCancellationToken)) + .Returns, CancellationToken>(sink.WriteAsync); +#endif + + Stream transcodingStream = new TranscodingStream( + innerStreamMock.Object, + innerEncoding: CustomAsciiEncoding /* performs custom substitution */, + thisEncoding: Encoding.UTF8 /* performs U+FFFD substitution */, + leaveOpen: true); + + // First, write some incomplete data + + await transcodingStream.WriteAsync(new byte[] { 0x78, 0x79, 0x7A, 0xC3 }, 0, 4, expectedCancellationToken); // [C3] shouldn't be flushed yet + Assert.Equal("xyz", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + + // Provide the second byte of the multi-byte sequence + + await transcodingStream.WriteAsync(new byte[] { 0xA0 }, 0, 1, expectedCancellationToken); // [C3 A0] = U+00E0 + Assert.Equal("xyz[00E0]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + + // Provide an incomplete sequence, then close the stream. + // Closing the stream should flush the underlying buffers and write the replacement char. + + await transcodingStream.WriteAsync(new byte[] { 0xE0, 0xBF }, 0, 2, expectedCancellationToken); // first 2 bytes of incomplete 3-byte sequence + Assert.Equal("xyz[00E0]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); // wasn't flushed yet + + // The call to Dispose() will call innerStream.Write. + + innerStreamMock.Setup(o => o.Write(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback(sink.Write); + transcodingStream.Dispose(); + Assert.Equal("xyz[00E0][FFFD]", ErrorCheckingAsciiEncoding.GetString(sink.ToArray())); + } + + [Fact] + public void WriteAsync_WithInvalidArgs_Throws() + { + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + + Assert.ThrowsArgumentNull(() => { transcodingStream.WriteAsync(null, 0, 0); }, "buffer"); + Assert.Throws(() => (object)transcodingStream.WriteAsync(new byte[5], -1, -1)); + Assert.Throws(() => (object)transcodingStream.WriteAsync(new byte[5], 3, -1)); + Assert.Throws(() => (object)transcodingStream.WriteAsync(new byte[5], 5, 1)); + Assert.Throws(() => (object)transcodingStream.WriteAsync(new byte[5], 6, -1)); + Assert.Throws(() => (object)transcodingStream.WriteAsync(new byte[5], 6, 0)); + } + + // Moq heavily utilizes RefEmit, which does not work on most aot workloads + [Fact] + public void WriteApm() + { + // Arrange + + MemoryStream sink = new(); + object expectedState = new(); + + var innerStreamMock = new Mock(MockBehavior.Strict); + innerStreamMock.Setup(o => o.CanWrite).Returns(true); +#if true // In current src/ projects, base Stream's BeginWrite method relies on Write and passes the byte array to the inner stream. + innerStreamMock.Setup(o => o.Write(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback(sink.Write); +#else + innerStreamMock.Setup(o => o.WriteAsync(It.IsAny>(), CancellationToken.None)) + .Returns, CancellationToken>(sink.WriteAsync); +#endif + + Stream transcodingStream = new TranscodingStream(innerStreamMock.Object, Encoding.UTF8, Encoding.UTF8); + + // Act + + IAsyncResult asyncResult = transcodingStream.BeginWrite(Encoding.UTF8.GetBytes("abcdefg"), 1, 3, null, expectedState); + transcodingStream.EndWrite(asyncResult); + + // Assert + + Assert.Equal(expectedState, asyncResult.AsyncState); + Assert.Equal("bcd", Encoding.UTF8.GetString(sink.ToArray())); + } + + [Fact] + public void WriteApm_WithInvalidArgs_Throws() + { + Stream transcodingStream = new TranscodingStream(new MemoryStream(), Encoding.UTF8, Encoding.UTF8); + +#if true // Not overriding BeginRead and base Stream's method returns a Task as its IAsyncResult, delaying parameter checks. + Assert.ThrowsArgumentNull(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(null, 0, 0, null, null)), "buffer"); + Assert.Throws(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], -1, -1, null, null))); + Assert.Throws(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 3, -1, null, null))); + Assert.Throws(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 5, 1, null, null))); + Assert.Throws(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 6, -1, null, null))); + Assert.Throws(() => transcodingStream.EndWrite(transcodingStream.BeginWrite(new byte[5], 6, 0, null, null))); +#else + Assert.ThrowsArgumentNull(() => transcodingStream.BeginWrite(null, 0, 0, null, null), "buffer"); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[5], -1, -1, null, null)); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[5], 3, -1, null, null)); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[5], 5, 1, null, null)); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[5], 6, -1, null, null)); + Assert.Throws(() => transcodingStream.BeginWrite(new byte[5], 6, 0, null, null)); +#endif + } + + // returns "abc...xyzabc...xyzabc..." + private static string GetVeryLongAsciiString(int length) + { +#if NETCOREAPP || NETSTANDARD2_1 + return string.Create(length, (object)null, (buffer, _) => + { + for (int i = 0; i < buffer.Length; i++) + { + buffer[i] = (char)('a' + (i % 26)); + } + }); +#else + // Somewhat minor that the string just repeats a single character. + return new string('z', length); +#endif + } + + // A custom ASCIIEncoding where both encoder + decoder fallbacks have been specified + private static readonly Encoding CustomAsciiEncoding = Encoding.GetEncoding( + "ascii", new CustomEncoderFallback(), new DecoderReplacementFallback("\uFFFD")); + + private static readonly Encoding ErrorCheckingAsciiEncoding + = Encoding.GetEncoding("ascii", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback); + + private static readonly UnicodeEncoding ErrorCheckingUnicodeEncoding + = new(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true); + + // A custom encoder fallback which substitutes unknown chars with "[xxxx]" (the code point as hex) + private sealed class CustomEncoderFallback : EncoderFallback + { + public override int MaxCharCount => 8; // = "[10FFFF]".Length + + public override EncoderFallbackBuffer CreateFallbackBuffer() + { + return new CustomEncoderFallbackBuffer(); + } + + private sealed class CustomEncoderFallbackBuffer : EncoderFallbackBuffer + { + private string _remaining = string.Empty; + private int _remainingIdx = 0; + + public override int Remaining => _remaining.Length - _remainingIdx; + + public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) + => FallbackCommon((uint)char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); + + public override bool Fallback(char charUnknown, int index) + => FallbackCommon(charUnknown); + + private bool FallbackCommon(uint codePoint) + { + Assert.True(codePoint <= 0x10FFFF); + _remaining = String.Format(CultureInfo.InvariantCulture, "[{0:X4}]", codePoint); + _remainingIdx = 0; + return true; + } + + public override char GetNextChar() + { + return (_remainingIdx < _remaining.Length) + ? _remaining[_remainingIdx++] + : '\0' /* end of string reached */; + } + + public override bool MovePrevious() + { + if (_remainingIdx == 0) + { + return false; + } + + _remainingIdx--; + return true; + } + } + } + + /// A custom encoding that's used to roundtrip from bytes to bytes through a string. + private sealed class IdentityEncoding : Encoding + { + public override int GetByteCount(char[] chars, int index, int count) => count; + + public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) + { + Span span = chars.AsSpan(charIndex, charCount); + for (int i = 0; i < span.Length; i++) + { + Debug.Assert(span[i] <= 0xFF); + bytes[byteIndex + i] = (byte)span[i]; + } + return charCount; + } + + public override int GetCharCount(byte[] bytes, int index, int count) => count; + + public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) + { + Span span = bytes.AsSpan(byteIndex, byteCount); + for (int i = 0; i < span.Length; i++) + { + Debug.Assert(span[i] <= 0xFF); + chars[charIndex + i] = (char)span[i]; + } + return byteCount; + } + + public override int GetMaxByteCount(int charCount) => charCount; + + public override int GetMaxCharCount(int byteCount) => byteCount; + + public override byte[] GetPreamble() => Array.Empty(); + } + + // A helper type that allows synchronously writing to a stream while asynchronously + // reading from it. + private sealed class AsyncComms : IDisposable + { + private readonly BlockingCollection _blockingCollection; + private readonly PipeWriter _writer; + + public AsyncComms() + { + _blockingCollection = new BlockingCollection(); + var pipe = new Pipe(); + ReadStream = pipe.Reader.AsStream(); + _writer = pipe.Writer; + Task.Run(DrainWorker); + } + + public Stream ReadStream { get; } + + public void Dispose() + { + _blockingCollection.Dispose(); + } + + public void WriteBytes(ReadOnlySpan bytes) + { + _blockingCollection.Add(bytes.ToArray()); + } + + public void WriteEof() + { + _blockingCollection.Add(null); + } + + private async Task DrainWorker() + { + byte[] buffer; + while ((buffer = _blockingCollection.Take()) is not null) + { + await _writer.WriteAsync(buffer); + } + _writer.Complete(); + } + } + } +} diff --git a/test/System.Net.Http.Formatting.Test/Mocks/MockDelegatingHandler.cs b/test/System.Net.Http.Formatting.Test/Mocks/MockDelegatingHandler.cs index 2a617479e..013287eda 100644 --- a/test/System.Net.Http.Formatting.Test/Mocks/MockDelegatingHandler.cs +++ b/test/System.Net.Http.Formatting.Test/Mocks/MockDelegatingHandler.cs @@ -40,11 +40,7 @@ protected override Task SendAsync(HttpRequestMessage reques SendAsyncException = new Exception("SendAsync exception"); throw SendAsyncException; } -#if !NETFX_CORE // Extension method only available on non portable library return Task.FromResult(request.CreateResponse()); -#else - return Task.FromResult(new HttpResponseMessage { RequestMessage = request }); -#endif } } } diff --git a/test/System.Net.Http.Formatting.Test/MultipartFileStreamProviderTests.cs b/test/System.Net.Http.Formatting.Test/MultipartFileStreamProviderTests.cs index 6e62bef0e..0cc9c5b7a 100644 --- a/test/System.Net.Http.Formatting.Test/MultipartFileStreamProviderTests.cs +++ b/test/System.Net.Http.Formatting.Test/MultipartFileStreamProviderTests.cs @@ -32,6 +32,7 @@ public class MultipartFileStreamProviderTests : MultipartStreamProviderTestBase< private const int ValidBufferSize = 0x111; private const string ValidPath = @"c:\some\path"; +#if !NETCOREAPP // .NET Core does not enforce path validity in many APIs. public static TheoryDataSet NotSupportedFilePaths { get @@ -44,6 +45,7 @@ public static TheoryDataSet NotSupportedFilePaths }; } } +#endif public static TheoryDataSet InvalidFilePaths { @@ -52,15 +54,17 @@ public static TheoryDataSet InvalidFilePaths return new TheoryDataSet { "", - " ", + " ", " ", - "\t\t \n ", +#if !NETCOREAPP // .NET Core does not enforce path validity in many APIs. + "\t\t \n ", "c:\\ab", "c:\\a\"b", "c:\\a\tb", "c:\\a|b", "c:\\a\bb", +#endif "c:\\a\0b", "c :\\a\0b", }; @@ -73,12 +77,14 @@ public void Constructor_ThrowsOnNullRootPath() Assert.ThrowsArgumentNull(() => { new MultipartFileStreamProvider(null); }, "rootPath"); } +#if !NETCOREAPP // .NET Core does not enforce path validity in many APIs. [Theory] [PropertyData("NotSupportedFilePaths")] public void Constructor_ThrowsOnNotSupportedRootPath(string notSupportedPath) { Assert.Throws(() => new MultipartFileStreamProvider(notSupportedPath, ValidBufferSize)); } +#endif [Theory] [PropertyData("InvalidFilePaths")] diff --git a/test/System.Net.Http.Formatting.Test/ParserData.cs b/test/System.Net.Http.Formatting.Test/ParserData.cs index b0bc1fd19..10c0b3617 100644 --- a/test/System.Net.Http.Formatting.Test/ParserData.cs +++ b/test/System.Net.Http.Formatting.Test/ParserData.cs @@ -198,7 +198,7 @@ public static TheoryDataSet InvalidStatusCodes ((int)HttpStatus).ToString() + " " + HttpReasonPhrase + - "\r\nN1: V1a, V1b, V1c, V1d, V1e\r\nN2: V2\r\n\r\n"; + "\r\nN1: V1a, V1b, V1c, V1d, V1e\r\nN2: V2\r\nContent-Length: 0\r\n\r\n"; public static readonly string HttpRequestWithEntity = HttpMethod + @@ -206,6 +206,7 @@ public static TheoryDataSet InvalidStatusCodes HttpHostName + "\r\nN1: V1a, V1b, V1c, V1d, V1e\r\nN2: V2\r\nContent-Type: " + TextContentType + + "\r\nContent-Length: 100" + "\r\n\r\n" + HttpMessageEntity; @@ -216,6 +217,7 @@ public static TheoryDataSet InvalidStatusCodes HttpReasonPhrase + "\r\nN1: V1a, V1b, V1c, V1d, V1e\r\nN2: V2\r\nContent-Type: " + TextContentType + + "\r\nContent-Length: 100" + "\r\n\r\n" + HttpMessageEntity; } diff --git a/test/System.Net.Http.Formatting.Test/PushStreamContentTest.cs b/test/System.Net.Http.Formatting.Test/PushStreamContentTest.cs index 3edd521b2..9274aaa01 100644 --- a/test/System.Net.Http.Formatting.Test/PushStreamContentTest.cs +++ b/test/System.Net.Http.Formatting.Test/PushStreamContentTest.cs @@ -79,7 +79,7 @@ public async Task SerializeToStreamAsync_CompletesTaskOnActionException() Assert.True(outputStream.CanRead); } -#if NETFX_CORE +#if Testing_NetStandard1_3 [Fact] public async Task CompleteTaskOnCloseStream_Dispose_CompletesTaskButDoNotDisposeInnerStream() { @@ -92,7 +92,7 @@ public async Task CompleteTaskOnCloseStream_Dispose_CompletesTaskButDoNotDispose mockStream.Dispose(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Never(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Never(), exactParameterMatch: true, args: true); Assert.Equal(TaskStatus.RanToCompletion, serializeToStreamTask.Task.Status); Assert.True(await serializeToStreamTask.Task); } @@ -109,7 +109,7 @@ public async Task CompleteTaskOnCloseStream_Dispose_CompletesTaskButDoNotCloseIn mockStream.Dispose(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Never(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Never(), exactParameterMatch: true, args: true); mockInnerStream.Verify(s => s.Close(), Times.Never()); Assert.Equal(TaskStatus.RanToCompletion, serializeToStreamTask.Task.Status); Assert.True(await serializeToStreamTask.Task); @@ -127,7 +127,7 @@ public async Task NonClosingDelegatingStream_Close_CompletesTaskButDoNotCloseInn mockStream.Close(); // Assert - mockInnerStream.Protected().Verify("Dispose", Times.Never(), true); + mockInnerStream.Protected().Verify("Dispose", Times.Never(), exactParameterMatch: true, args: true); mockInnerStream.Verify(s => s.Close(), Times.Never()); Assert.Equal(TaskStatus.RanToCompletion, serializeToStreamTask.Task.Status); Assert.True(await serializeToStreamTask.Task); @@ -222,7 +222,7 @@ public void Action(Stream stream, HttpContent content, TransportContext context) if (_close) { -#if NETFX_CORE +#if Testing_NetStandard1_3 stream.Dispose(); #else stream.Close(); diff --git a/test/System.Net.Http.Formatting.Test/System.Net.Http.Formatting.Test.csproj b/test/System.Net.Http.Formatting.Test/System.Net.Http.Formatting.Test.csproj index 68ba4f630..d8d02cd1e 100644 --- a/test/System.Net.Http.Formatting.Test/System.Net.Http.Formatting.Test.csproj +++ b/test/System.Net.Http.Formatting.Test/System.Net.Http.Formatting.Test.csproj @@ -1,7 +1,7 @@  - - + + {7AF77741-9158-4D5F-8782-8F21FADF025F} @@ -12,161 +12,66 @@ ..\..\bin\$(Configuration)\Test\ + true - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True + + + ..\..\packages\Newtonsoft.Json.Bson.1.0.3\lib\net45\Newtonsoft.Json.Bson.dll True + + ..\..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + False + True + - - - - - - - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + + ..\..\packages\System.IO.Pipelines.4.7.5\lib\net461\System.IO.Pipelines.dll + False True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll + False True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + False True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + False + True + + + + + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - False - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + {668E9021-CE84-49D9-98FB-DF125A9FCDB0} System.Net.Http.Formatting @@ -175,27 +80,32 @@ {FCCC4CB7-BAF7-4A57-9F89-E5766FE536C0} Microsoft.TestCommon - - - Designer - - + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll + True + + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll + True + + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll + True + - - - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.Test/app.config b/test/System.Net.Http.Formatting.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Net.Http.Formatting.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.Test/packages.config b/test/System.Net.Http.Formatting.Test/packages.config index 05cbc07d8..086f5d513 100644 --- a/test/System.Net.Http.Formatting.Test/packages.config +++ b/test/System.Net.Http.Formatting.Test/packages.config @@ -1,14 +1,20 @@  - - - - - - - - - - - + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Net.Http.Formatting.ns1_3.Test/System.Net.Http.Formatting.ns1_3.Test.csproj b/test/System.Net.Http.Formatting.ns1_3.Test/System.Net.Http.Formatting.ns1_3.Test.csproj new file mode 100644 index 000000000..129168a53 --- /dev/null +++ b/test/System.Net.Http.Formatting.ns1_3.Test/System.Net.Http.Formatting.ns1_3.Test.csproj @@ -0,0 +1,45 @@ + + + + net462;netcoreapp2.1;net8.0 + System.Net.Http + ..\..\bin\$(Configuration)\Test\ns1_3\ + $(Configurations);CodeAnalysis + false + $(DefineConstants);Testing_NetStandard1_3 + true + true + + + <_VSRunnerVersion Condition=" '$(TargetFramework)' == 'netcoreapp2.1' ">2.4.3 + <_VSRunnerVersion Condition=" '$(TargetFramework)' != 'netcoreapp2.1' ">2.4.5 + + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + %(RecursiveDir)\%(Filename).cs + + + + + + + + diff --git a/test/System.Net.Http.Formatting.ns2_0.Test/ExceptionAssertionsTest.cs b/test/System.Net.Http.Formatting.ns2_0.Test/ExceptionAssertionsTest.cs new file mode 100644 index 000000000..5204b3f04 --- /dev/null +++ b/test/System.Net.Http.Formatting.ns2_0.Test/ExceptionAssertionsTest.cs @@ -0,0 +1,76 @@ +// 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.Runtime.CompilerServices; +using Xunit; +using Xunit.Sdk; +using TestCommonAssert = Microsoft.TestCommon.Assert; + +namespace System.Net.Http +{ + public class ExceptionAssertionsTest + { + [Fact] + public void Throws_NoException_ReportsFilteredAssertionFailure() + { + var exception = Assert.IsAssignableFrom( + Record.Exception(AssertThrowsWithoutException)); + + Assert.IsAssignableFrom(exception); + Assert.Equal(ThrowsException.ForNoException(typeof(InvalidOperationException)).Message, exception.Message); + Assert.Null(exception.InnerException); + Assert.NotNull(exception.StackTrace); + Assert.Contains(nameof(AssertThrowsWithoutException), exception.StackTrace); + Assert.DoesNotContain("at Microsoft.TestCommon.Assert.", exception.StackTrace); + } + + [Fact] + public void Throws_WrongExceptionType_PreservesInnerExceptionAndOriginalStackTrace() + { + var actual = new InvalidOperationException("Actual exception message"); + var exception = Assert.IsAssignableFrom( + Record.Exception(() => TestCommonAssert.Throws(() => ThrowException(actual)))); + + Assert.IsAssignableFrom(exception); + Assert.Equal(ThrowsException.ForIncorrectExceptionType(typeof(ArgumentException), actual).Message, exception.Message); + Assert.Same(actual, exception.InnerException); + Assert.NotNull(actual.StackTrace); + Assert.Equal(Microsoft.TestCommon.ExceptionUtility.FilterStackTrace(actual.StackTrace), exception.StackTrace); + Assert.Contains(nameof(ThrowException), exception.StackTrace); + Assert.DoesNotContain("at Microsoft.TestCommon.Assert.", exception.StackTrace); + } + + [Fact] + public void Throws_ExpectedExceptionType_ReturnsOriginalException() + { + var expected = new InvalidOperationException(); + + var actual = TestCommonAssert.Throws(() => ThrowException(expected)); + + Assert.Same(expected, actual); + } + + [Fact] + public void Throws_DerivedExceptionType_ReportsAssertionFailure() + { + var actual = new ArgumentNullException("parameter"); + var exception = Assert.IsAssignableFrom( + Record.Exception(() => TestCommonAssert.Throws(() => ThrowException(actual)))); + + Assert.Equal(ThrowsException.ForIncorrectExceptionType(typeof(ArgumentException), actual).Message, exception.Message); + Assert.Same(actual, exception.InnerException); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void AssertThrowsWithoutException() + { + TestCommonAssert.Throws(() => { }); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void ThrowException(Exception exception) + { + throw exception; + } + } +} diff --git a/test/System.Net.Http.Formatting.ns2_0.Test/System.Net.Http.Formatting.ns2_0.Test.csproj b/test/System.Net.Http.Formatting.ns2_0.Test/System.Net.Http.Formatting.ns2_0.Test.csproj new file mode 100644 index 000000000..bf457605c --- /dev/null +++ b/test/System.Net.Http.Formatting.ns2_0.Test/System.Net.Http.Formatting.ns2_0.Test.csproj @@ -0,0 +1,41 @@ + + + + net462;netcoreapp2.1;net8.0 + System.Net.Http + ..\..\bin\$(Configuration)\Test\ns2_0\ + $(Configurations);CodeAnalysis + false + $(DefineConstants);Testing_NetStandard2_0 + true + true + + + <_VSRunnerVersion Condition=" '$(TargetFramework)' == 'netcoreapp2.1' ">2.4.3 + <_VSRunnerVersion Condition=" '$(TargetFramework)' != 'netcoreapp2.1' ">2.4.5 + + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + %(RecursiveDir)\%(Filename).cs + + + + + + + + diff --git a/test/System.Web.Cors.Test/CorsEngineTest.cs b/test/System.Web.Cors.Test/CorsEngineTest.cs index f981c2ae6..0c169e9e0 100644 --- a/test/System.Web.Cors.Test/CorsEngineTest.cs +++ b/test/System.Web.Cors.Test/CorsEngineTest.cs @@ -187,7 +187,7 @@ public void EvaluatePolicy_OneExposedHeaders_HeadersAllowed() CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); - Assert.Equal(1, result.AllowedExposedHeaders.Count); + Assert.Single(result.AllowedExposedHeaders); Assert.Contains("foo", result.AllowedExposedHeaders); } @@ -371,7 +371,7 @@ public void EvaluatePolicy_PreflightRequest_AnyMethod_ReturnsRequestMethod() CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); - Assert.Equal(1, result.AllowedMethods.Count); + Assert.Single(result.AllowedMethods); Assert.Contains("GET", result.AllowedMethods); } @@ -472,7 +472,7 @@ public void EvaluatePolicy_PreflightRequest_HeadersRequested_AllowSomeHeaders_Re CorsResult result = corsEngine.EvaluatePolicy(requestContext, policy); Assert.True(requestContext.IsPreflight); - Assert.Equal(1, result.AllowedHeaders.Count); + Assert.Single(result.AllowedHeaders); Assert.Contains("Content-Type", result.AllowedHeaders); } @@ -544,7 +544,7 @@ public void TryValidateMethod_DoesCaseSensitiveComparison() bool isValid = corsEngine.TryValidateMethod(new CorsRequestContext { AccessControlRequestMethod = "post" }, policy, result); Assert.False(isValid); - Assert.Equal(1, result.ErrorMessages.Count); + Assert.Single(result.ErrorMessages); Assert.Equal("The method 'post' is not allowed.", result.ErrorMessages[0]); } @@ -619,7 +619,7 @@ public void TryValidateOrigin_DoesCaseSensitiveComparison() bool isValid = corsEngine.TryValidateOrigin(new CorsRequestContext { Origin = "http://example.com" }, policy, result); Assert.False(isValid); - Assert.Equal(1, result.ErrorMessages.Count); + Assert.Single(result.ErrorMessages); Assert.Equal("The origin 'http://example.com' is not allowed.", result.ErrorMessages[0]); } } diff --git a/test/System.Web.Cors.Test/System.Web.Cors.Test.csproj b/test/System.Web.Cors.Test/System.Web.Cors.Test.csproj index 62b4ffd51..b86d79e49 100644 --- a/test/System.Web.Cors.Test/System.Web.Cors.Test.csproj +++ b/test/System.Web.Cors.Test/System.Web.Cors.Test.csproj @@ -1,7 +1,7 @@  - - + + Library @@ -14,31 +14,39 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -68,16 +76,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Cors.Test/packages.config b/test/System.Web.Cors.Test/packages.config index b06fb5e7a..842db1984 100644 --- a/test/System.Web.Cors.Test/packages.config +++ b/test/System.Web.Cors.Test/packages.config @@ -1,13 +1,15 @@  - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Helpers.Test/ObjectInfoTest.cs b/test/System.Web.Helpers.Test/ObjectInfoTest.cs index ea38a4540..3fb6dd7f6 100644 --- a/test/System.Web.Helpers.Test/ObjectInfoTest.cs +++ b/test/System.Web.Helpers.Test/ObjectInfoTest.cs @@ -461,7 +461,7 @@ public void PrintCharPrintsQuotedString() printer.VisitConvertedValue('x', "x"); // Assert - Assert.Equal(1, element.Children.Count); + Assert.Single(element.Children); HtmlElement child = element.Children[0]; Assert.Equal("'x'", child.InnerText); Assert.Equal("quote", child["class"]); @@ -479,7 +479,7 @@ public void PrintEscapeCharPrintsEscapedCharAsLiteral() printer.VisitConvertedValue('\t', "\t"); // Assert - Assert.Equal(1, element.Children.Count); + Assert.Single(element.Children); HtmlElement child = element.Children[0]; Assert.Equal("'\\t'", child.InnerText); Assert.Equal("quote", child["class"]); diff --git a/test/System.Web.Helpers.Test/ServerInfoTest.cs b/test/System.Web.Helpers.Test/ServerInfoTest.cs index e0a952436..e02c14deb 100644 --- a/test/System.Web.Helpers.Test/ServerInfoTest.cs +++ b/test/System.Web.Helpers.Test/ServerInfoTest.cs @@ -94,7 +94,7 @@ public void ServerInfoDoesNotProduceLegacyCasForHomogenousAppDomain() IDictionary configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain); Assert.NotNull(configValue); - Assert.Equal(0, configValue.Count); + Assert.Empty(configValue); }; AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: false), action); diff --git a/test/System.Web.Helpers.Test/System.Web.Helpers.Test.csproj b/test/System.Web.Helpers.Test/System.Web.Helpers.Test.csproj index dbb552e83..9974788ad 100644 --- a/test/System.Web.Helpers.Test/System.Web.Helpers.Test.csproj +++ b/test/System.Web.Helpers.Test/System.Web.Helpers.Test.csproj @@ -1,7 +1,7 @@  - - + + {D3313BDF-8071-4AC8-9D98-ABF7F9E88A57} @@ -14,36 +14,44 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -94,16 +102,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Helpers.Test/WebGridTest.cs b/test/System.Web.Helpers.Test/WebGridTest.cs index 2e2b23e1b..e3c3edd3b 100644 --- a/test/System.Web.Helpers.Test/WebGridTest.cs +++ b/test/System.Web.Helpers.Test/WebGridTest.cs @@ -300,7 +300,7 @@ public void PageIndexDefaultsToZero() new { P1 = 4, P2 = '5', P3 = "6" } }); Assert.Equal(0, grid.PageIndex); - Assert.Equal(1, grid.Rows.Count); + Assert.Single(grid.Rows); Assert.Equal(1, grid.Rows.First()["P1"]); } @@ -364,7 +364,7 @@ public void PageIndexResetsToLastPageWhenQueryStringValueGreaterThanPageCount() new { P1 = 4, P2 = '5', P3 = "6" } }); Assert.Equal(1, grid.PageIndex); - Assert.Equal(1, grid.Rows.Count); + Assert.Single(grid.Rows); Assert.Equal(4, grid.Rows.First()["P1"]); } @@ -380,7 +380,7 @@ public void PageIndexResetWhenQueryStringValueIsInvalid() new { P1 = 4, P2 = '5', P3 = "6" } }); Assert.Equal(0, grid.PageIndex); - Assert.Equal(1, grid.Rows.Count); + Assert.Single(grid.Rows); Assert.Equal(1, grid.Rows.First()["P1"]); } @@ -396,7 +396,7 @@ public void PageIndexResetWhenQueryStringValueLessThanOne() new { P1 = 4, P2 = '5', P3 = "6" } }); Assert.Equal(0, grid.PageIndex); - Assert.Equal(1, grid.Rows.Count); + Assert.Single(grid.Rows); Assert.Equal(1, grid.Rows.First()["P1"]); } @@ -412,7 +412,7 @@ public void PageIndexUsesCustomQueryString() new { P1 = 4, P2 = '5', P3 = "6" } }); Assert.Equal(1, grid.PageIndex); - Assert.Equal(1, grid.Rows.Count); + Assert.Single(grid.Rows); Assert.Equal(4, grid.Rows.First()["P1"]); } @@ -428,7 +428,7 @@ public void PageIndexUsesQueryString() new { P1 = 4, P2 = '5', P3 = "6" } }); Assert.Equal(1, grid.PageIndex); - Assert.Equal(1, grid.Rows.Count); + Assert.Single(grid.Rows); Assert.Equal(4, grid.Rows.First()["P1"]); } diff --git a/test/System.Web.Helpers.Test/packages.config b/test/System.Web.Helpers.Test/packages.config index b06fb5e7a..842db1984 100644 --- a/test/System.Web.Helpers.Test/packages.config +++ b/test/System.Web.Helpers.Test/packages.config @@ -1,13 +1,15 @@  - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.Cors.Test/System.Web.Http.Cors.Test.csproj b/test/System.Web.Http.Cors.Test/System.Web.Http.Cors.Test.csproj index 9454da007..15e627e8c 100644 --- a/test/System.Web.Http.Cors.Test/System.Web.Http.Cors.Test.csproj +++ b/test/System.Web.Http.Cors.Test/System.Web.Http.Cors.Test.csproj @@ -1,7 +1,7 @@  - - + + {1E89A3E9-0A7F-418F-B4BE-6E38A6315373} @@ -14,41 +14,49 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True - @@ -98,16 +106,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.Cors.Test/app.config b/test/System.Web.Http.Cors.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.Cors.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.Cors.Test/packages.config b/test/System.Web.Http.Cors.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/System.Web.Http.Cors.Test/packages.config +++ b/test/System.Web.Http.Cors.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.Integration.Test/System.Web.Http.Integration.Test.csproj b/test/System.Web.Http.Integration.Test/System.Web.Http.Integration.Test.csproj index 1a2766741..544f02209 100644 --- a/test/System.Web.Http.Integration.Test/System.Web.Http.Integration.Test.csproj +++ b/test/System.Web.Http.Integration.Test/System.Web.Http.Integration.Test.csproj @@ -1,7 +1,7 @@  - - + + {3267DFC6-B34D-4011-BC0F-D3B56AF6F608} @@ -14,16 +14,16 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -33,25 +33,33 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -144,23 +152,22 @@ - - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.Integration.Test/Tracing/TracingTest.cs b/test/System.Web.Http.Integration.Test/Tracing/TracingTest.cs index 39e6cffd9..bc5d1618b 100644 --- a/test/System.Web.Http.Integration.Test/Tracing/TracingTest.cs +++ b/test/System.Web.Http.Integration.Test/Tracing/TracingTest.cs @@ -380,12 +380,24 @@ private static IList UnexpectedTraces(IList expecte // artifact specific to testing in VS. (Attempting to load all types from xunit.runner.visualstudio.testadapter.dll // fails with recent xUnit.net packages. The assembly references Microsoft.VisualStudio.TestPlatform.ObjectModel.dll // which is not available with xUnit.net 2.0.x.) + // + // Similarly, ignore records for the same exception to allow test to succeed when using the xUnit MSBuild runner. + // In that case, missing types may come from System.Web and Microsoft.Build.Utilities.v4.0 as well as xunit.runner.msbuild.net452. if (actualRecord.Operation == null && actualRecord.Exception is ReflectionTypeLoadException && actualRecord.Message != null && - actualRecord.Message.StartsWith( - "Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, ", - StringComparison.Ordinal)) + (actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, ", + StringComparison.Ordinal) || + actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'xunit.runner.msbuild.", + StringComparison.Ordinal) || + actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'System.Web, ", + StringComparison.Ordinal) || + actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'Microsoft.Build.Utilities.", + StringComparison.Ordinal))) { continue; } @@ -397,8 +409,8 @@ actualRecord.Exception is ReflectionTypeLoadException && if (expectedTrace == null) { - unexpected.Add(string.Format("kind={0} category={1}, operator={2}, operation={3}", - actualRecord.Kind, actualRecord.Category, actualRecord.Operator, actualRecord.Operation)); + unexpected.Add(string.Format("kind={0} category={1}, operator={2}, operation={3}, message={4}", + actualRecord.Kind, actualRecord.Category, actualRecord.Operator, actualRecord.Operation, actualRecord.Message)); } } @@ -422,14 +434,26 @@ private static bool ConfirmTracingOrder(IList expectedRecor // artifact specific to testing in VS. (Attempting to load all types from xunit.runner.visualstudio.testadapter.dll // fails with recent xUnit.net packages. The assembly references Microsoft.VisualStudio.TestPlatform.ObjectModel.dll // which is not available with xUnit.net 2.0.x.) + // + // Similarly, ignore records for the same exception to allow test to succeed when using the xUnit MSBuild runner. + // In that case, missing types may come from System.Web and Microsoft.Build.Utilities.v4.0 as well as xunit.runner.msbuild.net452. var actualRecord = actualRecords.ElementAtOrDefault(traceBeginPos); - if (actualRecord != null && + while (actualRecord != null && actualRecord.Operation == null && actualRecord.Exception is ReflectionTypeLoadException && actualRecord.Message != null && - actualRecord.Message.StartsWith( - "Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, ", - StringComparison.Ordinal)) + (actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'xunit.runner.visualstudio.testadapter, ", + StringComparison.Ordinal) || + actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'xunit.runner.msbuild.", + StringComparison.Ordinal) || + actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'System.Web, ", + StringComparison.Ordinal) || + actualRecord.Message.StartsWith( + "Exception thrown while getting types from 'Microsoft.Build.Utilities.", + StringComparison.Ordinal))) { traceBeginPos++; actualRecord = actualRecords.ElementAtOrDefault(traceBeginPos); diff --git a/test/System.Web.Http.Integration.Test/app.config b/test/System.Web.Http.Integration.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.Integration.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.Integration.Test/packages.config b/test/System.Web.Http.Integration.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/System.Web.Http.Integration.Test/packages.config +++ b/test/System.Web.Http.Integration.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.Owin.Test/HttpMessageHandlerAdapterTest.cs b/test/System.Web.Http.Owin.Test/HttpMessageHandlerAdapterTest.cs index 8ddfce69d..b8b25e30f 100644 --- a/test/System.Web.Http.Owin.Test/HttpMessageHandlerAdapterTest.cs +++ b/test/System.Web.Http.Owin.Test/HttpMessageHandlerAdapterTest.cs @@ -429,7 +429,6 @@ public async Task Invoke_BuildsUriWithHostAndPort() [InlineData(@"-_.~+""<>^`{|}")] // random unicode characters [InlineData("激光這")] - [InlineData("%24")] [InlineData("?#")] public async Task Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string decodedId) { @@ -447,6 +446,27 @@ public async Task Invoke_CreatesUri_ThatGeneratesCorrectlyDecodedStrings(string Assert.Equal(decodedId, routeData.Values["id"]); } + [Theory] + [InlineData("%24", "$")] + [InlineData("%28%29", "()")] + [InlineData("%5B%5D", "[]")] + [InlineData("%7B%7D", "{}")] + public async Task Invoke_CreatesUri_ContainingCorrectlyDecodedStrings(string encoded, string decoded) + { + var handler = CreateOKHandlerStub(); + var bufferPolicySelector = CreateBufferPolicySelector(bufferInput: false, bufferOutput: false); + var environment = CreateOwinEnvironment("GET", "http", "localhost", "/vroot", "/api/customers/" + encoded); + var options = CreateValidOptions(handler, bufferPolicySelector); + var adapter = CreateProductUnderTest(options); + var route = new HttpRoute("api/customers/{id}"); + + await adapter.Invoke(new OwinContext(environment)); + IHttpRouteData routeData = route.GetRouteData("/vroot", handler.Request); + + Assert.NotNull(routeData); + Assert.Equal(decoded, routeData.Values["id"]); + } + [Fact] public async Task Invoke_AddsRequestHeadersToRequestMessage() { diff --git a/test/System.Web.Http.Owin.Test/NonOwnedStreamTests.cs b/test/System.Web.Http.Owin.Test/NonOwnedStreamTests.cs index 4591e067a..c21948fb5 100644 --- a/test/System.Web.Http.Owin.Test/NonOwnedStreamTests.cs +++ b/test/System.Web.Http.Owin.Test/NonOwnedStreamTests.cs @@ -121,7 +121,7 @@ public void Dispose_DoesNotDisposeInnerStream() Mock mock = new Mock(MockBehavior.Strict); mock.Setup(s => s.Close()).Callback(() => innerStreamDisposed = true); mock.As().Setup(s => s.Dispose()); - mock.Protected().Setup("Dispose", true).Callback(() => innerStreamDisposed = true); + mock.Protected().Setup("Dispose", exactParameterMatch: true, args: true).Callback(() => innerStreamDisposed = true); using (Stream innerStream = mock.Object) using (Stream product = CreateProductUnderTest(innerStream)) @@ -159,7 +159,7 @@ public void Close_DoesNotDisposeInnerStream() Mock mock = new Mock(MockBehavior.Strict); mock.Setup(s => s.Close()).Callback(() => innerStreamDisposed = true); mock.As().Setup(s => s.Dispose()); - mock.Protected().Setup("Dispose", true).Callback(() => innerStreamDisposed = true); + mock.Protected().Setup("Dispose", exactParameterMatch: true, args: true).Callback(() => innerStreamDisposed = true); using (Stream innerStream = mock.Object) using (Stream product = CreateProductUnderTest(innerStream)) diff --git a/test/System.Web.Http.Owin.Test/OwinHostIntegrationTest.cs b/test/System.Web.Http.Owin.Test/OwinHostIntegrationTest.cs index 17e2d15d0..1300d1fd5 100644 --- a/test/System.Web.Http.Owin.Test/OwinHostIntegrationTest.cs +++ b/test/System.Web.Http.Owin.Test/OwinHostIntegrationTest.cs @@ -12,6 +12,7 @@ namespace System.Web.Http.Owin { + [Xunit.Collection("PortReserver Collection")] // Avoid conflicts between different PortReserver consumers. public class OwinHostIntegrationTest { [Fact] diff --git a/test/System.Web.Http.Owin.Test/System.Web.Http.Owin.Test.csproj b/test/System.Web.Http.Owin.Test/System.Web.Http.Owin.Test.csproj index 021820fb9..c412d3625 100644 --- a/test/System.Web.Http.Owin.Test/System.Web.Http.Owin.Test.csproj +++ b/test/System.Web.Http.Owin.Test/System.Web.Http.Owin.Test.csproj @@ -1,7 +1,7 @@  - - + + {C19267DD-3984-430C-AE18-4034F85DE4E5} @@ -14,27 +14,28 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Microsoft.Owin.2.0.2\lib\net45\Microsoft.Owin.dll + + ..\..\packages\Microsoft.Owin.4.2.3\lib\net45\Microsoft.Owin.dll + True - - False - ..\..\packages\Microsoft.Owin.Host.HttpListener.2.0.2\lib\net45\Microsoft.Owin.Host.HttpListener.dll + + ..\..\packages\Microsoft.Owin.Host.HttpListener.4.2.3\lib\net45\Microsoft.Owin.Host.HttpListener.dll + True - - False - ..\..\packages\Microsoft.Owin.Hosting.2.0.2\lib\net45\Microsoft.Owin.Hosting.dll + + ..\..\packages\Microsoft.Owin.Hosting.4.2.3\lib\net45\Microsoft.Owin.Hosting.dll + True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -43,21 +44,29 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -100,23 +109,22 @@ - - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.Owin.Test/app.config b/test/System.Web.Http.Owin.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.Owin.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.Owin.Test/packages.config b/test/System.Web.Http.Owin.Test/packages.config index 257cb23d3..b794cb76d 100644 --- a/test/System.Web.Http.Owin.Test/packages.config +++ b/test/System.Web.Http.Owin.Test/packages.config @@ -1,18 +1,20 @@  - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.SelfHost.Test/Authentication/BasicOverHttpTest.cs b/test/System.Web.Http.SelfHost.Test/Authentication/BasicOverHttpTest.cs index 0b2a5739e..85cde9467 100644 --- a/test/System.Web.Http.SelfHost.Test/Authentication/BasicOverHttpTest.cs +++ b/test/System.Web.Http.SelfHost.Test/Authentication/BasicOverHttpTest.cs @@ -10,6 +10,7 @@ namespace System.Web.Http { + [Xunit.Collection("PortReserver Collection")] // Avoid conflicts between different PortReserver consumers. public class BasicOverHttpTest { [Fact] diff --git a/test/System.Web.Http.SelfHost.Test/HttpSelfHostResponseTest.cs b/test/System.Web.Http.SelfHost.Test/HttpSelfHostResponseTest.cs index bb192b922..8a8919057 100644 --- a/test/System.Web.Http.SelfHost.Test/HttpSelfHostResponseTest.cs +++ b/test/System.Web.Http.SelfHost.Test/HttpSelfHostResponseTest.cs @@ -12,6 +12,7 @@ namespace System.Web.Http.SelfHost { + [Xunit.Collection("PortReserver Collection")] // Avoid conflicts between different PortReserver consumers. public class HttpSelfHostResponseTest { [Fact] diff --git a/test/System.Web.Http.SelfHost.Test/HttpSelfHostServerTest.cs b/test/System.Web.Http.SelfHost.Test/HttpSelfHostServerTest.cs index afd3b77c2..a53f4ba3c 100644 --- a/test/System.Web.Http.SelfHost.Test/HttpSelfHostServerTest.cs +++ b/test/System.Web.Http.SelfHost.Test/HttpSelfHostServerTest.cs @@ -18,6 +18,7 @@ namespace System.Web.Http.SelfHost { + [Xunit.Collection("PortReserver Collection")] // Avoid conflicts between different PortReserver consumers. public class HttpSelfHostServerTest : IDisposable { private HttpSelfHostServer server = null; diff --git a/test/System.Web.Http.SelfHost.Test/System.Web.Http.SelfHost.Test.csproj b/test/System.Web.Http.SelfHost.Test/System.Web.Http.SelfHost.Test.csproj index 490f1adf3..7c7c82563 100644 --- a/test/System.Web.Http.SelfHost.Test/System.Web.Http.SelfHost.Test.csproj +++ b/test/System.Web.Http.SelfHost.Test/System.Web.Http.SelfHost.Test.csproj @@ -1,7 +1,7 @@  - - + + {7F29EE87-6A63-43C6-B7FF-74DD06815830} @@ -14,16 +14,16 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -32,24 +32,32 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -73,7 +81,6 @@ - @@ -102,16 +109,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.SelfHost.Test/app.config b/test/System.Web.Http.SelfHost.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.SelfHost.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.SelfHost.Test/packages.config b/test/System.Web.Http.SelfHost.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/System.Web.Http.SelfHost.Test/packages.config +++ b/test/System.Web.Http.SelfHost.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.SignalR.Test/System.Web.Http.SignalR.Test.csproj b/test/System.Web.Http.SignalR.Test/System.Web.Http.SignalR.Test.csproj index 08f07b428..a422b3b6b 100644 --- a/test/System.Web.Http.SignalR.Test/System.Web.Http.SignalR.Test.csproj +++ b/test/System.Web.Http.SignalR.Test/System.Web.Http.SignalR.Test.csproj @@ -1,7 +1,7 @@  - - + + {E22245AF-D5E1-46F6-B443-C886983EC50C} @@ -13,19 +13,20 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Microsoft.AspNet.SignalR.Core.1.0.0\lib\net40\Microsoft.AspNet.SignalR.Core.dll + + ..\..\packages\Microsoft.AspNet.SignalR.Core.1.2.2\lib\net40\Microsoft.AspNet.SignalR.Core.dll + True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -33,21 +34,29 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -70,7 +79,6 @@ - @@ -82,16 +90,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.SignalR.Test/app.config b/test/System.Web.Http.SignalR.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.SignalR.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.SignalR.Test/packages.config b/test/System.Web.Http.SignalR.Test/packages.config index cdf693e68..738a1b70a 100644 --- a/test/System.Web.Http.SignalR.Test/packages.config +++ b/test/System.Web.Http.SignalR.Test/packages.config @@ -1,15 +1,17 @@  - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.Test/Controllers/VoidResultConverterTest.cs b/test/System.Web.Http.Test/Controllers/VoidResultConverterTest.cs index c05e5f29a..7622e931f 100644 --- a/test/System.Web.Http.Test/Controllers/VoidResultConverterTest.cs +++ b/test/System.Web.Http.Test/Controllers/VoidResultConverterTest.cs @@ -31,7 +31,8 @@ public void Convert_ReturnsResponseMessageWithRequestAssignedAndNoContentToRefle var result = _converter.Convert(_context, null); Assert.Equal(HttpStatusCode.NoContent, result.StatusCode); - Assert.Null(result.Content); + Assert.NotNull(result.Content); + Assert.Equal(0L, result.Content.Headers.ContentLength); Assert.Same(_request, result.RequestMessage); } } diff --git a/test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerActivatorTest.cs b/test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerActivatorTest.cs index 7db1b5780..191397e83 100644 --- a/test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerActivatorTest.cs +++ b/test/System.Web.Http.Test/Dispatcher/DefaultHttpControllerActivatorTest.cs @@ -153,7 +153,7 @@ public void Create_ThrowsForNullDependencyScope() exception.Message); Assert.NotNull(exception.InnerException); Assert.Matches( - "A dependency resolver of type 'ObjectProxy(_\\d+)?' returned an invalid value of null from its " + + "A dependency resolver of type 'IDependencyResolverProxy' returned an invalid value of null from its " + "BeginScope method. If the container does not have a concept of scope, consider returning a scope " + "that resolves in the root of the container instead.", exception.InnerException.Message); diff --git a/test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerTests.cs b/test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerTests.cs index e202dad6a..d916c2578 100644 --- a/test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerTests.cs +++ b/test/System.Web.Http.Test/ExceptionHandling/ExceptionLoggerTests.cs @@ -242,7 +242,7 @@ public void ShouldLog_IfExceptionDataContainsLoggedByLogger_ReturnsFalse() Assert.True(data.Contains(ExceptionLogger.LoggedByKey)); object updatedLoggedBy = data[ExceptionLogger.LoggedByKey]; Assert.Same(loggedBy, updatedLoggedBy); - Assert.Equal(1, loggedBy.Count); + Assert.Single(loggedBy); } [Fact] diff --git a/test/System.Web.Http.Test/HttpRouteCollectionExtensionsTest.cs b/test/System.Web.Http.Test/HttpRouteCollectionExtensionsTest.cs index 2c3ac1c8f..24173e6ca 100644 --- a/test/System.Web.Http.Test/HttpRouteCollectionExtensionsTest.cs +++ b/test/System.Web.Http.Test/HttpRouteCollectionExtensionsTest.cs @@ -38,7 +38,7 @@ public void MapHttpRoute1CreatesRoute() // Assert Assert.NotNull(route); Assert.Equal("template", route.RouteTemplate); - Assert.Equal(1, route.Defaults.Count); + Assert.Single(route.Defaults); Assert.Equal("D1", route.Defaults["d1"]); Assert.Same(route, routes["name"]); } @@ -56,7 +56,7 @@ public void MapHttpRoute1WithDefaultsAsDictionaryCreatesRoute() // Assert Assert.NotNull(route); Assert.Equal("template", route.RouteTemplate); - Assert.Equal(1, route.Defaults.Count); + Assert.Single(route.Defaults); Assert.Equal("D1", route.Defaults["d1"]); Assert.Same(route, routes["name"]); } @@ -81,9 +81,9 @@ public void MapHttpRoute2CreatesRoute() // Assert Assert.NotNull(route); Assert.Equal("template", route.RouteTemplate); - Assert.Equal(1, route.Defaults.Count); + Assert.Single(route.Defaults); Assert.Equal("D1", route.Defaults["d1"]); - Assert.Equal(1, route.Defaults.Count); + Assert.Single(route.Defaults); Assert.Equal("C1", route.Constraints["c1"]); Assert.Same(route, routes["name"]); } @@ -102,9 +102,9 @@ public void MapHttpRoute2WithDefaultsAndConstraintsAsDictionaryCreatesRoute() // Assert Assert.NotNull(route); Assert.Equal("template", route.RouteTemplate); - Assert.Equal(1, route.Defaults.Count); + Assert.Single(route.Defaults); Assert.Equal("D1", route.Defaults["d1"]); - Assert.Equal(1, route.Defaults.Count); + Assert.Single(route.Defaults); Assert.Equal("C1", route.Constraints["c1"]); Assert.Same(route, routes["name"]); } diff --git a/test/System.Web.Http.Test/Routing/DirectRouteProviderContextTests.cs b/test/System.Web.Http.Test/Routing/DirectRouteProviderContextTests.cs index bec090eba..891f2ba2a 100644 --- a/test/System.Web.Http.Test/Routing/DirectRouteProviderContextTests.cs +++ b/test/System.Web.Http.Test/Routing/DirectRouteProviderContextTests.cs @@ -43,7 +43,7 @@ public void CreateBuilderWithResolverAndBuild_Throws_WhenConstraintResolverRetur var ex = Assert.Throws( () => BuildWithResolver(@"hello/{param:constraint}", constraintResolver: constraintResolver.Object)); Assert.Matches( - "The inline constraint resolver of type 'ObjectProxy(_\\d+)?' was unable to resolve the following inline constraint: 'constraint'.", + "The inline constraint resolver of type 'IInlineConstraintResolverProxy' was unable to resolve the following inline constraint: 'constraint'.", ex.Message); } diff --git a/test/System.Web.Http.Test/System.Web.Http.Test.csproj b/test/System.Web.Http.Test/System.Web.Http.Test.csproj index 65f5a6cee..155a41fb2 100644 --- a/test/System.Web.Http.Test/System.Web.Http.Test.csproj +++ b/test/System.Web.Http.Test/System.Web.Http.Test.csproj @@ -1,7 +1,7 @@  - - + + {7F2C796F-43B2-4F8F-ABFF-A154EC8AAFA1} @@ -15,16 +15,16 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -35,24 +35,32 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -375,7 +383,6 @@ - @@ -406,16 +413,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.Test/Tracing/Tracers/FormatterParameterBindingTracerTest.cs b/test/System.Web.Http.Test/Tracing/Tracers/FormatterParameterBindingTracerTest.cs index bcb9592be..326ac41ed 100644 --- a/test/System.Web.Http.Test/Tracing/Tracers/FormatterParameterBindingTracerTest.cs +++ b/test/System.Web.Http.Test/Tracing/Tracers/FormatterParameterBindingTracerTest.cs @@ -125,7 +125,7 @@ public async Task ExecuteBindingAsync_Traces_And_Invokes_Inner_ReadAsync() // Assert Assert.Equal(expectedTraces, traceWriter.Traces, new TraceRecordComparer()); - Assert.Equal("True", actionContext.ActionArguments["paramName"]); + Assert.Equal("true", actionContext.ActionArguments["paramName"]); } [Fact] diff --git a/test/System.Web.Http.Test/app.config b/test/System.Web.Http.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.Test/packages.config b/test/System.Web.Http.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/System.Web.Http.Test/packages.config +++ b/test/System.Web.Http.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.Tracing.Test/System.Web.Http.Tracing.Test.csproj b/test/System.Web.Http.Tracing.Test/System.Web.Http.Tracing.Test.csproj index d8b95dab1..41a901648 100644 --- a/test/System.Web.Http.Tracing.Test/System.Web.Http.Tracing.Test.csproj +++ b/test/System.Web.Http.Tracing.Test/System.Web.Http.Tracing.Test.csproj @@ -1,7 +1,7 @@  - - + + {F87FD911-4A97-4057-8EAE-1CB96B9A1937} @@ -14,8 +14,8 @@ - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -24,19 +24,19 @@ - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -45,7 +45,6 @@ - @@ -70,23 +69,23 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - - + \ No newline at end of file diff --git a/test/System.Web.Http.Tracing.Test/SystemDiagnosticsTraceWriterTest.cs b/test/System.Web.Http.Tracing.Test/SystemDiagnosticsTraceWriterTest.cs index 0e89eed34..6df7d570a 100644 --- a/test/System.Web.Http.Tracing.Test/SystemDiagnosticsTraceWriterTest.cs +++ b/test/System.Web.Http.Tracing.Test/SystemDiagnosticsTraceWriterTest.cs @@ -332,7 +332,7 @@ public void Trace_Brief_Trace_Does_Not_Trace_When_No_Data() writer.Trace(request, "TestCategory", TraceLevel.Info, (tr) => { }); // Assert - Assert.Equal(0, ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages.Count); + Assert.Empty(((TestTraceListener)writer.TraceSource.Listeners[0]).Messages); } [Fact] @@ -352,7 +352,7 @@ public void Trace_Brief_Trace_Does_Not_Trace_BeginKind() writer.Trace(request, "TestCategory", TraceLevel.Info, (tr) => { tr.Kind = TraceKind.Begin; tr.Message = "TestMessage"; }); // Assert - Assert.Equal(0, ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages.Count); + Assert.Empty(((TestTraceListener)writer.TraceSource.Listeners[0]).Messages); } [Theory] @@ -379,7 +379,7 @@ public void Trace_Does_Not_Trace_Below_Minimum_Level(TraceLevel level) writer.Trace(request, "TestCategory", level - 1, (tr) => { }); // Assert - Assert.Equal(0, ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages.Count); + Assert.Empty(((TestTraceListener)writer.TraceSource.Listeners[0]).Messages); } [Fact] @@ -851,7 +851,7 @@ public void TranslateHttpResponseException_Unpacks_Empty_HttpError() new SystemDiagnosticsTraceWriter().TranslateHttpResponseException(traceRecord); // Assert - Assert.Equal(0, ParseTrace(traceRecord.Message).Count); + Assert.Empty(ParseTrace(traceRecord.Message)); } [Fact] diff --git a/test/System.Web.Http.Tracing.Test/app.config b/test/System.Web.Http.Tracing.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.Tracing.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.Tracing.Test/packages.config b/test/System.Web.Http.Tracing.Test/packages.config index be24c1eea..9dcbea460 100644 --- a/test/System.Web.Http.Tracing.Test/packages.config +++ b/test/System.Web.Http.Tracing.Test/packages.config @@ -1,12 +1,12 @@  - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Http.WebHost.Test/System.Web.Http.WebHost.Test.csproj b/test/System.Web.Http.WebHost.Test/System.Web.Http.WebHost.Test.csproj index 4e6ec198a..e13acbdf2 100644 --- a/test/System.Web.Http.WebHost.Test/System.Web.Http.WebHost.Test.csproj +++ b/test/System.Web.Http.WebHost.Test/System.Web.Http.WebHost.Test.csproj @@ -1,7 +1,7 @@  - - + + {EA62944F-BD25-4730-9405-9BE8FF5BEACD} @@ -14,16 +14,16 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -31,22 +31,30 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -72,7 +80,6 @@ - @@ -105,16 +112,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Http.WebHost.Test/WebHostExceptionHandlerTests.cs b/test/System.Web.Http.WebHost.Test/WebHostExceptionHandlerTests.cs index 42e23eaf2..e6bcf94e3 100644 --- a/test/System.Web.Http.WebHost.Test/WebHostExceptionHandlerTests.cs +++ b/test/System.Web.Http.WebHost.Test/WebHostExceptionHandlerTests.cs @@ -220,7 +220,8 @@ public async Task HandleAsync_IfCatchBlockIsWebHostBufferedContent_WithCreateExc { Assert.NotNull(response); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); - Assert.Null(response.Content); + Assert.NotNull(response.Content); + Assert.Equal(0L, response.Content.Headers.ContentLength); Assert.Same(expectedRequest, response.RequestMessage); } } diff --git a/test/System.Web.Http.WebHost.Test/app.config b/test/System.Web.Http.WebHost.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Http.WebHost.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Http.WebHost.Test/packages.config b/test/System.Web.Http.WebHost.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/System.Web.Http.WebHost.Test/packages.config +++ b/test/System.Web.Http.WebHost.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Mvc.Test/Async/Test/AsyncResultWrapperTest.cs b/test/System.Web.Mvc.Test/Async/Test/AsyncResultWrapperTest.cs index 3ca160065..e15cd6be8 100644 --- a/test/System.Web.Mvc.Test/Async/Test/AsyncResultWrapperTest.cs +++ b/test/System.Web.Mvc.Test/Async/Test/AsyncResultWrapperTest.cs @@ -544,7 +544,7 @@ public void TimedOut() IAsyncResult asyncResult = AsyncResultWrapper.Begin( callback, null, (innerCallback, callbackState, state) => mockResult, - (ar, state) => { Assert.True(false, "This callback should never execute since we timed out."); }, + (ar, state) => { Assert.Fail("This callback should never execute since we timed out."); }, null, null, 0); diff --git a/test/System.Web.Mvc.Test/Async/Test/OperationCounterTest.cs b/test/System.Web.Mvc.Test/Async/Test/OperationCounterTest.cs index e2bd126a6..6e1bf6a6f 100644 --- a/test/System.Web.Mvc.Test/Async/Test/OperationCounterTest.cs +++ b/test/System.Web.Mvc.Test/Async/Test/OperationCounterTest.cs @@ -18,11 +18,11 @@ public void CompletedEvent() { if (premature) { - Assert.True(false, "Event fired too early!"); + Assert.Fail("Event fired too early!"); } if (eventFired) { - Assert.True(false, "Event fired multiple times."); + Assert.Fail("Event fired multiple times."); } Assert.Equal(ops, sender); diff --git a/test/System.Web.Mvc.Test/ExpressionUtil/Test/FingerprintingExpressionVisitorTest.cs b/test/System.Web.Mvc.Test/ExpressionUtil/Test/FingerprintingExpressionVisitorTest.cs index 5a1f384bf..6151e0c56 100644 --- a/test/System.Web.Mvc.Test/ExpressionUtil/Test/FingerprintingExpressionVisitorTest.cs +++ b/test/System.Web.Mvc.Test/ExpressionUtil/Test/FingerprintingExpressionVisitorTest.cs @@ -33,7 +33,7 @@ public void TypeOverridesAllMethods() sb.AppendLine(); sb.Append(method); } - Assert.True(false, sb.ToString()); + Assert.Fail(sb.ToString()); } } diff --git a/test/System.Web.Mvc.Test/Routing/RouteCollectionAttributeRoutingExtensionsTests.cs b/test/System.Web.Mvc.Test/Routing/RouteCollectionAttributeRoutingExtensionsTests.cs index 6d85b8025..0315754cf 100644 --- a/test/System.Web.Mvc.Test/Routing/RouteCollectionAttributeRoutingExtensionsTests.cs +++ b/test/System.Web.Mvc.Test/Routing/RouteCollectionAttributeRoutingExtensionsTests.cs @@ -57,7 +57,7 @@ public void MapMvcAttributeRoutes_CustomConstraintResolver() // Assert var attributeRoutes = GetAttributeRoutes(routes); - Assert.Equal(1, attributeRoutes.Count); + Assert.Single(attributeRoutes); Route route = (Route)attributeRoutes.Single(); Assert.Equal("fruits/{apple}", route.Url); @@ -97,7 +97,7 @@ public void MapMvcAttributeRoutes_WithPrefixedController() // Assert var attributeRoutes = GetAttributeRoutes(routes); - Assert.Equal(1, attributeRoutes.Count); + Assert.Single(attributeRoutes); Route route = (Route)attributeRoutes.Single(); Assert.Equal("prefpref/getme", route.Url); @@ -128,7 +128,7 @@ public void MapMvcAttributeRoutes_WithArea() // Assert var attributeRoutes = GetAttributeRoutes(routes); - Assert.Equal(1, attributeRoutes.Count); + Assert.Single(attributeRoutes); Route route = (Route)attributeRoutes.Single(); @@ -151,7 +151,7 @@ public void MapMvcAttributeRoutes_WithPrefixedArea() // Assert var attributeRoutes = GetAttributeRoutes(routes); - Assert.Equal(1, attributeRoutes.Count); + Assert.Single(attributeRoutes); Route route = (Route)attributeRoutes.Single(); diff --git a/test/System.Web.Mvc.Test/System.Web.Mvc.Test.csproj b/test/System.Web.Mvc.Test/System.Web.Mvc.Test.csproj index 1c842075d..9cfce63b5 100644 --- a/test/System.Web.Mvc.Test/System.Web.Mvc.Test.csproj +++ b/test/System.Web.Mvc.Test/System.Web.Mvc.Test.csproj @@ -1,7 +1,7 @@  - - + + {8AC2A2E4-2F11-4D40-A887-62E2583A65E6} @@ -17,17 +17,18 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll + True @@ -37,23 +38,31 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -402,7 +411,6 @@ - @@ -415,16 +423,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Mvc.Test/Test/AcceptVerbsAttributeTest.cs b/test/System.Web.Mvc.Test/Test/AcceptVerbsAttributeTest.cs index 18ff1238a..a920afacd 100644 --- a/test/System.Web.Mvc.Test/Test/AcceptVerbsAttributeTest.cs +++ b/test/System.Web.Mvc.Test/Test/AcceptVerbsAttributeTest.cs @@ -62,7 +62,7 @@ public void EnumToArray() string message = String.Format(_invalidEnumFormatString, aggrValues, aggrNames.Aggregate((a, b) => a + ", " + b), array.Aggregate((a, b) => a + ", " + b)); - Assert.True(false, message); + Assert.Fail(message); } } } diff --git a/test/System.Web.Mvc.Test/Test/ControllerActionInvokerTest.cs b/test/System.Web.Mvc.Test/Test/ControllerActionInvokerTest.cs index f03f0c4a4..a012695d1 100644 --- a/test/System.Web.Mvc.Test/Test/ControllerActionInvokerTest.cs +++ b/test/System.Web.Mvc.Test/Test/ControllerActionInvokerTest.cs @@ -990,7 +990,7 @@ public void InvokeActionMethodFilterWhereOnActionExecutingCancels() }; Func continuation = delegate { - Assert.True(false, "The continuation should not be called."); + Assert.Fail("The continuation should not be called."); return null; }; @@ -1106,7 +1106,7 @@ public void InvokeActionInvokesExceptionFiltersAndRethrowsExceptionIfNotHandled( mockHelper.Setup(h => h.PublicInvokeAuthenticationFilters(context, filterInfo.AuthenticationFilters, ad)).Returns(authenticationContext).Verifiable(); mockHelper.Setup(h => h.PublicInvokeAuthorizationFilters(context, filterInfo.AuthorizationFilters, ad)).Throws(exception).Verifiable(); mockHelper.Setup(h => h.PublicInvokeExceptionFilters(context, filterInfo.ExceptionFilters, exception)).Returns(exContext).Verifiable(); - mockHelper.Setup(h => h.PublicInvokeActionResult(context, It.IsAny())).Callback(delegate { Assert.True(false, "InvokeActionResult() shouldn't be called if the exception was unhandled by filters."); }); + mockHelper.Setup(h => h.PublicInvokeActionResult(context, It.IsAny())).Callback(delegate { Assert.Fail("InvokeActionResult() shouldn't be called if the exception was unhandled by filters."); }); ControllerActionInvokerHelper helper = mockHelper.Object; // Act @@ -1267,7 +1267,7 @@ public void InvokeActionMethodWithFiltersPassesArgumentsCorrectly() }; Func continuation = delegate { - Assert.True(false, "Continuation should not be called."); + Assert.Fail("Continuation should not be called."); return null; }; ControllerBase controller = new ContinuationController(continuation); @@ -1783,7 +1783,7 @@ public void InvokeActionResultWithFiltersPassesArgumentsCorrectly() { // Arrange bool wasCalled = false; - Action continuation = delegate { Assert.True(false, "Continuation should not be called."); }; + Action continuation = delegate { Assert.Fail("Continuation should not be called."); }; ActionResult actionResult = new ContinuationResult(continuation); ControllerBase controller = new Mock().Object; ControllerContext context = GetControllerContext(controller); @@ -2152,7 +2152,7 @@ public void InvokeActionResultWithFiltersWhereCancelled() }; Action continuation = delegate { - Assert.True(false, "The continuation should not be called."); + Assert.Fail("The continuation should not be called."); }; ActionResult actionResult = new ContinuationResult(continuation); @@ -2466,12 +2466,14 @@ private static ControllerContext GetControllerContext(ControllerBase controller, Mock mockControllerContext = new Mock(); mockControllerContext.SetupGet(c => c.RouteData).Returns(new RouteData()); + mockControllerContext.SetupGet(c => c.HttpContext.Session).Returns((HttpSessionStateBase)null); + mockControllerContext.SetupProperty(c => c.HttpContext.User); mockControllerContext.Setup(c => c.HttpContext.Request.ValidateInput()).Callback(() => { if (!controller.ValidateRequest) { - Assert.True(false, "ValidateRequest() should not be called if the controller opted out."); + Assert.Fail("ValidateRequest() should not be called if the controller opted out."); } if (validateInputCallback != null) { @@ -2480,7 +2482,6 @@ private static ControllerContext GetControllerContext(ControllerBase controller, } }); - mockControllerContext.Setup(c => c.HttpContext.Session).Returns((HttpSessionStateBase)null); mockControllerContext.Setup(c => c.Controller).Returns(controller); return mockControllerContext.Object; } diff --git a/test/System.Web.Mvc.Test/Test/ControllerTest.cs b/test/System.Web.Mvc.Test/Test/ControllerTest.cs index b9793aaa9..f9cf70837 100644 --- a/test/System.Web.Mvc.Test/Test/ControllerTest.cs +++ b/test/System.Web.Mvc.Test/Test/ControllerTest.cs @@ -301,7 +301,7 @@ public void DisposeCallsProtectedDisposingMethod() { // Arrange Mock mockController = new Mock(); - mockController.Protected().Setup("Dispose", true).Verifiable(); + mockController.Protected().Setup("Dispose", exactParameterMatch: true, args: true).Verifiable(); Controller controller = mockController.Object; // Act diff --git a/test/System.Web.Mvc.Test/Test/FilterInfoTest.cs b/test/System.Web.Mvc.Test/Test/FilterInfoTest.cs index 0d71daaba..9e5c1c5a9 100644 --- a/test/System.Web.Mvc.Test/Test/FilterInfoTest.cs +++ b/test/System.Web.Mvc.Test/Test/FilterInfoTest.cs @@ -205,7 +205,7 @@ public void ActionFilters_ReturnLastActionFilters_WhenOverrideScopeIsLast() // Assert Assert.NotNull(actionFilters); - Assert.Equal(1, actionFilters.Count); + Assert.Single(actionFilters); Assert.Same(expectedLastFilter, actionFilters[0]); } @@ -261,7 +261,7 @@ public void AuthorizationFilters_ReturnsLastAuthorizationFilters_WhenOverrideSco // Assert Assert.NotNull(authorizationFilters); - Assert.Equal(1, authorizationFilters.Count); + Assert.Single(authorizationFilters); Assert.Same(expectedLastFilter, authorizationFilters[0]); } @@ -285,7 +285,7 @@ public void AuthenticationFilters_ReturnsLastAuthenticationFilters_WhenOverrideS // Assert Assert.NotNull(authenticationFilters); - Assert.Equal(1, authenticationFilters.Count); + Assert.Single(authenticationFilters); Assert.Same(expectedLastFilter, authenticationFilters[0]); } @@ -309,7 +309,7 @@ public void ExceptionFilters_ReturnsLastExceptionFilters_WhenOverrideScopeIsLast // Assert Assert.NotNull(exceptionFilters); - Assert.Equal(1, exceptionFilters.Count); + Assert.Single(exceptionFilters); Assert.Same(expectedLastFilter, exceptionFilters[0]); } @@ -333,7 +333,7 @@ public void ResultFilters_ReturnsLastResultFilters_WhenOverrideScopeIsLast() // Assert Assert.NotNull(resultFilters); - Assert.Equal(1, resultFilters.Count); + Assert.Single(resultFilters); Assert.Same(expectedLastFilter, resultFilters[0]); } @@ -354,10 +354,10 @@ public void FilterImplementingMultipleType_WhereOneTypeIsOverridden_AppearsOnlyI // Assert Assert.NotNull(actionFilters); - Assert.Equal(1, actionFilters.Count); + Assert.Single(actionFilters); Assert.Same(expectedInstance, actionFilters[0]); Assert.NotNull(exceptionFilters); - Assert.Equal(0, exceptionFilters.Count); + Assert.Empty(exceptionFilters); } private static IActionFilter CreateDummyActionFilter() diff --git a/test/System.Web.Mvc.Test/Test/MaxLengthAttributeAdapterTest.cs b/test/System.Web.Mvc.Test/Test/MaxLengthAttributeAdapterTest.cs index c368f30c0..27c5d6ea0 100644 --- a/test/System.Web.Mvc.Test/Test/MaxLengthAttributeAdapterTest.cs +++ b/test/System.Web.Mvc.Test/Test/MaxLengthAttributeAdapterTest.cs @@ -25,7 +25,7 @@ public void ClientRulesWithMaxLengthAttribute() // Assert ModelClientValidationRule rule = Assert.Single(rules); Assert.Equal("maxlength", rule.ValidationType); - Assert.Equal(1, rule.ValidationParameters.Count); + Assert.Single(rule.ValidationParameters); Assert.Equal(10, rule.ValidationParameters["max"]); Assert.Equal("The field Length must be a string or array type with a maximum length of '10'.", rule.ErrorMessage); } @@ -48,7 +48,7 @@ public void ClientRulesWithMaxLengthAttributeAndCustomMessage() // Assert ModelClientValidationRule rule = Assert.Single(rules); Assert.Equal("maxlength", rule.ValidationType); - Assert.Equal(1, rule.ValidationParameters.Count); + Assert.Single(rule.ValidationParameters); Assert.Equal(5, rule.ValidationParameters["max"]); Assert.Equal("Length must be at most 5", rule.ErrorMessage); } diff --git a/test/System.Web.Mvc.Test/Test/MinLengthAttributeAdapterTest.cs b/test/System.Web.Mvc.Test/Test/MinLengthAttributeAdapterTest.cs index e8d822804..abee8ad93 100644 --- a/test/System.Web.Mvc.Test/Test/MinLengthAttributeAdapterTest.cs +++ b/test/System.Web.Mvc.Test/Test/MinLengthAttributeAdapterTest.cs @@ -25,7 +25,7 @@ public void ClientRulesWithMinLengthAttribute() // Assert ModelClientValidationRule rule = Assert.Single(rules); Assert.Equal("minlength", rule.ValidationType); - Assert.Equal(1, rule.ValidationParameters.Count); + Assert.Single(rule.ValidationParameters); Assert.Equal(6, rule.ValidationParameters["min"]); Assert.Equal("The field Length must be a string or array type with a minimum length of '6'.", rule.ErrorMessage); } @@ -48,7 +48,7 @@ public void ClientRulesWithMinLengthAttributeAndCustomMessage() // Assert ModelClientValidationRule rule = Assert.Single(rules); Assert.Equal("minlength", rule.ValidationType); - Assert.Equal(1, rule.ValidationParameters.Count); + Assert.Single(rule.ValidationParameters); Assert.Equal(2, rule.ValidationParameters["min"]); Assert.Equal("Array must have at least 2 items.", rule.ErrorMessage); } diff --git a/test/System.Web.Mvc.Test/Test/RazorViewTest.cs b/test/System.Web.Mvc.Test/Test/RazorViewTest.cs index 92a02af7c..fd249cbba 100644 --- a/test/System.Web.Mvc.Test/Test/RazorViewTest.cs +++ b/test/System.Web.Mvc.Test/Test/RazorViewTest.cs @@ -134,7 +134,7 @@ public void RenderWithViewPageAndNoStartPageLookupRendersView() RazorView view = new RazorView(controllerContext, "~/viewPath", null, false, Enumerable.Empty(), activator.Object); view.StartPageLookup = (WebPageRenderingBase p, string n, IEnumerable e) => { - Assert.True(false, "ViewStart page lookup should not be called"); + Assert.Fail("ViewStart page lookup should not be called"); return null; }; view.BuildManager = buildManager; diff --git a/test/System.Web.Mvc.Test/Util/DictionaryHelper.cs b/test/System.Web.Mvc.Test/Util/DictionaryHelper.cs index a250bba19..a73db0d99 100644 --- a/test/System.Web.Mvc.Test/Util/DictionaryHelper.cs +++ b/test/System.Web.Mvc.Test/Util/DictionaryHelper.cs @@ -512,7 +512,7 @@ private void VerifyDictionaryEntriesEqual(Dictionary controlDictio foreach (var entry in clonedControlDictionary) { var key = entry.Key; - Assert.True(false, String.Format("Test dictionary did not contain key '{0}'.", key)); + Assert.Fail(String.Format("Test dictionary did not contain key '{0}'.", key)); } } } diff --git a/test/System.Web.Mvc.Test/app.config b/test/System.Web.Mvc.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/System.Web.Mvc.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/System.Web.Mvc.Test/packages.config b/test/System.Web.Mvc.Test/packages.config index 05cbc07d8..a8c31b704 100644 --- a/test/System.Web.Mvc.Test/packages.config +++ b/test/System.Web.Mvc.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.Razor.Test/Framework/ParserTestBase.cs b/test/System.Web.Razor.Test/Framework/ParserTestBase.cs index 469f3af9d..24d16a368 100644 --- a/test/System.Web.Razor.Test/Framework/ParserTestBase.cs +++ b/test/System.Web.Razor.Test/Framework/ParserTestBase.cs @@ -258,7 +258,7 @@ public static void EvaluateParseTree(Block actualRoot, Block expectedRoot) } else { - Assert.True(false, String.Format("\r\n{0}", collector.Message)); + Assert.Fail(String.Format("\r\n{0}", collector.Message)); } } } diff --git a/test/System.Web.Razor.Test/Parser/Html/HtmlAttributeTest.cs b/test/System.Web.Razor.Test/Parser/Html/HtmlAttributeTest.cs index 4baf7fdf2..c912a74a7 100644 --- a/test/System.Web.Razor.Test/Parser/Html/HtmlAttributeTest.cs +++ b/test/System.Web.Razor.Test/Parser/Html/HtmlAttributeTest.cs @@ -178,7 +178,7 @@ public void ConditionalAttributeCollapserDoesNotRemoveUrlAttributeValues() rewritten = new MarkupCollapser(new HtmlMarkupParser().BuildSpan).Rewrite(rewritten); // Assert - Assert.Equal(0, results.ParserErrors.Count); + Assert.Empty(results.ParserErrors); EvaluateParseTree(rewritten, new MarkupBlock( Factory.Markup(" - - + + {0BB62A1D-E6B5-49FA-9E3C-6AF679A66DFE} @@ -15,13 +15,13 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True @@ -29,20 +29,29 @@ 3.5 + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -480,9 +489,9 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.Razor.Test/packages.config b/test/System.Web.Razor.Test/packages.config index a5553dbbe..6ed5d6539 100644 --- a/test/System.Web.Razor.Test/packages.config +++ b/test/System.Web.Razor.Test/packages.config @@ -1,11 +1,14 @@  - - - - - - - - + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.WebPages.Administration.Test/System.Web.WebPages.Administration.Test.csproj b/test/System.Web.WebPages.Administration.Test/System.Web.WebPages.Administration.Test.csproj index c3b753fd7..e81b6e4ba 100644 --- a/test/System.Web.WebPages.Administration.Test/System.Web.WebPages.Administration.Test.csproj +++ b/test/System.Web.WebPages.Administration.Test/System.Web.WebPages.Administration.Test.csproj @@ -1,7 +1,7 @@  - - + + {21C729D6-ECF8-47EF-A236-7C6A4272EAF0} @@ -14,41 +14,49 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - + + ..\..\packages\NuGet.Core.1.8.0\lib\net40-Client\NuGet.Core.dll True - ..\..\packages\Nuget.Core.1.6.2\lib\net40\NuGet.Core.dll 3.5 + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -92,16 +100,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.WebPages.Administration.Test/WebProjectManagerTest.cs b/test/System.Web.WebPages.Administration.Test/WebProjectManagerTest.cs index f8dce4e0f..9fc9211fe 100644 --- a/test/System.Web.WebPages.Administration.Test/WebProjectManagerTest.cs +++ b/test/System.Web.WebPages.Administration.Test/WebProjectManagerTest.cs @@ -127,7 +127,44 @@ public void GetPackagesWithLicenseReturnsEmptyResultForPackageThatDoesNotRequire var result = WebProjectManager.GetPackagesRequiringLicenseAcceptance(package, localRepository, remoteRepository); // Assert - Assert.False(result.Any()); + Assert.False(Enumerable.Any(result)); + } + + [Fact] + public void GetUpdateReturnsOnlyLatestVersion() + { + var installed = GetPackage("A"); + var olderUpdate = GetPackage("A", version: "2.0"); + var latestUpdate = GetPackage("A", version: "3.0"); + Mock.Get(olderUpdate).SetupGet(p => p.Listed).Returns(true); + Mock.Get(latestUpdate).SetupGet(p => p.Listed).Returns(true); + var repository = new Mock(); + repository.Setup(r => r.GetPackages()).Returns(new[] { olderUpdate, latestUpdate }.AsQueryable()); + var projectManager = new Mock(); + projectManager.SetupGet(p => p.SourceRepository).Returns(repository.Object); + var webProjectManager = new WebProjectManager(projectManager.Object, @"x:\"); + + var update = webProjectManager.GetUpdate(installed); + + Assert.Same(latestUpdate, update); + } + + [Fact] + public void CollapseVersionsPreservesPackageOrderAndSelectsHighestVersion() + { + var first = GetPackage("B", version: "1.0"); + var latest = GetPackage("B", version: "3.0"); + var intermediate = GetPackage("B", version: "2.0"); + var second = GetPackage("A"); + var packages = new[] { first, latest, intermediate, second }; + foreach (var package in packages) + { + Mock.Get(package).SetupGet(p => p.IsLatestVersion).Returns(true); + } + + var collapsed = WebProjectManager.CollapseVersions(packages.AsQueryable()); + + Assert.Equal(new[] { latest, second }, collapsed); } private static IPackageRepository GetRepository() diff --git a/test/System.Web.WebPages.Administration.Test/WebProjectSystemTest.cs b/test/System.Web.WebPages.Administration.Test/WebProjectSystemTest.cs index c0b1dfecc..0eda27258 100644 --- a/test/System.Web.WebPages.Administration.Test/WebProjectSystemTest.cs +++ b/test/System.Web.WebPages.Administration.Test/WebProjectSystemTest.cs @@ -15,6 +15,14 @@ namespace System.Web.WebPages.Administration.Test { public class WebProjectSystemTest { + [Fact] + public void IsBindingRedirectSupportedReturnsTrue() + { + IProjectSystem webProjectSystem = new WebProjectSystem(Path.GetTempPath()); + + Assert.True(webProjectSystem.IsBindingRedirectSupported); + } + [Fact] public void ResolvePathReturnsAppCodePathIfPathIsSourceFile() { diff --git a/test/System.Web.WebPages.Administration.Test/packages.config b/test/System.Web.WebPages.Administration.Test/packages.config index 84e222124..b4231b31d 100644 --- a/test/System.Web.WebPages.Administration.Test/packages.config +++ b/test/System.Web.WebPages.Administration.Test/packages.config @@ -1,14 +1,16 @@  - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.WebPages.Deployment.Test/App.Config b/test/System.Web.WebPages.Deployment.Test/App.Config index 49cc43e1d..9fcf237fe 100644 --- a/test/System.Web.WebPages.Deployment.Test/App.Config +++ b/test/System.Web.WebPages.Deployment.Test/App.Config @@ -1,3 +1,19 @@ - + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.WebPages.Deployment.Test/AssemblyUtilsTest.cs b/test/System.Web.WebPages.Deployment.Test/AssemblyUtilsTest.cs index c0db5b44a..e065db2eb 100644 --- a/test/System.Web.WebPages.Deployment.Test/AssemblyUtilsTest.cs +++ b/test/System.Web.WebPages.Deployment.Test/AssemblyUtilsTest.cs @@ -267,7 +267,7 @@ public void GetMatchingAssembliesReturnsReferencingAssemblyAndWebPagesVersionFor var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences); // Assert - Assert.Equal(1, referencedAssemblies.Count); + Assert.Single(referencedAssemblies); Assert.Equal(@"x:\site\bin\B.dll", referencedAssemblies.Single().Key); Assert.Equal(new Version("1.0.0.0"), referencedAssemblies.Single().Value); } @@ -299,7 +299,7 @@ public void GetMatchingAssembliesFiltersWebPagesVersionsThatMatch() var referencedAssemblies = AssemblyUtils.GetAssembliesMatchingOtherVersions(assemblyReferences); // Assert - Assert.Equal(1, referencedAssemblies.Count); + Assert.Single(referencedAssemblies); Assert.Equal(@"x:\site\bin\C.dll", referencedAssemblies.Single().Key); Assert.Equal(new Version("1.2.0.0"), referencedAssemblies.Single().Value); } diff --git a/test/System.Web.WebPages.Deployment.Test/System.Web.WebPages.Deployment.Test.csproj b/test/System.Web.WebPages.Deployment.Test/System.Web.WebPages.Deployment.Test.csproj index 1134691fb..5d68c0aa5 100644 --- a/test/System.Web.WebPages.Deployment.Test/System.Web.WebPages.Deployment.Test.csproj +++ b/test/System.Web.WebPages.Deployment.Test/System.Web.WebPages.Deployment.Test.csproj @@ -1,7 +1,7 @@  - - + + {268DEE9D-F323-4A00-8ED8-3784388C3E3A} @@ -18,19 +18,19 @@ - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -84,16 +84,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.WebPages.Deployment.Test/packages.config b/test/System.Web.WebPages.Deployment.Test/packages.config index 38edc2742..c1e4a6e08 100644 --- a/test/System.Web.WebPages.Deployment.Test/packages.config +++ b/test/System.Web.WebPages.Deployment.Test/packages.config @@ -1,11 +1,11 @@  - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.WebPages.Razor.Test/System.Web.WebPages.Razor.Test.csproj b/test/System.Web.WebPages.Razor.Test/System.Web.WebPages.Razor.Test.csproj index de53f1f81..176588053 100644 --- a/test/System.Web.WebPages.Razor.Test/System.Web.WebPages.Razor.Test.csproj +++ b/test/System.Web.WebPages.Razor.Test/System.Web.WebPages.Razor.Test.csproj @@ -1,7 +1,7 @@  - - + + {66A74F3C-A106-4C1E-BAA0-001908FEA2CA} @@ -23,32 +23,40 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -80,16 +88,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.WebPages.Razor.Test/app.config b/test/System.Web.WebPages.Razor.Test/app.config index 0ee03fcb9..9d8e140df 100644 --- a/test/System.Web.WebPages.Razor.Test/app.config +++ b/test/System.Web.WebPages.Razor.Test/app.config @@ -18,4 +18,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.WebPages.Razor.Test/packages.config b/test/System.Web.WebPages.Razor.Test/packages.config index b06fb5e7a..842db1984 100644 --- a/test/System.Web.WebPages.Razor.Test/packages.config +++ b/test/System.Web.WebPages.Razor.Test/packages.config @@ -1,13 +1,15 @@  - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/test/System.Web.WebPages.Test/App.config b/test/System.Web.WebPages.Test/App.config index 0f0603365..d1f1a9c3d 100644 --- a/test/System.Web.WebPages.Test/App.config +++ b/test/System.Web.WebPages.Test/App.config @@ -1,9 +1,9 @@ - + - + @@ -11,7 +11,27 @@ - + + + + + + + + + + + + + + + + + + + + + diff --git a/test/System.Web.WebPages.Test/ApplicationParts/ApplicationPartTest.cs b/test/System.Web.WebPages.Test/ApplicationParts/ApplicationPartTest.cs index 742da8aee..fa82487bd 100644 --- a/test/System.Web.WebPages.Test/ApplicationParts/ApplicationPartTest.cs +++ b/test/System.Web.WebPages.Test/ApplicationParts/ApplicationPartTest.cs @@ -70,7 +70,7 @@ public void GetResourceNameFromVirtualPathForTopLevelPath() var moduleName = "my-module"; var path = "foo.baz"; - // Act + // Act var name = ApplicationPart.GetResourceNameFromVirtualPath(moduleName, path); // Assert @@ -84,7 +84,7 @@ public void GetResourceNameFromVirtualPathForItemInSubDir() var moduleName = "my-module"; var path = "/bar/foo"; - // Act + // Act var name = ApplicationPart.GetResourceNameFromVirtualPath(moduleName, path); // Assert @@ -98,7 +98,7 @@ public void GetResourceNameFromVirtualPathForItemWithSpaces() var moduleName = "my-module"; var path = "/program files/data files/my file .foo"; - // Act + // Act var name = ApplicationPart.GetResourceNameFromVirtualPath(moduleName, path); // Assert @@ -117,7 +117,7 @@ public void GetResourceVirtualPathForTopLevelItem() var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path); // Assert - Assert.Equal(virtualPath, "~/r.ashx/" + moduleName + "/" + "foo.txt"); + Assert.Equal("~/r.ashx/" + moduleName + "/" + "foo.txt", virtualPath); } [Fact] @@ -132,7 +132,7 @@ public void GetResourceVirtualPathForTopLevelItemAndModuleRootWithTrailingSlash( var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path); // Assert - Assert.Equal(virtualPath, "~/r.ashx/" + moduleName + "/" + "foo.txt"); + Assert.Equal("~/r.ashx/" + moduleName + "/" + "foo.txt", virtualPath); } [Fact] @@ -147,7 +147,7 @@ public void GetResourceVirtualPathForTopLevelItemAndNestedModuleRootPath() var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path); // Assert - Assert.Equal(virtualPath, "~/r.ashx/" + moduleName + "/" + "foo.txt"); + Assert.Equal("~/r.ashx/" + moduleName + "/" + "foo.txt", virtualPath); } [Fact] @@ -162,7 +162,7 @@ public void GetResourceVirtualPathEncodesModuleName() var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path); // Assert - Assert.Equal(virtualPath, "~/r.ashx/" + "Debugger%20Package%20v?&%" + "/" + "foo.txt"); + Assert.Equal("~/r.ashx/" + "Debugger%20Package%20v?&%" + "/" + "foo.txt", virtualPath); } [Fact] @@ -178,7 +178,7 @@ public void GetResourceVirtualPathForNestedItemPath() var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path); // Assert - Assert.Equal(virtualPath, "~/r.ashx/" + moduleName + "/" + itemPath); + Assert.Equal("~/r.ashx/" + moduleName + "/" + itemPath, virtualPath); } [Fact] @@ -194,7 +194,7 @@ public void GetResourceVirtualPathForItemPathWithParameters() var virtualPath = ApplicationPart.GetResourceVirtualPath(moduleName, moduleRoot, path); // Assert - Assert.Equal(virtualPath, "~/r.ashx/" + moduleName + "/" + itemPath); + Assert.Equal("~/r.ashx/" + moduleName + "/" + itemPath, virtualPath); } } } diff --git a/test/System.Web.WebPages.Test/ApplicationParts/ResourceHandlerTest.cs b/test/System.Web.WebPages.Test/ApplicationParts/ResourceHandlerTest.cs index bec2fb97c..c679afb29 100644 --- a/test/System.Web.WebPages.Test/ApplicationParts/ResourceHandlerTest.cs +++ b/test/System.Web.WebPages.Test/ApplicationParts/ResourceHandlerTest.cs @@ -29,7 +29,7 @@ public void ResourceHandlerWritesContentsOfFileToStream() // Assert response.Verify(); - Assert.Equal(Encoding.Default.GetString(stream.ToArray()), _fileContent); + Assert.Equal(_fileContent, Encoding.Default.GetString(stream.ToArray())); } [Fact] diff --git a/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMaxLengthRuleTest.cs b/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMaxLengthRuleTest.cs index 02c0e8193..917868272 100644 --- a/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMaxLengthRuleTest.cs +++ b/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMaxLengthRuleTest.cs @@ -14,7 +14,7 @@ public void ModelClientValidationMaxLengthRuleTestAddsMaxLengthParameter() var clientValidationRule = new ModelClientValidationMaxLengthRule("Max length error message", 8); // Assert - Assert.Equal(1, clientValidationRule.ValidationParameters.Count); + Assert.Single(clientValidationRule.ValidationParameters); Assert.Equal(8, clientValidationRule.ValidationParameters["max"]); Assert.Equal("Max length error message", clientValidationRule.ErrorMessage); } diff --git a/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMinLengthRuleTest.cs b/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMinLengthRuleTest.cs index 3f01d296a..fdb1b7d6b 100644 --- a/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMinLengthRuleTest.cs +++ b/test/System.Web.WebPages.Test/Mvc/ModelClientValidationMinLengthRuleTest.cs @@ -14,7 +14,7 @@ public void ModelClientValidationMinLengthRuleTestAddsMinLengthParameter() var clientValidationRule = new ModelClientValidationMinLengthRule("Min Length message", 2); // Assert - Assert.Equal(1, clientValidationRule.ValidationParameters.Count); + Assert.Single(clientValidationRule.ValidationParameters); Assert.Equal(2, clientValidationRule.ValidationParameters["min"]); Assert.Equal("Min Length message", clientValidationRule.ErrorMessage); } diff --git a/test/System.Web.WebPages.Test/Mvc/ModelClientValidationStringLengthRuleTest.cs b/test/System.Web.WebPages.Test/Mvc/ModelClientValidationStringLengthRuleTest.cs index a491ea3d9..e77290ec7 100644 --- a/test/System.Web.WebPages.Test/Mvc/ModelClientValidationStringLengthRuleTest.cs +++ b/test/System.Web.WebPages.Test/Mvc/ModelClientValidationStringLengthRuleTest.cs @@ -14,7 +14,7 @@ public void ModelClientValidationStringLengthRuleTestDoesNotAddMinLengthParamete var clientValidationRule = new ModelClientValidationStringLengthRule("Test message", 0, 10); // Assert - Assert.Equal(1, clientValidationRule.ValidationParameters.Count); + Assert.Single(clientValidationRule.ValidationParameters); Assert.Equal(10, clientValidationRule.ValidationParameters["max"]); } @@ -25,7 +25,7 @@ public void ModelClientValidationStringLengthRuleTestDoesNotAddMaxLengthIfSpecif var clientValidationRule = new ModelClientValidationStringLengthRule("Test message", 3, Int32.MaxValue); // Assert - Assert.Equal(1, clientValidationRule.ValidationParameters.Count); + Assert.Single(clientValidationRule.ValidationParameters); Assert.Equal(3, clientValidationRule.ValidationParameters["min"]); } diff --git a/test/System.Web.WebPages.Test/Mvc/TagBuilderTest.cs b/test/System.Web.WebPages.Test/Mvc/TagBuilderTest.cs index 10257fbb0..a94cbfc45 100644 --- a/test/System.Web.WebPages.Test/Mvc/TagBuilderTest.cs +++ b/test/System.Web.WebPages.Test/Mvc/TagBuilderTest.cs @@ -288,7 +288,7 @@ public void MergeAttributesWithNullAttributesDoesNothing() builder.MergeAttributes(null); // Assert - Assert.Equal(0, builder.Attributes.Count); + Assert.Empty(builder.Attributes); } [Fact] diff --git a/test/System.Web.WebPages.Test/System.Web.WebPages.Test.csproj b/test/System.Web.WebPages.Test/System.Web.WebPages.Test.csproj index a1df66006..0d9a7d34f 100644 --- a/test/System.Web.WebPages.Test/System.Web.WebPages.Test.csproj +++ b/test/System.Web.WebPages.Test/System.Web.WebPages.Test.csproj @@ -1,7 +1,7 @@  - - + + {0F4870DB-A799-4DBA-99DF-0D74BB52FEC2} @@ -14,13 +14,14 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll + True @@ -29,21 +30,29 @@ 3.5 + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -183,16 +192,16 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - + \ No newline at end of file diff --git a/test/System.Web.WebPages.Test/Utils/TypeHelperTest.cs b/test/System.Web.WebPages.Test/Utils/TypeHelperTest.cs index 18ffc65f3..e59470e97 100644 --- a/test/System.Web.WebPages.Test/Utils/TypeHelperTest.cs +++ b/test/System.Web.WebPages.Test/Utils/TypeHelperTest.cs @@ -17,7 +17,7 @@ public void ObjectToDictionaryWithNullObjectReturnsEmptyDictionary() IDictionary dictValues = TypeHelper.ObjectToDictionary(dict); Assert.NotNull(dictValues); - Assert.Equal(0, dictValues.Count); + Assert.Empty(dictValues); } [Fact] @@ -31,7 +31,7 @@ public void ObjectToDictionaryWithPlainObjectTypeReturnsEmptyDictionary() // Assert Assert.NotNull(dictValues); - Assert.Equal(0, dictValues.Count); + Assert.Empty(dictValues); } [Fact] @@ -45,7 +45,7 @@ public void ObjectToDictionaryWithPrimitiveTypeLooksUpPublicProperties() // Assert Assert.NotNull(dictValues); - Assert.Equal(1, dictValues.Count); + Assert.Single(dictValues); Assert.Equal(4, dictValues["Length"]); } diff --git a/test/System.Web.WebPages.Test/Validation/ValidationHelperTest.cs b/test/System.Web.WebPages.Test/Validation/ValidationHelperTest.cs index 6282ee4fc..a71025d17 100644 --- a/test/System.Web.WebPages.Test/Validation/ValidationHelperTest.cs +++ b/test/System.Web.WebPages.Test/Validation/ValidationHelperTest.cs @@ -19,8 +19,8 @@ public class ValidationHelperTest : IDisposable public void FormFieldKeyIsCommonToModelStateAndValidationHelper() { // Arrange + const string key = "_FORM"; RequestFieldValidatorBase.IgnoreUseUnvalidatedValues = true; - string key = "_FORM"; ValidationHelper validationHelper = GetValidationHelper(GetContext()); // Act and Assert diff --git a/test/System.Web.WebPages.Test/WebPage/PageDataDictionaryTest.cs b/test/System.Web.WebPages.Test/WebPage/PageDataDictionaryTest.cs index 776c5f2a0..4eebf0ab8 100644 --- a/test/System.Web.WebPages.Test/WebPage/PageDataDictionaryTest.cs +++ b/test/System.Web.WebPages.Test/WebPage/PageDataDictionaryTest.cs @@ -45,7 +45,7 @@ public void ClearTest() var d = new PageDataDictionary(); d.Add("x", 2); d.Clear(); - Assert.Equal(0, d.Data.Count); + Assert.Empty(d.Data); } [Fact] @@ -54,9 +54,9 @@ public void ContainsTest() var d = new PageDataDictionary(); var item = new KeyValuePair("x", 1); d.Add(item); - Assert.Contains(item, d); + Assert.Contains>(item, d); var item2 = new KeyValuePair("y", 2); - Assert.DoesNotContain(item2, d); + Assert.DoesNotContain>(item2, d); } [Fact] @@ -106,9 +106,9 @@ public void RemoveTest1() var d = new PageDataDictionary(); var item = new KeyValuePair("x", 2); d.Add(item); - Assert.Contains(item, d); + Assert.Contains>(item, d); d.Remove(item); - Assert.DoesNotContain(item, d); + Assert.DoesNotContain>(item, d); } [Fact] diff --git a/test/System.Web.WebPages.Test/WebPage/TemplateStackTest.cs b/test/System.Web.WebPages.Test/WebPage/TemplateStackTest.cs index 513a012b4..19489f2aa 100644 --- a/test/System.Web.WebPages.Test/WebPage/TemplateStackTest.cs +++ b/test/System.Web.WebPages.Test/WebPage/TemplateStackTest.cs @@ -19,7 +19,7 @@ public void GetCurrentContextReturnsNullWhenStackIsEmpty() var template = TemplateStack.GetCurrentTemplate(httpContext); // Assert - Assert.Equal(1, httpContext.Items.Count); + Assert.Single(httpContext.Items); Assert.Null(template); } diff --git a/test/System.Web.WebPages.Test/packages.config b/test/System.Web.WebPages.Test/packages.config index b06fb5e7a..842db1984 100644 --- a/test/System.Web.WebPages.Test/packages.config +++ b/test/System.Web.WebPages.Test/packages.config @@ -1,13 +1,15 @@  - - - - - - - - - - + + + + + + + + + + + + \ No newline at end of file diff --git a/test/WebApiHelpPage.Test/WebApiHelpPage.Test.csproj b/test/WebApiHelpPage.Test/WebApiHelpPage.Test.csproj index 9037354ab..d2aebf501 100644 --- a/test/WebApiHelpPage.Test/WebApiHelpPage.Test.csproj +++ b/test/WebApiHelpPage.Test/WebApiHelpPage.Test.csproj @@ -1,7 +1,7 @@  - - + + {291EF478-BF24-4935-BC78-E0DCCD0C9A1B} @@ -15,16 +15,16 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -33,7 +33,15 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + @@ -41,19 +49,19 @@ - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -77,7 +85,6 @@ - Designer @@ -137,23 +144,23 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - - + \ No newline at end of file diff --git a/test/WebApiHelpPage.Test/app.config b/test/WebApiHelpPage.Test/app.config deleted file mode 100644 index 195db1f42..000000000 --- a/test/WebApiHelpPage.Test/app.config +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/test/WebApiHelpPage.Test/packages.config b/test/WebApiHelpPage.Test/packages.config index 9fa54ca17..6dbbddd09 100644 --- a/test/WebApiHelpPage.Test/packages.config +++ b/test/WebApiHelpPage.Test/packages.config @@ -1,15 +1,17 @@  - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/WebApiHelpPage.VB.Test/WebApiHelpPage.VB.Test.csproj b/test/WebApiHelpPage.VB.Test/WebApiHelpPage.VB.Test.csproj index c77de5310..51bede45f 100644 --- a/test/WebApiHelpPage.VB.Test/WebApiHelpPage.VB.Test.csproj +++ b/test/WebApiHelpPage.VB.Test/WebApiHelpPage.VB.Test.csproj @@ -1,7 +1,7 @@  - - + + {41D5691F-2720-44A0-9185-EEFE928D2679} @@ -15,16 +15,16 @@ - - ..\..\packages\Castle.Core.4.2.1\lib\net45\Castle.Core.dll + + ..\..\packages\Castle.Core.5.2.1\lib\net462\Castle.Core.dll True - - ..\..\packages\Moq.4.7.142\lib\net45\Moq.dll + + ..\..\packages\Moq.4.21.0\lib\net462\Moq.dll True - - ..\..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll + + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll True @@ -33,7 +33,15 @@ + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll + True + + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + True + @@ -41,19 +49,19 @@ - ..\..\packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll + ..\..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll True - - ..\..\packages\xunit.assert.2.3.0\lib\netstandard1.1\xunit.assert.dll + + ..\..\packages\xunit.assert.2.9.3\lib\netstandard1.1\xunit.assert.dll True - - ..\..\packages\xunit.extensibility.core.2.3.0\lib\netstandard1.1\xunit.core.dll + + ..\..\packages\xunit.extensibility.core.2.9.3\lib\net452\xunit.core.dll True - - ..\..\packages\xunit.extensibility.execution.2.3.0\lib\net452\xunit.execution.desktop.dll + + ..\..\packages\xunit.extensibility.execution.2.9.3\lib\net452\xunit.execution.desktop.dll True @@ -108,9 +116,6 @@ - - app.config - packages.config Designer @@ -171,19 +176,19 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + - - - 5 + + 9.0 true diff --git a/tools/WebStack.tasks.targets b/tools/WebStack.tasks.targets index fbebe6774..038a3af68 100644 --- a/tools/WebStack.tasks.targets +++ b/tools/WebStack.tasks.targets @@ -30,6 +30,7 @@ if (!Version.TryParse(MinimumVersion, out minimumRequiredVersion)) { Log.LogError("MinimumVersion '{0}' is not a valid Version.", MinimumVersion); + return false; } try @@ -47,6 +48,11 @@ if (versionInfo != null && versionInfo.ProductVersion != null) { toParse = versionInfo.ProductVersion; + int index = toParse.IndexOfAny(new[] {'-', '+'}); + if (index > 0) + { + toParse = toParse.Substring(0, index); + } } else { @@ -74,7 +80,7 @@ if (!File.Exists(OutputFileName)) { - Log.LogMessage("Downloading latest version of NuGet.exe..."); + Log.LogMessage(MessageImportance.High, "Downloading latest version of NuGet.exe..."); WebClient webClient = new WebClient(); webClient.DownloadFile("https://dist.nuget.org/win-x86-commandline/latest/nuget.exe", OutputFileName); } @@ -91,58 +97,6 @@ - - - - - - - - - - - - - - - - - - - - @@ -154,13 +108,18 @@ + + + + [0-9A-Fa-f]+);", + RegexOptions.Multiline | RegexOptions.Compiled); int testsPassed = 0; int testsFailed = 0; int testsSkipped = 0; @@ -169,8 +128,20 @@ foreach (string testResultFile in testResultFiles) { + // Replace potentially illegal escaped characters (if they get through validations done during Save). + string fullPath = Path.GetFullPath(testResultFile); + string originalText = File.ReadAllText(fullPath); + bool matched = regex.IsMatch(originalText); + + if (matched) + { + File.SetAttributes(fullPath, File.GetAttributes(fullPath) & ~FileAttributes.ReadOnly); + File.WriteAllText(fullPath, regex.Replace(originalText, "\\x${char}"), Encoding.UTF8); + } + + // Collect test failure information from results file. XElement xml; - using (FileStream fileStream = File.OpenRead(testResultFile)) + using (FileStream fileStream = File.OpenRead(fullPath)) { xml = XElement.Load(fileStream); } @@ -213,23 +184,32 @@ } } + // Log all test failures. if (testFailures.Count > 0) { - Console.WriteLine(); - Console.WriteLine(" Test Failures:"); - ConsoleColor originalColor = Console.ForegroundColor; - Console.ForegroundColor = ConsoleColor.Red; + Log.LogMessage(MessageImportance.High, string.Empty); + Log.LogError("Tests failed..."); foreach (string testFailure in testFailures) { - Console.WriteLine(" " + testFailure); + // Provide the list of failed tests but don't repeat it in the build summary. List + // is usually less helpful than errors from tests themselves (which are repeated) + // because those errors include the exact failure locations. On the other hand, + // this is more compact. + Log.LogMessage(MessageImportance.High, testFailure); } - Console.ForegroundColor = originalColor; } - Console.WriteLine(); - Console.WriteLine(" Tests passed: {0}, Tests failed: {1}, Tests skipped: {2}", testsPassed, testsFailed, testsSkipped); - Console.WriteLine(" Time spent running tests: {0} seconds", timeSpent); - return true; + // Log summary of all results. + Log.LogMessage(MessageImportance.High, string.Empty); + Log.LogMessage(MessageImportance.High, + "Tests passed: {0}, Tests failed: {1}, Tests skipped: {2}", + testsPassed, + testsFailed, + testsSkipped); + Log.LogMessage(MessageImportance.High, + "Time spent running tests: {0} seconds", timeSpent); + + return !Log.HasLoggedErrors; } catch (Exception ex) { @@ -240,4 +220,4 @@ - \ No newline at end of file + diff --git a/tools/WebStack.testing.targets b/tools/WebStack.testing.targets new file mode 100644 index 000000000..9a134d52b --- /dev/null +++ b/tools/WebStack.testing.targets @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + <_ExitCodes Include="$(TestAssembly)" Code="$(_ExitCode)" /> + + + diff --git a/tools/WebStack.xunit.targets b/tools/WebStack.xunit.targets deleted file mode 100644 index 3392c1dde..000000000 --- a/tools/WebStack.xunit.targets +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/tools/src/Microsoft.Web.FxCop/Microsoft.Web.FxCop.csproj b/tools/src/Microsoft.Web.FxCop/Microsoft.Web.FxCop.csproj index d4a4451c7..2fc7c9bb4 100644 --- a/tools/src/Microsoft.Web.FxCop/Microsoft.Web.FxCop.csproj +++ b/tools/src/Microsoft.Web.FxCop/Microsoft.Web.FxCop.csproj @@ -10,7 +10,8 @@ Properties Microsoft.Web.FxCop Microsoft.Web.FxCop - v4.0 + + v4.7.2 bin\$(Configuration) diff --git a/tools/vslicense/dotnet-library-license.htm b/tools/vslicense/dotnet-library-license.htm new file mode 100644 index 000000000..902081889 --- /dev/null +++ b/tools/vslicense/dotnet-library-license.htm @@ -0,0 +1,476 @@ + + + + + + + +
    +

    MICROSOFT SOFTWARE LICENSE TERMS

    +
    +

    MICROSOFT .NET LIBRARY

    +
    +

    These license terms are an agreement between you and Microsoft Corporation (or based on where you live, one of its affiliates). They apply to the software named above. The terms also apply + to any Microsoft services or updates for the software, except to the extent those have different terms.

    +
    +

    If you comply with these license terms, you have the rights below.

    +
    +

    +1.    +INSTALLATION AND USE RIGHTS.

    +

    +You may install and use any number of copies of the software +to develop and test your applications.  +

    +

    2.    +THIRD PARTY COMPONENTS. The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices + file(s) accompanying the software.

    +

    3.    +ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.

    +

    a.     +DISTRIBUTABLE CODE.  +The software is comprised of Distributable Code. “Distributable Code” is code that you are permitted to distribute in applications + you develop if you comply with the terms below.

    +

    +i.      +Right to Use and Distribute. +

    +

    +·        +You may copy and distribute the object code form of the software.

    +

    +·        +Third Party Distribution. You may permit distributors of your applications to copy and distribute the Distributable Code as part of those applications.

    +

    +ii.     +Distribution Requirements. For any Distributable Code you distribute, you must

    +

    +·        +use the Distributable Code in your applications and not as a standalone distribution;

    +

    +·        +require distributors and external end users to agree to terms that protect it at least as much as this agreement; and

    +

    +·        +indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your applications, except to the extent + that any claim is based solely on the unmodified Distributable Code.

    +

    +iii.   +Distribution Restrictions. You may not

    +

    +·        +use Microsoft’s trademarks in your applications’ names or in a way that suggests your applications come from or are endorsed by Microsoft; or

    +

    +·        +modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An “Excluded License” is one that requires, + as a condition of use, modification or distribution of code, that (i) it be disclosed or distributed in source code form; or (ii) others have the right to modify it.

    +

    4.    +DATA.

    +

    a.     +Data Collection. The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information + to provide services and improve our products and services.  You may opt-out of many of these scenarios, but not all, as described in the software documentation.  There are also some features in the software that may enable you and + Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with Microsoft’s privacy statement. Our privacy + statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can + learn more about data collection and its use from the software documentation and our privacy statement. Your use of the software operates as your consent to these practices.

    +

    b.    +Processing of Personal Data. +To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the + Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr.

    +

    5.    +Scope of License. The software is licensed, not sold. This agreement only gives you some rights + to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations + in the software that only allow you to use it in certain ways. You may not

    +

    ·        +work around any technical limitations in the software;

    +

    ·        +reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain + open source components that may be included in the software;

    +

    ·        +remove, minimize, block or modify any notices of Microsoft or its suppliers in the software; +

    +

    ·        +use the software in any way that is against the law; or

    +

    ·        +share, publish, rent or lease the software, provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party.

    +

    6.    +Export Restrictions. +You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information + on export restrictions, visit www.microsoft.com/exporting. + 

    +

    7.    +SUPPORT SERVICES. +Because this software is “as is,” we may not provide support services for it.

    +

    8.    +Entire Agreement. This agreement, and the terms for supplements, updates, Internet-based services and support services that you + use, are the entire agreement for the software and support services.

    +

    9.    +Applicable Law.  +If you acquired the software in the United States, Washington law applies to interpretation of and claims for breach of this agreement, and the laws of the state where you live apply to all other claims. + If you acquired the software in any other country, its laws apply.

    +

    10. +CONSUMER RIGHTS; REGIONAL VARIATIONS. +This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state or country. Separate and apart from your relationship with Microsoft, + you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state or country do not permit it to do so. For example, if you acquired the software in one of the + below regions, or mandatory country law applies, then the following provisions apply to you:

    +

    a)    +Australia. You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights.

    +

    b)    +Canada. If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from + the Internet (if and when you re-connect to the Internet, however, the software will resume checking for and installing updates), or uninstalling the software. The product documentation, if any, may also specify how to turn off updates for your specific device + or software.

    +

    c)    +Germany and Austria.

    +

    (i)        +Warranty. The software will perform substantially as described in any Microsoft materials that accompany it. However, Microsoft gives no contractual guarantee in relation to the software.

    +

    (ii)       +Limitation of Liability. In case of intentional conduct, gross negligence, claims based on the Product Liability Act, as well as in case of death or personal or physical injury, Microsoft is liable according to the statutory law.

    +

    Subject to the foregoing clause (ii), Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, + the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of + slight negligence, Microsoft will not be liable for slight negligence

    +

    11. +Disclaimer of Warranty. THE SOFTWARE IS LICENSED “AS-IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. + TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. +

    +

    12. +Limitation on and Exclusion of Remedies and Damages. +YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.

    +

    This limitation applies to (a) anything related to the software, services, content (including code) on third party Internet sites, or third party applications; and (b) claims for breach of contract, breach of + warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law.

    +

    It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state or country + may not allow the exclusion or limitation of incidental, consequential or other damages.

    +

     

    +
    + + diff --git a/tools/vslicense/dotnet-library-license.md b/tools/vslicense/dotnet-library-license.md new file mode 100644 index 000000000..18a6fd30c --- /dev/null +++ b/tools/vslicense/dotnet-library-license.md @@ -0,0 +1,87 @@ +**MICROSOFT SOFTWARE LICENSE TERMS** + +**MICROSOFT .NET LIBRARY** + +------------------------------------------------------------------------------ +These license terms are an agreement between you and Microsoft Corporation (or based on where you live, one of its affiliates). They apply to the software named above. The terms also apply to any Microsoft services or updates for the software, except to the extent those have different terms. + +------------------------------------------------------------------------------ +**IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW.** + +**1. INSTALLATION AND USE RIGHTS.** + +> You may install and use any number of copies of the software to develop and test your applications. + +**2. THIRD PARTY COMPONENTS.** The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file(s) accompanying the software. + +**3. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.** + +> **a. DISTRIBUTABLE CODE.** The software is comprised of Distributable Code. "Distributable Code" is code that you are permitted to distribute in applications you develop if you comply with the terms below. + +>> **i. Right to Use and Distribute.** + +>> - You may copy and distribute the object code form of the software. + +>> - Third Party Distribution. You may permit distributors of your applications to copy and distribute the Distributable Code as part of those applications. + +>> **ii. Distribution Requirements. For any Distributable Code you distribute, you must** + +>> - use the Distributable Code in your applications and not as a standalone distribution; + +>> - require distributors and external end users to agree to terms that protect it at least as much as this agreement; and + +>> - indemnify, defend, and hold harmless Microsoft from any claims, including attorneys' fees, related to the distribution or use of your applications, except to the extent that any claim is based solely on the unmodified Distributable Code. + +>> **iii. Distribution Restrictions. You may not** + +>> - use Microsoft's trademarks in your applications' names or in a way that suggests your applications come from or are endorsed by Microsoft; or + +>> - modify or distribute the source code of any Distributable Code so that any part of it becomes subject to an Excluded License. An "Excluded License" is one that requires, as a condition of use, modification or distribution of code, that (i) it be disclosed or distributed in source code form; or (ii) others have the right to modify it. + +**4. DATA.** + +> **a. Data Collection.** The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may opt-out of many of these scenarios, but not all, as described in the software documentation. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and its use from the software documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +> **b. Processing of Personal Data.** To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr. + +**5. SCOPE OF LICENSE.** The software is licensed, not sold. This agreement only gives you some rights to use the software. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you may use the software only as expressly permitted in this agreement. In doing so, you must comply with any technical limitations in the software that only allow you to use it in certain ways. You may not + +> - work around any technical limitations in the software; + +> - reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the software; + +> - remove, minimize, block or modify any notices of Microsoft or its suppliers in the software; + +> - use the software in any way that is against the law; or + +> - share, publish, rent or lease the software, provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party. + +**6. EXPORT RESTRICTIONS.** You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit www.microsoft.com/exporting. + +**7. SUPPORT SERVICES.** Because this software is "as is", we may not provide support services for it. + +**8. ENTIRE AGREEMENT.** This agreement, and the terms for supplements, updates, Internet-based services and support services that you use, are the entire agreement for the software and support services. + +**9. APPLICABLE LAW.** If you acquired the software in the United States, Washington law applies to interpretation of and claims for breach of this agreement, and the laws of the state where you live apply to all other claims. If you acquired the software in any other country, its laws apply. + +**10. CONSUMER RIGHTS; REGIONAL VARIATIONS.** This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you: + +> **a) Australia.** You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights. + +> **b) Canada.** If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from the Internet (if and when you re-connect to the Internet, however, the software will resume checking for and installing updates), or uninstalling the software. The product documentation, if any, may also specify how to turn off updates for your specific device or software. + +> **c) Germany and Austria.** + +>> **(i) Warranty.** The software will perform substantially as described in any Microsoft materials that accompany it. However, Microsoft gives no contractual guarantee in relation to the software. + +>> **(ii) Limitation of Liability.** In case of intentional conduct, gross negligence, claims based on the Product Liability Act, as well as in case of death or personal or physical injury, Microsoft is liable according to the statutory law. + +> Subject to the foregoing clause (ii), Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence + +**11. Disclaimer of Warranty. THE SOFTWARE IS LICENSED "AS-IS". YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES OR CONDITIONS. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS, MICROSOFT EXCLUDES THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.** + +**12. Limitation on and Exclusion of Remedies and Damages. YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES.** + +This limitation applies to (a) anything related to the software, services, content (including code) on third party Internet sites, or third party applications; and (b) claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence, or other tort to the extent permitted by applicable law. + +It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state or country may not allow the exclusion or limitation of incidental, consequential or other damages. \ No newline at end of file